Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/funny-geese-mix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gitbook/cli': patch
---

Validate OpenAPI slug with pattern
2 changes: 1 addition & 1 deletion bun.lock
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@
},
"packages/api": {
"name": "@gitbook/api",
"version": "0.143.2",
"version": "0.145.0",
"dependencies": {
"event-iterator": "^2.0.0",
"eventsource-parser": "^3.0.0",
Expand Down
1 change: 1 addition & 0 deletions packages/api/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
dist/
spec/
src/client.ts
src/constants.ts
4 changes: 4 additions & 0 deletions packages/api/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ swagger-typescript-api --path ./spec/openapi.yaml --output ./src/ --name client.
# Then we bundle into an importable JSON module
swagger-cli bundle ./spec/openapi.yaml --outfile ./spec/openapi.json --type json

# Then we extract the API constants
echo "Extracting API constants..."
bun ./scripts/extract-constants.ts

# Then we build the JS files
echo "Bundling CJS format from code..."
esbuild ./src/index.ts --bundle --platform=node --format=cjs --outfile=./dist/index.cjs --log-level=warning
Expand Down
76 changes: 76 additions & 0 deletions packages/api/scripts/extract-constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import fs from 'fs';
import path from 'path';

const fileContentPrefix = `/* tslint:disable */
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED ##
* ## ##
* ## See extract-constants.ts for more details ##
* ---------------------------------------------------------------
*/
`;

const inputPath = path.resolve(process.cwd(), 'spec/openapi.json');
const outputPath = path.resolve(process.cwd(), 'src/constants.ts');

const file = await fs.promises.readFile(inputPath, 'utf-8');
const api = JSON.parse(file);
const constants: Record<string, number | string | string[] | number[]> = {};
for (const [schemaName, schema] of Object.entries(api.components.schemas)) {
if (
schema &&
typeof schema === 'object' &&
'maxLength' in schema &&
typeof schema.maxLength === 'number'
) {
constants[formatKey(schemaName, 'maxLength')] = schema.maxLength;
}

if (
schema &&
typeof schema === 'object' &&
'minLength' in schema &&
typeof schema.minLength === 'number'
) {
constants[formatKey(schemaName, 'minLength')] = schema.minLength;
}

if (
schema &&
typeof schema === 'object' &&
'pattern' in schema &&
typeof schema.pattern === 'string'
) {
constants[formatKey(schemaName, 'pattern')] = schema.pattern;
}

if (
schema &&
typeof schema === 'object' &&
'enum' in schema &&
Array.isArray(schema.enum) &&
(schema.enum.every((item) => typeof item === 'string') ||
schema.enum.every((item) => typeof item === 'number'))
) {
constants[formatKey(schemaName, 'enum')] = schema.enum;
}
}
const constantLines = Object.entries(constants)
.map(([key, value]) => {
if (Array.isArray(value)) {
return `export const ${key}:${JSON.stringify(value)} = ${JSON.stringify(value)};`;
}
return `export const ${key} = ${JSON.stringify(value)};`;
})
.join('\n');

await fs.promises.writeFile(outputPath, `${fileContentPrefix}\n${constantLines}`);

function formatKey(schemaName: string, key: string) {
return convertCamelToSnake(`${schemaName}_${key}`);
}

function convertCamelToSnake(str: string) {
return str.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
}
1 change: 1 addition & 0 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Api } from './client';
import { GitBookAPIError } from './GitBookAPIError';

export * from './client';
export * from './constants';
export { GitBookAPIError };

export const GITBOOK_DEFAULT_ENDPOINT = 'https://api.gitbook.com';
Expand Down
52 changes: 34 additions & 18 deletions packages/cli/src/openapi/publish.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import * as fs from 'fs';
import * as path from 'path';

import * as api from '@gitbook/api';
import { getAPIClient } from '../remote';

Expand All @@ -22,16 +20,13 @@ export async function publishOpenAPISpecificationFromURL(args: {
*/
url: string;
}): Promise<api.OpenAPISpec> {
const slug = validateSlug(args.specSlug);
const api = await getAPIClient(true);
const spec = await api.orgs.createOrUpdateOpenApiSpecBySlug(
args.organizationId,
args.specSlug,
{
source: {
url: args.url,
},
const spec = await api.orgs.createOrUpdateOpenApiSpecBySlug(args.organizationId, slug, {
source: {
url: args.url,
},
);
});
return spec.data;
}

Expand All @@ -53,17 +48,14 @@ export async function publishOpenAPISpecificationFromFilepath(args: {
*/
filepath: string;
}): Promise<api.OpenAPISpec> {
const slug = validateSlug(args.specSlug);
const api = await getAPIClient(true);
const fileContent = await readOpenAPIFile(args.filepath);
const spec = await api.orgs.createOrUpdateOpenApiSpecBySlug(
args.organizationId,
args.specSlug,
{
source: {
text: fileContent,
},
const spec = await api.orgs.createOrUpdateOpenApiSpecBySlug(args.organizationId, slug, {
source: {
text: fileContent,
},
);
});
return spec.data;
}

Expand All @@ -81,3 +73,27 @@ async function readOpenAPIFile(filePath: string): Promise<string> {
throw error;
}
}

const OPENAPISPEC_SLUG_REGEX = new RegExp(api.OPEN_APISPEC_SLUG_PATTERN);
/**
* Validate the OpenAPI specification slug.
* It should match the pattern and be between the minimum and maximum length.
*/
function validateSlug(specSlug: string) {
if (!OPENAPISPEC_SLUG_REGEX.test(specSlug)) {
throw new Error(
`Invalid OpenAPI specification slug, must match pattern: ${api.OPEN_APISPEC_SLUG_PATTERN}`,
);
}

if (
specSlug.length < api.OPEN_APISPEC_SLUG_MIN_LENGTH ||
specSlug.length > api.OPEN_APISPEC_SLUG_MAX_LENGTH
) {
throw new Error(
`Invalid OpenAPI specification slug, must be between ${api.OPEN_APISPEC_SLUG_MIN_LENGTH} and ${api.OPEN_APISPEC_SLUG_MAX_LENGTH} characters`,
);
}

return specSlug;
}