@sdk-it/spec 0.46.7 → 0.46.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/pagination/guess-pagination.d.ts +2 -0
- package/dist/lib/pagination/guess-pagination.d.ts.map +1 -1
- package/dist/lib/pagination/guess-pagination.js.map +2 -2
- package/dist/lib/pagination/pagination-result.d.ts +2 -0
- package/dist/lib/pagination/pagination-result.d.ts.map +1 -1
- package/dist/lib/pagination/pagination-result.js +42 -1
- package/dist/lib/pagination/pagination-result.js.map +2 -2
- package/dist/lib/pagination/pagination.d.ts.map +1 -1
- package/dist/lib/pagination/pagination.js +9 -6
- package/dist/lib/pagination/pagination.js.map +2 -2
- package/dist/lib/processing-plugins/enrich-examples.d.ts.map +1 -1
- package/dist/lib/processing-plugins/enrich-examples.js +11 -2
- package/dist/lib/processing-plugins/enrich-examples.js.map +2 -2
- package/dist/lib/processing-plugins/normalize-schemas.js +1 -1
- package/dist/lib/processing-plugins/normalize-schemas.js.map +2 -2
- package/dist/lib/processing.d.ts.map +1 -1
- package/dist/lib/processing.js +2 -1
- package/dist/lib/processing.js.map +2 -2
- package/package.json +9 -8
|
@@ -23,6 +23,8 @@ export interface CursorPaginationResult extends PaginationResultBase {
|
|
|
23
23
|
cursorKeyword: string;
|
|
24
24
|
limitParamName: string;
|
|
25
25
|
limitKeyword: string;
|
|
26
|
+
/** Dot-separated response path containing the next request cursor. */
|
|
27
|
+
nextCursor?: string;
|
|
26
28
|
}
|
|
27
29
|
export interface NoPaginationResult extends PaginationResultBase {
|
|
28
30
|
type: 'none';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guess-pagination.d.ts","sourceRoot":"","sources":["../../../src/lib/pagination/guess-pagination.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,YAAY,EAEb,MAAM,mBAAmB,CAAC;AAM3B,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;A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
|
|
3
3
|
"sources": ["../../../src/lib/pagination/guess-pagination.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n ReferenceObject,\n SchemaObject,\n SchemasObject,\n} from 'openapi3-ts/oas31';\n\nimport { isRef } from '@sdk-it/core/ref.js';\nimport { isEmpty } from '@sdk-it/core/utils.js';\n\nimport { coerceTypes } from '../is.js';\nimport type { TunedOperationObject } from '../types.js';\nimport { getHasMoreName, getItemsName } from './pagination-result.js';\n\ninterface PaginationResultBase {\n type: 'offset' | 'page' | 'cursor' | 'none';\n}\n\nexport interface OffsetPaginationResult extends PaginationResultBase {\n type: 'offset';\n offsetParamName: string;\n offsetKeyword: string; // The actual part of param name that matched\n limitParamName: string;\n limitKeyword: string; // The actual part of param name that matched\n}\n\nexport interface PagePaginationResult extends PaginationResultBase {\n type: 'page';\n pageNumberParamName: string;\n pageNumberKeyword: string;\n pageSizeParamName: string;\n pageSizeKeyword: string;\n}\n\nexport interface CursorPaginationResult extends PaginationResultBase {\n type: 'cursor';\n cursorParamName: string;\n cursorKeyword: string;\n limitParamName: string;\n limitKeyword: string;\n}\n\nexport interface NoPaginationResult extends PaginationResultBase {\n type: 'none';\n reason: string;\n}\n\nexport type PaginationGuess =\n | ((\n OffsetPaginationResult | PagePaginationResult | CursorPaginationResult\n ) & { items: string; hasMore: string })\n | NoPaginationResult;\n\n// --- Keyword Regex Definitions ---\n\nexport const OFFSET_PARAM_REGEXES: RegExp[] = [\n /\\boffset\\b/i,\n /\\bskip\\b/i,\n /\\bstart(?:ing_at|_index)?\\b/i, // e.g., start, starting_at, start_index\n /\\bfrom\\b/i,\n];\n\nexport const GENERIC_LIMIT_PARAM_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\b(?:page_?)?size\\b/i, // e.g., size, page_size, pagesize\n /\\bmax_results\\b/i,\n /\\bnum_results\\b/i,\n /\\bshow\\b/i, // Can sometimes mean limit\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\btake\\b/i,\n];\n\nexport const PAGE_NUMBER_REGEXES: RegExp[] = [\n // /^(currentPage)?page$/i, // Exact match for \"page\"\n // /^currentPage$/i, // Exact match for \"currentPage\"\n /^p$/i, // Exact match for \"p\" (common shorthand)\n // /\\bpage_?(?:number|no|num|idx|index)\\b/i, // e.g., page_number, pageNumber, page_num, page_idx\n /^(current)?_?page(_?)(?:number|no|num|idx|index)?\\b/i,\n];\n\n// Regexes for parameters indicating page size (when used with page number)\nexport const PAGE_SIZE_REGEXES: RegExp[] = [\n /\\bpage_?size\\b/i, // e.g., page_size, pagesize\n /^size$/i, // Exact \"size\"\n // /\\bsize\\b/i, // Broader \"size\" - can be ambiguous, prefer more specific ones first\n /\\blimit\\b/i, // Limit is often used for page size\n /\\bcount\\b/i, // Count can also be used for page size\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items, numitems\n /\\bresults_?per_?page\\b/i,\n];\n\n// Regexes for parameters indicating a cursor\nexport const CURSOR_REGEXES: RegExp[] = [\n /\\bmarker\\b/i,\n /\\bcursor\\b/i,\n /\\bafter(?:_?cursor)?\\b/i, // e.g., after, after_cursor\n /\\bbefore(?:_?cursor)?\\b/i, // e.g., before, before_cursor\n /\\b(next|prev|previous)_?(?:page_?)?token\\b/i, // e.g., next_page_token, nextPageToken, prev_token\n /\\b(next|prev|previous)_?cursor\\b/i, // e.g., next_cursor, previousCursor\n /\\bcontinuation(?:_?token)?\\b/i, // e.g., continuation, continuation_token\n /\\bpage(?:_?(token|id))?\\b/i, // e.g., after, after_cursor\n\n /\\bstart_?(?:key|cursor|token|after)\\b/i, // e.g., start_key, startCursor, startToken, startAfter\n];\n\n// Regexes for parameters indicating a limit when used with cursors\nexport const CURSOR_LIMIT_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\bsize\\b/i, // General size\n /\\bfirst\\b/i, // Common in Relay-style cursor pagination (forward pagination)\n /\\blast\\b/i, // Common in Relay-style cursor pagination (backward pagination)\n /\\bpage_?size\\b/i, // Sometimes page_size is used with cursors\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items\n /\\bmax_?items\\b/i,\n /\\btake\\b/i,\n];\n\n// --- Helper Function ---\nfunction findParamAndKeyword(\n queryParams: { name: string }[],\n regexes: RegExp[],\n excludeParamName?: string,\n) {\n for (const param of queryParams) {\n if (param.name === excludeParamName) {\n continue;\n }\n for (const regex of regexes) {\n const match = param.name.match(regex);\n if (match) {\n return { param, keyword: match[0] }; // match[0] is the actual matched substring\n }\n }\n }\n return null;\n}\n\nfunction coerceParameters(\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[],\n) {\n const cleanedParameters: {\n name: string;\n schema: Omit<SchemaObject, 'type'> & {\n type: string[]; // Ensure type is always an array\n };\n }[] = [];\n for (const param of parameters) {\n if (!param.schema) {\n continue;\n }\n if (isRef(param.schema)) {\n continue;\n }\n if (param.schema.anyOf || param.schema.oneOf || param.schema.allOf) {\n const schemas = (\n param.schema.anyOf ||\n param.schema.oneOf ||\n param.schema.allOf ||\n []\n ).filter((it): it is SchemaObject => !isRef(it));\n schemas.forEach((schema) => {\n if (schema.type) {\n cleanedParameters.push({\n ...param,\n schema: {\n ...schema,\n type: coerceTypes(schema),\n },\n });\n }\n });\n continue;\n }\n if (!param.schema.type) {\n continue;\n }\n if (param.schema) {\n cleanedParameters.push({\n ...param,\n schema: {\n ...param.schema,\n type: coerceTypes(param.schema),\n },\n });\n }\n }\n return cleanedParameters;\n}\n\nfunction isOffsetPagination(\n operation: TunedOperationObject,\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[],\n): OffsetPaginationResult | null {\n const params = coerceParameters(parameters).filter(\n (it) =>\n it.schema.type.includes('integer') || it.schema.type.includes('number'),\n );\n\n const offsetMatch = findParamAndKeyword(params, OFFSET_PARAM_REGEXES);\n\n if (!offsetMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n params,\n GENERIC_LIMIT_PARAM_REGEXES,\n offsetMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'offset',\n offsetParamName: offsetMatch.param.name,\n offsetKeyword: offsetMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\nfunction isPagePagination(\n operation: TunedOperationObject,\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[],\n): PagePaginationResult | null {\n const params = coerceParameters(parameters).filter(\n (it) =>\n it.schema.type.includes('integer') || it.schema.type.includes('number'),\n );\n\n if (params.length < 2) return null;\n\n const pageNoMatch = findParamAndKeyword(params, PAGE_NUMBER_REGEXES);\n if (!pageNoMatch) return null;\n\n const pageSizeMatch = findParamAndKeyword(\n params,\n PAGE_SIZE_REGEXES,\n pageNoMatch.param.name,\n );\n if (!pageSizeMatch) return null;\n\n return {\n type: 'page',\n pageNumberParamName: pageNoMatch.param.name,\n pageNumberKeyword: pageNoMatch.keyword,\n pageSizeParamName: pageSizeMatch.param.name,\n pageSizeKeyword: pageSizeMatch.keyword,\n };\n}\n\nfunction isCursorPagination(\n operation: TunedOperationObject,\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[] = [],\n): CursorPaginationResult | null {\n const queryParams = parameters;\n if (queryParams.length < 2) return null; // Need at least a cursor and a limit-like param\n\n const cursorMatch = findParamAndKeyword(queryParams, CURSOR_REGEXES);\n if (!cursorMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n queryParams,\n CURSOR_LIMIT_REGEXES,\n cursorMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'cursor',\n cursorParamName: cursorMatch.param.name,\n cursorKeyword: cursorMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\n/**\n * Guesses the pagination strategy of an OpenAPI operation based on its query parameters.\n * It checks for offset, page-based, and cursor-based pagination in that order.\n *\n * @param operation The OpenAPI operation object.\n * @returns A PaginationGuess object indicating the detected type and relevant parameters.\n */\nexport function guessPagination(\n operation: TunedOperationObject,\n body?: SchemaObject,\n response?: SchemaObject,\n): PaginationGuess {\n const bodyParameters =\n body && body.properties\n ? Object.entries(body.properties).map(([it, schema]) => ({\n name: it,\n schema,\n }))\n : [];\n const parameters = operation.parameters;\n\n if (isEmpty(operation.parameters) && isEmpty(bodyParameters)) {\n return { type: 'none', reason: 'no parameters' };\n }\n if (!response) {\n return { type: 'none', reason: 'no response' };\n }\n if (!response.properties) {\n return { type: 'none', reason: 'empty response' };\n }\n const properties = response.properties as SchemasObject;\n\n const itemsKey = getItemsName(properties);\n if (!itemsKey) {\n return { type: 'none', reason: 'no items key' };\n }\n const hasMoreKey = getHasMoreName(excludeKey(properties, itemsKey));\n\n if (!hasMoreKey) {\n return { type: 'none', reason: 'no hasMore key' };\n }\n const pagination =\n isOffsetPagination(operation, [...parameters, ...bodyParameters]) ||\n isPagePagination(operation, [...parameters, ...bodyParameters]) ||\n isCursorPagination(operation, [...parameters, ...bodyParameters]);\n return pagination\n ? { ...pagination, items: itemsKey, hasMore: hasMoreKey }\n : { type: 'none', reason: 'no pagination' };\n}\n\nfunction excludeKey<T extends Record<string, any>>(\n obj: T,\n key: string,\n): Omit<T, typeof key> {\n const { [key]: _, ...rest } = obj;\n return rest;\n}\n"],
|
|
5
|
-
"mappings": "AAMA,SAAS,aAAa;AACtB,SAAS,eAAe;AAExB,SAAS,mBAAmB;AAE5B,SAAS,gBAAgB,oBAAoB;
|
|
4
|
+
"sourcesContent": ["import type {\n ReferenceObject,\n SchemaObject,\n SchemasObject,\n} from 'openapi3-ts/oas31';\n\nimport { isRef } from '@sdk-it/core/ref.js';\nimport { isEmpty } from '@sdk-it/core/utils.js';\n\nimport { coerceTypes } from '../is.js';\nimport type { TunedOperationObject } from '../types.js';\nimport { getHasMoreName, getItemsName } from './pagination-result.js';\n\ninterface PaginationResultBase {\n type: 'offset' | 'page' | 'cursor' | 'none';\n}\n\nexport interface OffsetPaginationResult extends PaginationResultBase {\n type: 'offset';\n offsetParamName: string;\n offsetKeyword: string; // The actual part of param name that matched\n limitParamName: string;\n limitKeyword: string; // The actual part of param name that matched\n}\n\nexport interface PagePaginationResult extends PaginationResultBase {\n type: 'page';\n pageNumberParamName: string;\n pageNumberKeyword: string;\n pageSizeParamName: string;\n pageSizeKeyword: string;\n}\n\nexport interface CursorPaginationResult extends PaginationResultBase {\n type: 'cursor';\n cursorParamName: string;\n cursorKeyword: string;\n limitParamName: string;\n limitKeyword: string;\n /** Dot-separated response path containing the next request cursor. */\n nextCursor?: string;\n}\n\nexport interface NoPaginationResult extends PaginationResultBase {\n type: 'none';\n reason: string;\n}\n\nexport type PaginationGuess =\n | ((\n OffsetPaginationResult | PagePaginationResult | CursorPaginationResult\n ) & { items: string; hasMore: string })\n | NoPaginationResult;\n\n// --- Keyword Regex Definitions ---\n\nexport const OFFSET_PARAM_REGEXES: RegExp[] = [\n /\\boffset\\b/i,\n /\\bskip\\b/i,\n /\\bstart(?:ing_at|_index)?\\b/i, // e.g., start, starting_at, start_index\n /\\bfrom\\b/i,\n];\n\nexport const GENERIC_LIMIT_PARAM_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\b(?:page_?)?size\\b/i, // e.g., size, page_size, pagesize\n /\\bmax_results\\b/i,\n /\\bnum_results\\b/i,\n /\\bshow\\b/i, // Can sometimes mean limit\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\btake\\b/i,\n];\n\nexport const PAGE_NUMBER_REGEXES: RegExp[] = [\n // /^(currentPage)?page$/i, // Exact match for \"page\"\n // /^currentPage$/i, // Exact match for \"currentPage\"\n /^p$/i, // Exact match for \"p\" (common shorthand)\n // /\\bpage_?(?:number|no|num|idx|index)\\b/i, // e.g., page_number, pageNumber, page_num, page_idx\n /^(current)?_?page(_?)(?:number|no|num|idx|index)?\\b/i,\n];\n\n// Regexes for parameters indicating page size (when used with page number)\nexport const PAGE_SIZE_REGEXES: RegExp[] = [\n /\\bpage_?size\\b/i, // e.g., page_size, pagesize\n /^size$/i, // Exact \"size\"\n // /\\bsize\\b/i, // Broader \"size\" - can be ambiguous, prefer more specific ones first\n /\\blimit\\b/i, // Limit is often used for page size\n /\\bcount\\b/i, // Count can also be used for page size\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items, numitems\n /\\bresults_?per_?page\\b/i,\n];\n\n// Regexes for parameters indicating a cursor\nexport const CURSOR_REGEXES: RegExp[] = [\n /\\bmarker\\b/i,\n /\\bcursor\\b/i,\n /\\bafter(?:_?cursor)?\\b/i, // e.g., after, after_cursor\n /\\bbefore(?:_?cursor)?\\b/i, // e.g., before, before_cursor\n /\\b(next|prev|previous)_?(?:page_?)?token\\b/i, // e.g., next_page_token, nextPageToken, prev_token\n /\\b(next|prev|previous)_?cursor\\b/i, // e.g., next_cursor, previousCursor\n /\\bcontinuation(?:_?token)?\\b/i, // e.g., continuation, continuation_token\n /\\bpage(?:_?(token|id))?\\b/i, // e.g., after, after_cursor\n\n /\\bstart_?(?:key|cursor|token|after)\\b/i, // e.g., start_key, startCursor, startToken, startAfter\n];\n\n// Regexes for parameters indicating a limit when used with cursors\nexport const CURSOR_LIMIT_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\bsize\\b/i, // General size\n /\\bfirst\\b/i, // Common in Relay-style cursor pagination (forward pagination)\n /\\blast\\b/i, // Common in Relay-style cursor pagination (backward pagination)\n /\\bpage_?size\\b/i, // Sometimes page_size is used with cursors\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items\n /\\bmax_?items\\b/i,\n /\\btake\\b/i,\n];\n\n// --- Helper Function ---\nfunction findParamAndKeyword(\n queryParams: { name: string }[],\n regexes: RegExp[],\n excludeParamName?: string,\n) {\n for (const param of queryParams) {\n if (param.name === excludeParamName) {\n continue;\n }\n for (const regex of regexes) {\n const match = param.name.match(regex);\n if (match) {\n return { param, keyword: match[0] }; // match[0] is the actual matched substring\n }\n }\n }\n return null;\n}\n\nfunction coerceParameters(\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[],\n) {\n const cleanedParameters: {\n name: string;\n schema: Omit<SchemaObject, 'type'> & {\n type: string[]; // Ensure type is always an array\n };\n }[] = [];\n for (const param of parameters) {\n if (!param.schema) {\n continue;\n }\n if (isRef(param.schema)) {\n continue;\n }\n if (param.schema.anyOf || param.schema.oneOf || param.schema.allOf) {\n const schemas = (\n param.schema.anyOf ||\n param.schema.oneOf ||\n param.schema.allOf ||\n []\n ).filter((it): it is SchemaObject => !isRef(it));\n schemas.forEach((schema) => {\n if (schema.type) {\n cleanedParameters.push({\n ...param,\n schema: {\n ...schema,\n type: coerceTypes(schema),\n },\n });\n }\n });\n continue;\n }\n if (!param.schema.type) {\n continue;\n }\n if (param.schema) {\n cleanedParameters.push({\n ...param,\n schema: {\n ...param.schema,\n type: coerceTypes(param.schema),\n },\n });\n }\n }\n return cleanedParameters;\n}\n\nfunction isOffsetPagination(\n operation: TunedOperationObject,\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[],\n): OffsetPaginationResult | null {\n const params = coerceParameters(parameters).filter(\n (it) =>\n it.schema.type.includes('integer') || it.schema.type.includes('number'),\n );\n\n const offsetMatch = findParamAndKeyword(params, OFFSET_PARAM_REGEXES);\n\n if (!offsetMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n params,\n GENERIC_LIMIT_PARAM_REGEXES,\n offsetMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'offset',\n offsetParamName: offsetMatch.param.name,\n offsetKeyword: offsetMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\nfunction isPagePagination(\n operation: TunedOperationObject,\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[],\n): PagePaginationResult | null {\n const params = coerceParameters(parameters).filter(\n (it) =>\n it.schema.type.includes('integer') || it.schema.type.includes('number'),\n );\n\n if (params.length < 2) return null;\n\n const pageNoMatch = findParamAndKeyword(params, PAGE_NUMBER_REGEXES);\n if (!pageNoMatch) return null;\n\n const pageSizeMatch = findParamAndKeyword(\n params,\n PAGE_SIZE_REGEXES,\n pageNoMatch.param.name,\n );\n if (!pageSizeMatch) return null;\n\n return {\n type: 'page',\n pageNumberParamName: pageNoMatch.param.name,\n pageNumberKeyword: pageNoMatch.keyword,\n pageSizeParamName: pageSizeMatch.param.name,\n pageSizeKeyword: pageSizeMatch.keyword,\n };\n}\n\nfunction isCursorPagination(\n operation: TunedOperationObject,\n parameters: { name: string; schema?: SchemaObject | ReferenceObject }[] = [],\n): CursorPaginationResult | null {\n const queryParams = parameters;\n if (queryParams.length < 2) return null; // Need at least a cursor and a limit-like param\n\n const cursorMatch = findParamAndKeyword(queryParams, CURSOR_REGEXES);\n if (!cursorMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n queryParams,\n CURSOR_LIMIT_REGEXES,\n cursorMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'cursor',\n cursorParamName: cursorMatch.param.name,\n cursorKeyword: cursorMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\n/**\n * Guesses the pagination strategy of an OpenAPI operation based on its query parameters.\n * It checks for offset, page-based, and cursor-based pagination in that order.\n *\n * @param operation The OpenAPI operation object.\n * @returns A PaginationGuess object indicating the detected type and relevant parameters.\n */\nexport function guessPagination(\n operation: TunedOperationObject,\n body?: SchemaObject,\n response?: SchemaObject,\n): PaginationGuess {\n const bodyParameters =\n body && body.properties\n ? Object.entries(body.properties).map(([it, schema]) => ({\n name: it,\n schema,\n }))\n : [];\n const parameters = operation.parameters;\n\n if (isEmpty(operation.parameters) && isEmpty(bodyParameters)) {\n return { type: 'none', reason: 'no parameters' };\n }\n if (!response) {\n return { type: 'none', reason: 'no response' };\n }\n if (!response.properties) {\n return { type: 'none', reason: 'empty response' };\n }\n const properties = response.properties as SchemasObject;\n\n const itemsKey = getItemsName(properties);\n if (!itemsKey) {\n return { type: 'none', reason: 'no items key' };\n }\n const hasMoreKey = getHasMoreName(excludeKey(properties, itemsKey));\n\n if (!hasMoreKey) {\n return { type: 'none', reason: 'no hasMore key' };\n }\n const pagination =\n isOffsetPagination(operation, [...parameters, ...bodyParameters]) ||\n isPagePagination(operation, [...parameters, ...bodyParameters]) ||\n isCursorPagination(operation, [...parameters, ...bodyParameters]);\n return pagination\n ? { ...pagination, items: itemsKey, hasMore: hasMoreKey }\n : { type: 'none', reason: 'no pagination' };\n}\n\nfunction excludeKey<T extends Record<string, any>>(\n obj: T,\n key: string,\n): Omit<T, typeof key> {\n const { [key]: _, ...rest } = obj;\n return rest;\n}\n"],
|
|
5
|
+
"mappings": "AAMA,SAAS,aAAa;AACtB,SAAS,eAAe;AAExB,SAAS,mBAAmB;AAE5B,SAAS,gBAAgB,oBAAoB;AA6CtC,MAAM,uBAAiC;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AACF;AAEO,MAAM,8BAAwC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AACF;AAEO,MAAM,sBAAgC;AAAA;AAAA;AAAA,EAG3C;AAAA;AAAA;AAAA,EAEA;AACF;AAGO,MAAM,oBAA8B;AAAA,EACzC;AAAA;AAAA,EACA;AAAA;AAAA;AAAA,EAEA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AACF;AAGO,MAAM,iBAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AACF;AAGO,MAAM,uBAAiC;A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G,YAAY,GAAG,cAAc,CAAC;AAClE,SAAO,aACH,EAAE,GAAG,YAAY,OAAO,UAAU,SAAS,WAAW,IACtD,EAAE,MAAM,QAAQ,QAAQ,gBAAgB;AAC9C;AAEA,SAAS,WACP,KACA,KACqB;AACrB,QAAM,EAAE,CAAC,GAAG,GAAG,GAAG,GAAG,KAAK,IAAI;AAC9B,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { SchemaObject, SchemasObject } from 'openapi3-ts/oas31';
|
|
2
|
+
import type { IR } from '../types.js';
|
|
3
|
+
export declare function getNextCursorName(schema: SchemaObject, spec: IR, visited?: Set<SchemaObject>): string | undefined;
|
|
2
4
|
/**
|
|
3
5
|
* Tries to guess the name of the property that holds the main list of items
|
|
4
6
|
* within an object schema using a series of heuristics.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pagination-result.d.ts","sourceRoot":"","sources":["../../../src/lib/pagination/pagination-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"pagination-result.d.ts","sourceRoot":"","sources":["../../../src/lib/pagination/pagination-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAMrE,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAEtC,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,YAAY,EACpB,IAAI,EAAE,EAAE,EACR,OAAO,oBAA0B,GAChC,MAAM,GAAG,SAAS,CAyCpB;AAkID;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,GACvC,MAAM,GAAG,IAAI,CAqFf;AAmFD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,aAAa,GAAG,MAAM,GAAG,IAAI,CAevE"}
|
|
@@ -1,4 +1,44 @@
|
|
|
1
1
|
import pluralize from "pluralize";
|
|
2
|
+
import { resolveRef } from "@sdk-it/core/ref.js";
|
|
3
|
+
import { coerceTypes } from "../is.js";
|
|
4
|
+
function getNextCursorName(schema, spec, visited = /* @__PURE__ */ new Set()) {
|
|
5
|
+
if (visited.has(schema)) return void 0;
|
|
6
|
+
const ancestors = new Set(visited).add(schema);
|
|
7
|
+
const properties = Object.entries(schema.properties ?? {}).map(
|
|
8
|
+
([name, property]) => [name, resolveRef(spec, property)]
|
|
9
|
+
);
|
|
10
|
+
for (const [name, property] of properties) {
|
|
11
|
+
if (/^(nextcursor|nextpagetoken|nexttoken|continuationtoken|endcursor)$/i.test(
|
|
12
|
+
name.replaceAll(/[_-]/g, "")
|
|
13
|
+
) && (property.anyOf ?? property.oneOf ?? [property]).some(
|
|
14
|
+
(variant) => coerceTypes(resolveRef(spec, variant)).includes("string")
|
|
15
|
+
)) {
|
|
16
|
+
return name;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
for (const [name, property] of properties) {
|
|
20
|
+
const nested = getNextCursorName(property, spec, ancestors);
|
|
21
|
+
if (nested) return `${name}.${nested}`;
|
|
22
|
+
}
|
|
23
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
24
|
+
for (const variant of [...schema.anyOf ?? [], ...schema.oneOf ?? []]) {
|
|
25
|
+
const resolved = resolveRef(spec, variant);
|
|
26
|
+
const types = coerceTypes(resolved, false);
|
|
27
|
+
if (types.length === 1 && types[0] === "null") continue;
|
|
28
|
+
const candidate = getNextCursorName(resolved, spec, ancestors);
|
|
29
|
+
if (!candidate) return void 0;
|
|
30
|
+
candidates.add(candidate);
|
|
31
|
+
}
|
|
32
|
+
for (const variant of schema.allOf ?? []) {
|
|
33
|
+
const candidate = getNextCursorName(
|
|
34
|
+
resolveRef(spec, variant),
|
|
35
|
+
spec,
|
|
36
|
+
ancestors
|
|
37
|
+
);
|
|
38
|
+
if (candidate) candidates.add(candidate);
|
|
39
|
+
}
|
|
40
|
+
return candidates.size === 1 ? candidates.values().next().value : void 0;
|
|
41
|
+
}
|
|
2
42
|
const PRIMARY_TOP_TIER_KEYWORDS = [
|
|
3
43
|
"data",
|
|
4
44
|
"items",
|
|
@@ -240,6 +280,7 @@ function getHasMoreName(properties) {
|
|
|
240
280
|
}
|
|
241
281
|
export {
|
|
242
282
|
getHasMoreName,
|
|
243
|
-
getItemsName
|
|
283
|
+
getItemsName,
|
|
284
|
+
getNextCursorName
|
|
244
285
|
};
|
|
245
286
|
//# sourceMappingURL=pagination-result.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/pagination/pagination-result.ts"],
|
|
4
|
-
"sourcesContent": ["import type { SchemaObject, SchemasObject } from 'openapi3-ts/oas31';\nimport pluralize from 'pluralize';\n\nconst PRIMARY_TOP_TIER_KEYWORDS: string[] = [\n 'data',\n 'items',\n 'results',\n 'value',\n];\nconst PRIMARY_OTHER_KEYWORDS: string[] = [\n 'records',\n 'content',\n 'list',\n 'payload',\n 'entities',\n 'collection',\n 'users',\n 'products',\n 'orders',\n 'bookings',\n 'articles',\n 'posts',\n 'documents',\n 'events',\n];\nconst SECONDARY_KEYWORDS: string[] = ['entries', 'rows', 'elements'];\n\nfunction lastWord(propName: string) {\n return (\n propName\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean)\n .at(-1) ?? ''\n );\n}\n\nfunction hasKeyword(propName: string, keywords: string[]) {\n return keywords.includes(lastWord(propName));\n}\n\nconst PLURAL_DEPRIORITIZE_LIST: string[] = [\n 'status',\n 'success',\n 'address',\n 'details',\n 'properties',\n 'params',\n 'headers',\n 'cookies',\n 'series',\n 'links',\n 'meta',\n 'metadata',\n 'statistics',\n 'settings',\n 'options',\n 'permissions',\n 'credentials',\n 'diagnostics',\n 'warnings',\n 'errors',\n 'actions',\n 'attributes',\n 'categories',\n 'configurations',\n 'features',\n 'includes',\n 'tags',\n];\n\n// For exact matches (normalized: lowercase, no underscores/hyphens)\nconst HAS_MORE_PRIMARY_POSITIVE_EXACT: string[] = [\n 'hasmore',\n 'hasnext',\n 'hasnextpage',\n 'moreitems',\n 'moreitemsavailable',\n 'nextpage',\n 'nextpageexists',\n 'nextpageavailable',\n 'hasadditionalresults',\n 'moreresultsavailable',\n 'canloadmore',\n 'hasadditional',\n 'additionalitems',\n 'fetchmore',\n];\n\nconst HAS_MORE_SECONDARY_POSITIVE_EXACT: string[] = ['more', 'next'];\n\nconst HAS_MORE_PRIMARY_INVERTED_EXACT: string[] = [\n 'islast',\n 'lastpage',\n 'endofresults',\n 'endoflist',\n 'nomoreitems',\n 'nomoredata',\n 'allitemsloaded',\n 'iscomplete',\n 'completed',\n];\n\n// For regex-based sub-phrase matching (tested against original propName, case-insensitive)\n// These regexes look for meaningful phrases, often using word boundaries (\\b)\n// and allowing for optional underscores.\nconst HAS_MORE_POSITIVE_REGEX_PATTERNS: string[] = [\n '\\\\bhas_?more\\\\b',\n '\\\\bhas_?next\\\\b', // e.g., itemsHasNext, items_has_next\n '\\\\bmore_?items\\\\b',\n '\\\\bnext_?page\\\\b', // e.g., userNextPageFlag\n '\\\\badditional\\\\b', // e.g., hasAdditionalData, additional_results_exist\n '\\\\bcontinuation\\\\b', // e.g., continuationAvailable, has_continuation_token\n '\\\\bmore_?results\\\\b',\n '\\\\bpage_?available\\\\b',\n '\\\\bnext(?:_?(page|marker))?\\\\b',\n];\nconst COMPILED_HAS_MORE_POSITIVE_REGEXES: RegExp[] =\n HAS_MORE_POSITIVE_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\nconst HAS_MORE_INVERTED_REGEX_PATTERNS: string[] = [\n '\\\\bis_?last\\\\b', // e.g., pageIsLast\n '\\\\blast_?page\\\\b', // e.g., resultsAreLastPage\n '\\\\bend_?of_?(data|results|list|items|stream)\\\\b',\n '\\\\bno_?more_?(items|data|results)?\\\\b',\n '\\\\ball_?(items_?)?loaded\\\\b',\n '\\\\bis_?complete\\\\b',\n];\nconst COMPILED_HAS_MORE_INVERTED_REGEXES: RegExp[] =\n HAS_MORE_INVERTED_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\n/**\n * Tries to guess the name of the property that holds the main list of items\n * within an object schema using a series of heuristics.\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely property containing the items array,\n * or null if no array properties are found in the schema.\n */\nexport function getItemsName(\n properties: Record<string, SchemaObject>,\n): string | null {\n const arrayPropertyNames: string[] = [];\n for (const propName in properties) {\n if (propName in properties) {\n const propSchema = properties[propName] as SchemaObject;\n if (propSchema && propSchema.type === 'array') {\n arrayPropertyNames.push(propName);\n }\n }\n }\n\n // Heuristic 0: No array properties at all.\n if (arrayPropertyNames.length === 0) {\n return null;\n }\n\n // Heuristic 1: Exactly one array property. This is the strongest signal.\n if (arrayPropertyNames.length === 1) {\n return arrayPropertyNames[0];\n }\n\n // Multiple array properties exist. Apply ranked heuristics:\n let bestCandidate: string | null = null;\n let candidateRank = Infinity; // Lower is better\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of arrayPropertyNames) {\n const lowerPropName = propName.toLowerCase();\n const finalWord = lastWord(propName);\n const isDeprioritized = PLURAL_DEPRIORITIZE_LIST.includes(lowerPropName);\n const isCompoundMetadata =\n finalWord !== lowerPropName &&\n PLURAL_DEPRIORITIZE_LIST.includes(finalWord);\n\n // Heuristic 2: Top-tier primary keywords (e.g., \"data\", \"items\")\n if (hasKeyword(propName, PRIMARY_TOP_TIER_KEYWORDS)) {\n updateCandidate(propName, 2);\n continue; // Move to next property, this is a strong match for this prop\n }\n\n // Heuristic 3: Other primary keywords\n if (candidateRank > 3 && hasKeyword(propName, PRIMARY_OTHER_KEYWORDS)) {\n updateCandidate(propName, 3);\n continue;\n }\n\n // Heuristic 4: Secondary keywords\n if (candidateRank > 4 && hasKeyword(propName, SECONDARY_KEYWORDS)) {\n updateCandidate(propName, 4);\n continue;\n }\n\n // Heuristic 5: Pluralized name, not on the deprioritize list\n if (\n candidateRank > 5 &&\n pluralize.isPlural(propName) &&\n !isDeprioritized &&\n !isCompoundMetadata\n ) {\n updateCandidate(propName, 5);\n continue;\n }\n\n // Heuristic 6: Pluralized name, IS on the deprioritize list (less preferred plural)\n if (candidateRank > 6 && pluralize.isPlural(propName) && isDeprioritized) {\n updateCandidate(propName, 6);\n continue;\n }\n }\n\n // If any of the above heuristics found a candidate, return it.\n if (bestCandidate) {\n return bestCandidate;\n }\n\n // Heuristic 7: Fallback - If no keywords or clear plurals,\n // and multiple arrays exist, return the first array property encountered.\n // This ensures we always return a name if arrays are present.\n return arrayPropertyNames[0];\n}\n\nfunction guess(properties: Record<string, SchemaObject>) {\n const booleanPropertyNames: string[] = [];\n for (const propName in properties) {\n const propSchema = properties[propName] as SchemaObject;\n if (\n propSchema.type === 'boolean' ||\n propSchema.type === 'integer' ||\n propSchema.type === 'string'\n ) {\n booleanPropertyNames.push(propName);\n }\n }\n\n if (booleanPropertyNames.length === 0) {\n return null;\n }\n\n if (booleanPropertyNames.length === 1) {\n return booleanPropertyNames[0];\n }\n\n let bestCandidate: string | null = null;\n let candidateRank = Infinity;\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of booleanPropertyNames) {\n const normalizedForExactMatch = propName.toLowerCase().replace(/[-_]/g, '');\n let currentPropRank = Infinity;\n\n // Rank 1: Primary Exact Positive Match\n if (HAS_MORE_PRIMARY_POSITIVE_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 1;\n }\n // Rank 2: Secondary Exact Positive Match\n else if (\n HAS_MORE_SECONDARY_POSITIVE_EXACT.includes(normalizedForExactMatch)\n ) {\n currentPropRank = 2;\n }\n // Rank 3: Positive Regex Match (sub-phrase)\n else {\n let foundPositiveRegex = false;\n for (const regex of COMPILED_HAS_MORE_POSITIVE_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 3;\n foundPositiveRegex = true;\n break;\n }\n }\n\n // Only proceed to inverted matches if no positive match of any kind (Rank 1, 2, or 3) was found\n if (!foundPositiveRegex) {\n // Rank 4: Primary Exact Inverted Match\n if (HAS_MORE_PRIMARY_INVERTED_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 4;\n }\n // Rank 5: Inverted Regex Match (sub-phrase)\n else {\n for (const regex of COMPILED_HAS_MORE_INVERTED_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 5;\n break;\n }\n }\n }\n }\n }\n\n updateCandidate(propName, currentPropRank);\n }\n return bestCandidate;\n}\n\n/**\n * Tries to guess the name of a boolean property that indicates if there are more items\n * to fetch (e.g., for pagination).\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely boolean property indicating \"has more\",\n * or null if no suitable boolean property is found.\n */\nexport function getHasMoreName(properties: SchemasObject): string | null {\n const rootGuess = guess(properties);\n if (rootGuess) {\n return rootGuess;\n }\n for (const propName in properties) {\n const propSchema = properties[propName];\n if (propSchema.type === 'object' && propSchema.properties) {\n const nested = getHasMoreName(propSchema.properties as SchemasObject);\n if (nested) {\n return propName + '.' + nested;\n }\n }\n }\n return null;\n}\n"],
|
|
5
|
-
"mappings": "AACA,OAAO,eAAe;AAEtB,MAAM,4BAAsC;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,yBAAmC;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,qBAA+B,CAAC,WAAW,QAAQ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AAgB,UAAU,eAAe;AAAA,EAC3C;AACA,SAAO;AACT;AAUO,SAAS,eAAe,YAA0C;AACvE,QAAM,YAAY,MAAM,UAAU;AAClC,MAAI,WAAW;AACb,WAAO;AAAA,EACT;AACA,aAAW,YAAY,YAAY;AACjC,UAAM,aAAa,WAAW,QAAQ;AACtC,QAAI,WAAW,SAAS,YAAY,WAAW,YAAY;AACzD,YAAM,SAAS,eAAe,WAAW,UAA2B;AACpE,UAAI,QAAQ;AACV,eAAO,WAAW,MAAM;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["import type { SchemaObject, SchemasObject } from 'openapi3-ts/oas31';\nimport pluralize from 'pluralize';\n\nimport { resolveRef } from '@sdk-it/core/ref.js';\n\nimport { coerceTypes } from '../is.js';\nimport type { IR } from '../types.js';\n\nexport function getNextCursorName(\n schema: SchemaObject,\n spec: IR,\n visited = new Set<SchemaObject>(),\n): string | undefined {\n if (visited.has(schema)) return undefined;\n const ancestors = new Set(visited).add(schema);\n const properties = Object.entries(schema.properties ?? {}).map(\n ([name, property]) =>\n [name, resolveRef<SchemaObject>(spec, property)] as const,\n );\n for (const [name, property] of properties) {\n if (\n /^(nextcursor|nextpagetoken|nexttoken|continuationtoken|endcursor)$/i.test(\n name.replaceAll(/[_-]/g, ''),\n ) &&\n (property.anyOf ?? property.oneOf ?? [property]).some((variant) =>\n coerceTypes(resolveRef<SchemaObject>(spec, variant)).includes('string'),\n )\n ) {\n return name;\n }\n }\n for (const [name, property] of properties) {\n const nested = getNextCursorName(property, spec, ancestors);\n if (nested) return `${name}.${nested}`;\n }\n const candidates = new Set<string>();\n for (const variant of [...(schema.anyOf ?? []), ...(schema.oneOf ?? [])]) {\n const resolved = resolveRef<SchemaObject>(spec, variant);\n const types = coerceTypes(resolved, false);\n if (types.length === 1 && types[0] === 'null') continue;\n const candidate = getNextCursorName(resolved, spec, ancestors);\n if (!candidate) return undefined;\n candidates.add(candidate);\n }\n for (const variant of schema.allOf ?? []) {\n const candidate = getNextCursorName(\n resolveRef<SchemaObject>(spec, variant),\n spec,\n ancestors,\n );\n if (candidate) candidates.add(candidate);\n }\n return candidates.size === 1 ? candidates.values().next().value : undefined;\n}\n\nconst PRIMARY_TOP_TIER_KEYWORDS: string[] = [\n 'data',\n 'items',\n 'results',\n 'value',\n];\nconst PRIMARY_OTHER_KEYWORDS: string[] = [\n 'records',\n 'content',\n 'list',\n 'payload',\n 'entities',\n 'collection',\n 'users',\n 'products',\n 'orders',\n 'bookings',\n 'articles',\n 'posts',\n 'documents',\n 'events',\n];\nconst SECONDARY_KEYWORDS: string[] = ['entries', 'rows', 'elements'];\n\nfunction lastWord(propName: string) {\n return (\n propName\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean)\n .at(-1) ?? ''\n );\n}\n\nfunction hasKeyword(propName: string, keywords: string[]) {\n return keywords.includes(lastWord(propName));\n}\n\nconst PLURAL_DEPRIORITIZE_LIST: string[] = [\n 'status',\n 'success',\n 'address',\n 'details',\n 'properties',\n 'params',\n 'headers',\n 'cookies',\n 'series',\n 'links',\n 'meta',\n 'metadata',\n 'statistics',\n 'settings',\n 'options',\n 'permissions',\n 'credentials',\n 'diagnostics',\n 'warnings',\n 'errors',\n 'actions',\n 'attributes',\n 'categories',\n 'configurations',\n 'features',\n 'includes',\n 'tags',\n];\n\n// For exact matches (normalized: lowercase, no underscores/hyphens)\nconst HAS_MORE_PRIMARY_POSITIVE_EXACT: string[] = [\n 'hasmore',\n 'hasnext',\n 'hasnextpage',\n 'moreitems',\n 'moreitemsavailable',\n 'nextpage',\n 'nextpageexists',\n 'nextpageavailable',\n 'hasadditionalresults',\n 'moreresultsavailable',\n 'canloadmore',\n 'hasadditional',\n 'additionalitems',\n 'fetchmore',\n];\n\nconst HAS_MORE_SECONDARY_POSITIVE_EXACT: string[] = ['more', 'next'];\n\nconst HAS_MORE_PRIMARY_INVERTED_EXACT: string[] = [\n 'islast',\n 'lastpage',\n 'endofresults',\n 'endoflist',\n 'nomoreitems',\n 'nomoredata',\n 'allitemsloaded',\n 'iscomplete',\n 'completed',\n];\n\n// For regex-based sub-phrase matching (tested against original propName, case-insensitive)\n// These regexes look for meaningful phrases, often using word boundaries (\\b)\n// and allowing for optional underscores.\nconst HAS_MORE_POSITIVE_REGEX_PATTERNS: string[] = [\n '\\\\bhas_?more\\\\b',\n '\\\\bhas_?next\\\\b', // e.g., itemsHasNext, items_has_next\n '\\\\bmore_?items\\\\b',\n '\\\\bnext_?page\\\\b', // e.g., userNextPageFlag\n '\\\\badditional\\\\b', // e.g., hasAdditionalData, additional_results_exist\n '\\\\bcontinuation\\\\b', // e.g., continuationAvailable, has_continuation_token\n '\\\\bmore_?results\\\\b',\n '\\\\bpage_?available\\\\b',\n '\\\\bnext(?:_?(page|marker))?\\\\b',\n];\nconst COMPILED_HAS_MORE_POSITIVE_REGEXES: RegExp[] =\n HAS_MORE_POSITIVE_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\nconst HAS_MORE_INVERTED_REGEX_PATTERNS: string[] = [\n '\\\\bis_?last\\\\b', // e.g., pageIsLast\n '\\\\blast_?page\\\\b', // e.g., resultsAreLastPage\n '\\\\bend_?of_?(data|results|list|items|stream)\\\\b',\n '\\\\bno_?more_?(items|data|results)?\\\\b',\n '\\\\ball_?(items_?)?loaded\\\\b',\n '\\\\bis_?complete\\\\b',\n];\nconst COMPILED_HAS_MORE_INVERTED_REGEXES: RegExp[] =\n HAS_MORE_INVERTED_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\n/**\n * Tries to guess the name of the property that holds the main list of items\n * within an object schema using a series of heuristics.\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely property containing the items array,\n * or null if no array properties are found in the schema.\n */\nexport function getItemsName(\n properties: Record<string, SchemaObject>,\n): string | null {\n const arrayPropertyNames: string[] = [];\n for (const propName in properties) {\n if (propName in properties) {\n const propSchema = properties[propName] as SchemaObject;\n if (propSchema && propSchema.type === 'array') {\n arrayPropertyNames.push(propName);\n }\n }\n }\n\n // Heuristic 0: No array properties at all.\n if (arrayPropertyNames.length === 0) {\n return null;\n }\n\n // Heuristic 1: Exactly one array property. This is the strongest signal.\n if (arrayPropertyNames.length === 1) {\n return arrayPropertyNames[0];\n }\n\n // Multiple array properties exist. Apply ranked heuristics:\n let bestCandidate: string | null = null;\n let candidateRank = Infinity; // Lower is better\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of arrayPropertyNames) {\n const lowerPropName = propName.toLowerCase();\n const finalWord = lastWord(propName);\n const isDeprioritized = PLURAL_DEPRIORITIZE_LIST.includes(lowerPropName);\n const isCompoundMetadata =\n finalWord !== lowerPropName &&\n PLURAL_DEPRIORITIZE_LIST.includes(finalWord);\n\n // Heuristic 2: Top-tier primary keywords (e.g., \"data\", \"items\")\n if (hasKeyword(propName, PRIMARY_TOP_TIER_KEYWORDS)) {\n updateCandidate(propName, 2);\n continue; // Move to next property, this is a strong match for this prop\n }\n\n // Heuristic 3: Other primary keywords\n if (candidateRank > 3 && hasKeyword(propName, PRIMARY_OTHER_KEYWORDS)) {\n updateCandidate(propName, 3);\n continue;\n }\n\n // Heuristic 4: Secondary keywords\n if (candidateRank > 4 && hasKeyword(propName, SECONDARY_KEYWORDS)) {\n updateCandidate(propName, 4);\n continue;\n }\n\n // Heuristic 5: Pluralized name, not on the deprioritize list\n if (\n candidateRank > 5 &&\n pluralize.isPlural(propName) &&\n !isDeprioritized &&\n !isCompoundMetadata\n ) {\n updateCandidate(propName, 5);\n continue;\n }\n\n // Heuristic 6: Pluralized name, IS on the deprioritize list (less preferred plural)\n if (candidateRank > 6 && pluralize.isPlural(propName) && isDeprioritized) {\n updateCandidate(propName, 6);\n continue;\n }\n }\n\n // If any of the above heuristics found a candidate, return it.\n if (bestCandidate) {\n return bestCandidate;\n }\n\n // Heuristic 7: Fallback - If no keywords or clear plurals,\n // and multiple arrays exist, return the first array property encountered.\n // This ensures we always return a name if arrays are present.\n return arrayPropertyNames[0];\n}\n\nfunction guess(properties: Record<string, SchemaObject>) {\n const booleanPropertyNames: string[] = [];\n for (const propName in properties) {\n const propSchema = properties[propName] as SchemaObject;\n if (\n propSchema.type === 'boolean' ||\n propSchema.type === 'integer' ||\n propSchema.type === 'string'\n ) {\n booleanPropertyNames.push(propName);\n }\n }\n\n if (booleanPropertyNames.length === 0) {\n return null;\n }\n\n if (booleanPropertyNames.length === 1) {\n return booleanPropertyNames[0];\n }\n\n let bestCandidate: string | null = null;\n let candidateRank = Infinity;\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of booleanPropertyNames) {\n const normalizedForExactMatch = propName.toLowerCase().replace(/[-_]/g, '');\n let currentPropRank = Infinity;\n\n // Rank 1: Primary Exact Positive Match\n if (HAS_MORE_PRIMARY_POSITIVE_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 1;\n }\n // Rank 2: Secondary Exact Positive Match\n else if (\n HAS_MORE_SECONDARY_POSITIVE_EXACT.includes(normalizedForExactMatch)\n ) {\n currentPropRank = 2;\n }\n // Rank 3: Positive Regex Match (sub-phrase)\n else {\n let foundPositiveRegex = false;\n for (const regex of COMPILED_HAS_MORE_POSITIVE_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 3;\n foundPositiveRegex = true;\n break;\n }\n }\n\n // Only proceed to inverted matches if no positive match of any kind (Rank 1, 2, or 3) was found\n if (!foundPositiveRegex) {\n // Rank 4: Primary Exact Inverted Match\n if (HAS_MORE_PRIMARY_INVERTED_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 4;\n }\n // Rank 5: Inverted Regex Match (sub-phrase)\n else {\n for (const regex of COMPILED_HAS_MORE_INVERTED_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 5;\n break;\n }\n }\n }\n }\n }\n\n updateCandidate(propName, currentPropRank);\n }\n return bestCandidate;\n}\n\n/**\n * Tries to guess the name of a boolean property that indicates if there are more items\n * to fetch (e.g., for pagination).\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely boolean property indicating \"has more\",\n * or null if no suitable boolean property is found.\n */\nexport function getHasMoreName(properties: SchemasObject): string | null {\n const rootGuess = guess(properties);\n if (rootGuess) {\n return rootGuess;\n }\n for (const propName in properties) {\n const propSchema = properties[propName];\n if (propSchema.type === 'object' && propSchema.properties) {\n const nested = getHasMoreName(propSchema.properties as SchemasObject);\n if (nested) {\n return propName + '.' + nested;\n }\n }\n }\n return null;\n}\n"],
|
|
5
|
+
"mappings": "AACA,OAAO,eAAe;AAEtB,SAAS,kBAAkB;AAE3B,SAAS,mBAAmB;AAGrB,SAAS,kBACd,QACA,MACA,UAAU,oBAAI,IAAkB,GACZ;AACpB,MAAI,QAAQ,IAAI,MAAM,EAAG,QAAO;AAChC,QAAM,YAAY,IAAI,IAAI,OAAO,EAAE,IAAI,MAAM;AAC7C,QAAM,aAAa,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC,EAAE;AAAA,IACzD,CAAC,CAAC,MAAM,QAAQ,MACd,CAAC,MAAM,WAAyB,MAAM,QAAQ,CAAC;AAAA,EACnD;AACA,aAAW,CAAC,MAAM,QAAQ,KAAK,YAAY;AACzC,QACE,sEAAsE;AAAA,MACpE,KAAK,WAAW,SAAS,EAAE;AAAA,IAC7B,MACC,SAAS,SAAS,SAAS,SAAS,CAAC,QAAQ,GAAG;AAAA,MAAK,CAAC,YACrD,YAAY,WAAyB,MAAM,OAAO,CAAC,EAAE,SAAS,QAAQ;AAAA,IACxE,GACA;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACA,aAAW,CAAC,MAAM,QAAQ,KAAK,YAAY;AACzC,UAAM,SAAS,kBAAkB,UAAU,MAAM,SAAS;AAC1D,QAAI,OAA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;AACV,eAAO,WAAW,MAAM;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../../src/lib/pagination/pagination.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,EAAE,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../../src/lib/pagination/pagination.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,EAAE,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAI5D,wBAAgB,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,cAAc,EAAE,oBAAoB,OAyC1E"}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { followRef, isRef } from "@sdk-it/core/ref.js";
|
|
2
2
|
import { isSuccessStatusCode } from "../is.js";
|
|
3
3
|
import { guessPagination } from "./guess-pagination.js";
|
|
4
|
+
import { getNextCursorName } from "./pagination-result.js";
|
|
4
5
|
function toPagination(spec, tunedOperation) {
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
const configured = tunedOperation["x-pagination"];
|
|
7
|
+
if (configured && (configured.type !== "cursor" || configured.nextCursor)) {
|
|
8
|
+
return configured;
|
|
7
9
|
}
|
|
8
10
|
const successResponse = Object.entries(tunedOperation.responses).find(
|
|
9
|
-
([status]) => isSuccessStatusCode(status) && Number.isInteger(Number(status))
|
|
11
|
+
([status]) => configured ? Number(status) === configured.statusCode : isSuccessStatusCode(status) && Number.isInteger(Number(status))
|
|
10
12
|
);
|
|
11
13
|
const statusCode = successResponse ? Number(successResponse[0]) : void 0;
|
|
12
14
|
const schema = successResponse ? getResponseContentSchema(spec, successResponse[1], "application/json") : void 0;
|
|
13
|
-
const pagination = guessPagination(
|
|
15
|
+
const pagination = configured ?? guessPagination(
|
|
14
16
|
tunedOperation,
|
|
15
17
|
tunedOperation.requestBody ? getRequestContentSchema(
|
|
16
18
|
spec,
|
|
@@ -20,9 +22,10 @@ function toPagination(spec, tunedOperation) {
|
|
|
20
22
|
schema
|
|
21
23
|
);
|
|
22
24
|
if (pagination && pagination.type !== "none" && schema && statusCode !== void 0) {
|
|
23
|
-
|
|
25
|
+
const nextCursor = pagination.type === "cursor" ? getNextCursorName(schema, spec) : void 0;
|
|
26
|
+
return { ...pagination, statusCode, ...nextCursor ? { nextCursor } : {} };
|
|
24
27
|
}
|
|
25
|
-
return
|
|
28
|
+
return configured;
|
|
26
29
|
}
|
|
27
30
|
function getResponseContentSchema(spec, response, type) {
|
|
28
31
|
if (!response) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/pagination/pagination.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef } from '@sdk-it/core/ref.js';\n\nimport { isSuccessStatusCode } from '../is.js';\nimport type { IR, TunedOperationObject } from '../types.js';\nimport { guessPagination } from './guess-pagination.js';\n\nexport function toPagination(spec: IR, tunedOperation: TunedOperationObject) {\n
|
|
5
|
-
"mappings": "AAMA,SAAS,WAAW,aAAa;AAEjC,SAAS,2BAA2B;AAEpC,SAAS,uBAAuB;
|
|
4
|
+
"sourcesContent": ["import type {\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef } from '@sdk-it/core/ref.js';\n\nimport { isSuccessStatusCode } from '../is.js';\nimport type { IR, TunedOperationObject } from '../types.js';\nimport { guessPagination } from './guess-pagination.js';\nimport { getNextCursorName } from './pagination-result.js';\n\nexport function toPagination(spec: IR, tunedOperation: TunedOperationObject) {\n const configured = tunedOperation['x-pagination'];\n if (configured && (configured.type !== 'cursor' || configured.nextCursor)) {\n return configured;\n }\n const successResponse = Object.entries(tunedOperation.responses).find(\n ([status]) =>\n configured\n ? Number(status) === configured.statusCode\n : isSuccessStatusCode(status) && Number.isInteger(Number(status)),\n );\n const statusCode = successResponse ? Number(successResponse[0]) : undefined;\n const schema = successResponse\n ? getResponseContentSchema(spec, successResponse[1], 'application/json')\n : undefined;\n const pagination =\n configured ??\n guessPagination(\n tunedOperation,\n tunedOperation.requestBody\n ? getRequestContentSchema(\n spec,\n tunedOperation.requestBody,\n 'application/json',\n )\n : undefined,\n schema,\n );\n if (\n pagination &&\n pagination.type !== 'none' &&\n schema &&\n statusCode !== undefined\n ) {\n const nextCursor =\n pagination.type === 'cursor'\n ? getNextCursorName(schema, spec)\n : undefined;\n return { ...pagination, statusCode, ...(nextCursor ? { nextCursor } : {}) };\n }\n return configured;\n}\n\nfunction getResponseContentSchema(\n spec: IR,\n response: ResponseObject,\n type: string,\n) {\n if (!response) {\n return undefined;\n }\n const content = response.content;\n if (!content) {\n return undefined;\n }\n for (const contentType in content) {\n if (contentType.toLowerCase() === type.toLowerCase()) {\n return isRef(content[contentType].schema)\n ? followRef<SchemaObject>(spec, content[contentType].schema.$ref)\n : content[contentType].schema;\n }\n }\n return undefined;\n}\n\nfunction getRequestContentSchema(\n spec: IR,\n requestBody: RequestBodyObject,\n type: string,\n) {\n const content = requestBody.content;\n if (!content) {\n return undefined;\n }\n for (const contentType in content) {\n if (contentType.toLowerCase() === type.toLowerCase()) {\n return isRef(content[contentType].schema)\n ? followRef<SchemaObject>(spec, content[contentType].schema.$ref)\n : content[contentType].schema;\n }\n }\n return undefined;\n}\n"],
|
|
5
|
+
"mappings": "AAMA,SAAS,WAAW,aAAa;AAEjC,SAAS,2BAA2B;AAEpC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAE3B,SAAS,aAAa,MAAU,gBAAsC;AAC3E,QAAM,aAAa,eAAe,cAAc;AAChD,MAAI,eAAe,WAAW,SAAS,YAAY,WAAW,aAAa;AACzE,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AG;AACpD,aAAO,MAAM,QAAQ,WAAW,EAAE,MAAM,IACpC,UAAwB,MAAM,QAAQ,WAAW,EAAE,OAAO,IAAI,IAC9D,QAAQ,WAAW,EAAE;AAAA,IAC3B;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enrich-examples.d.ts","sourceRoot":"","sources":["../../../src/lib/processing-plugins/enrich-examples.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"enrich-examples.d.ts","sourceRoot":"","sources":["../../../src/lib/processing-plugins/enrich-examples.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,eAAe,EAGf,YAAY,EACb,MAAM,mBAAmB,CAAC;AAK3B,OAAO,KAAK,EAAwB,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC/E,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAEtC,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,EAAE,CAAC;IACT,SAAS,EAAE,eAAe,CAAC;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,SAAS,GAAG,UAAU,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,YAAY,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,MAAM,WAAW,sBAAuB,SAAQ,sBAAsB;IACpE,KAAK,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,wBAAwB;IACvC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACpE,QAAQ,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACrE;AAwDD,wBAAgB,cAAc,CAC5B,OAAO,EAAE,wBAAwB,GAChC,gBAAgB,CAyDlB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { untilAborted } from "@zukhruf/async";
|
|
1
2
|
import { resolveRef } from "@sdk-it/core/ref.js";
|
|
2
3
|
import { iterateOperations } from "../for-each-operation.js";
|
|
3
4
|
function hasAuthoredExample(media) {
|
|
@@ -11,9 +12,17 @@ async function enrichMediaType(input, options, report) {
|
|
|
11
12
|
target.signal?.throwIfAborted();
|
|
12
13
|
const schema = resolveRef(target.spec, media.schema);
|
|
13
14
|
const enrichmentInput = { ...target, schema };
|
|
14
|
-
const value = await
|
|
15
|
+
const value = await untilAborted(
|
|
16
|
+
Promise.resolve(options.generate(enrichmentInput)),
|
|
17
|
+
target.signal
|
|
18
|
+
);
|
|
15
19
|
target.signal?.throwIfAborted();
|
|
16
|
-
|
|
20
|
+
const valid = await untilAborted(
|
|
21
|
+
Promise.resolve(options.validate({ ...enrichmentInput, value })),
|
|
22
|
+
target.signal
|
|
23
|
+
);
|
|
24
|
+
target.signal?.throwIfAborted();
|
|
25
|
+
if (!valid) {
|
|
17
26
|
report({
|
|
18
27
|
severity: "warning",
|
|
19
28
|
code: "generated-example-invalid",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/processing-plugins/enrich-examples.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n MediaTypeObject,\n OperationObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { resolveRef } from '@sdk-it/core/ref.js';\n\nimport { iterateOperations } from '../for-each-operation.js';\nimport type { ProcessingDiagnostic, ProcessingPlugin } from '../processing.js';\nimport type { IR } from '../types.js';\n\nexport interface ExampleEnrichmentInput {\n spec: IR;\n operation: OperationObject;\n method: string;\n path: string;\n direction: 'request' | 'response';\n mediaType: string;\n schema: SchemaObject;\n statusCode?: string;\n signal?: AbortSignal;\n}\n\nexport interface ExampleValidationInput extends ExampleEnrichmentInput {\n value: unknown;\n}\n\nexport interface ExampleEnrichmentOptions {\n name?: string;\n overwrite?: boolean;\n generate(input: ExampleEnrichmentInput): unknown | Promise<unknown>;\n validate(input: ExampleValidationInput): boolean | Promise<boolean>;\n}\n\nfunction hasAuthoredExample(media: MediaTypeObject): boolean {\n return (\n Object.prototype.hasOwnProperty.call(media, 'example') ||\n Object.keys(media.examples ?? {}).length > 0\n );\n}\n\nasync function enrichMediaType(\n input: Omit<ExampleEnrichmentInput, 'schema'> & {\n media: MediaTypeObject;\n },\n options: ExampleEnrichmentOptions,\n report: (\n diagnostic: Omit<ProcessingDiagnostic, 'plugin'>,\n ) => ProcessingDiagnostic,\n) {\n const { media, ...target } = input;\n if (!media.schema || (!options.overwrite && hasAuthoredExample(media))) {\n return;\n }\n\n target.signal?.throwIfAborted();\n const schema = resolveRef<SchemaObject>(target.spec, media.schema);\n const enrichmentInput = { ...target, schema };\n const value = await options.generate(enrichmentInput);\n target.signal?.throwIfAborted();\n\n
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { untilAborted } from '@zukhruf/async';\nimport type {\n MediaTypeObject,\n OperationObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { resolveRef } from '@sdk-it/core/ref.js';\n\nimport { iterateOperations } from '../for-each-operation.js';\nimport type { ProcessingDiagnostic, ProcessingPlugin } from '../processing.js';\nimport type { IR } from '../types.js';\n\nexport interface ExampleEnrichmentInput {\n spec: IR;\n operation: OperationObject;\n method: string;\n path: string;\n direction: 'request' | 'response';\n mediaType: string;\n schema: SchemaObject;\n statusCode?: string;\n signal?: AbortSignal;\n}\n\nexport interface ExampleValidationInput extends ExampleEnrichmentInput {\n value: unknown;\n}\n\nexport interface ExampleEnrichmentOptions {\n name?: string;\n overwrite?: boolean;\n generate(input: ExampleEnrichmentInput): unknown | Promise<unknown>;\n validate(input: ExampleValidationInput): boolean | Promise<boolean>;\n}\n\nfunction hasAuthoredExample(media: MediaTypeObject): boolean {\n return (\n Object.prototype.hasOwnProperty.call(media, 'example') ||\n Object.keys(media.examples ?? {}).length > 0\n );\n}\n\nasync function enrichMediaType(\n input: Omit<ExampleEnrichmentInput, 'schema'> & {\n media: MediaTypeObject;\n },\n options: ExampleEnrichmentOptions,\n report: (\n diagnostic: Omit<ProcessingDiagnostic, 'plugin'>,\n ) => ProcessingDiagnostic,\n) {\n const { media, ...target } = input;\n if (!media.schema || (!options.overwrite && hasAuthoredExample(media))) {\n return;\n }\n\n target.signal?.throwIfAborted();\n const schema = resolveRef<SchemaObject>(target.spec, media.schema);\n const enrichmentInput = { ...target, schema };\n const value = await untilAborted(\n Promise.resolve(options.generate(enrichmentInput)),\n target.signal,\n );\n target.signal?.throwIfAborted();\n\n const valid = await untilAborted(\n Promise.resolve(options.validate({ ...enrichmentInput, value })),\n target.signal,\n );\n target.signal?.throwIfAborted();\n if (!valid) {\n report({\n severity: 'warning',\n code: 'generated-example-invalid',\n message: `Discarded an invalid generated ${target.direction} example`,\n path: `${target.method.toUpperCase()} ${target.path}`,\n });\n return;\n }\n\n media.example = value;\n report({\n severity: 'info',\n code: 'example-generated',\n message: `Generated a schema-valid ${target.direction} example`,\n path: `${target.method.toUpperCase()} ${target.path}`,\n });\n}\n\nexport function enrichExamples(\n options: ExampleEnrichmentOptions,\n): ProcessingPlugin {\n return {\n name: options.name ?? 'enrich-examples',\n async process({ spec, report, signal }) {\n for (const { entry, operation } of iterateOperations(spec)) {\n if (operation.requestBody) {\n const requestBody = resolveRef<RequestBodyObject>(\n spec,\n operation.requestBody,\n );\n for (const [mediaType, media] of Object.entries(\n requestBody.content,\n )) {\n await enrichMediaType(\n {\n spec,\n operation,\n method: entry.method,\n path: entry.path,\n direction: 'request',\n mediaType,\n media,\n signal,\n },\n options,\n report,\n );\n }\n }\n\n for (const [statusCode, responseOrRef] of Object.entries(\n operation.responses ?? {},\n )) {\n const response = resolveRef<ResponseObject>(spec, responseOrRef);\n for (const [mediaType, media] of Object.entries(\n response.content ?? {},\n )) {\n await enrichMediaType(\n {\n spec,\n operation,\n method: entry.method,\n path: entry.path,\n direction: 'response',\n statusCode,\n mediaType,\n media,\n signal,\n },\n options,\n report,\n );\n }\n }\n }\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAS7B,SAAS,kBAAkB;AAE3B,SAAS,yBAAyB;AA2BlC,SAAS,mBAAmB,OAAiC;AAC3D,SACE,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,KACrD,OAAO,KAAK,MAAM,YAAY,CAAC,CAAC,EAAE,SAAS;AAE/C;AAEA,eAAe,gBACb,OAGA,SACA,QAGA;AACA,QAAM,EAAE,OAAO,GAAG,OAAO,IAAI;AAC7B,MAAI,CAAC,MAAM,UAAW,CAAC,QAAQ,aAAa,mBAAmB,KAAK,GAAI;AACtE;AAAA,EACF;AAEA,SAAO,QAAQ,eAAe;AAC9B,QAAM,SAAS,WAAyB,OAAO,MAAM,MAAM,MAAM;AACjE,QAAM,kBAAkB,EAAE,GAAG,QAAQ,OAAO;AAC5C,QAAM,QAAQ,MAAM;AAAA,IAClB,QAAQ,QAAQ,QAAQ,SAAS,eAAe,CAAC;AAAA,IACjD,OAAO;AAAA,EACT;AACA,SAAO,QAAQ,eAAe;AAE9B,QAAM,QAAQ,MAAM;AAAA,IAClB,QAAQ,QAAQ,QAAQ,SAAS,EAAE,GAAG,iBAAiB,MAAM,CAAC,CAAC;AAAA,IAC/D,OAAO;AAAA,EACT;AACA,SAAO,QAAQ,eAAe;AAC9B,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,MACL,UAAU;AAAA,MACV,MAAM;AAAA,MACN,SAAS,kCAAkC,OAAO,SAAS;AAAA,MAC3D,MAAM,GAAG,OAAO,OAAO,YAAY,CAAC,IAAI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AA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -9,7 +9,7 @@ function normalizeSchemaObjects(spec, schemas, visited = /* @__PURE__ */ new Set
|
|
|
9
9
|
for (const schema of schemas) {
|
|
10
10
|
if (isRef(schema)) continue;
|
|
11
11
|
if (!isEmpty(schema.properties)) {
|
|
12
|
-
schema.type
|
|
12
|
+
schema.type ??= "object";
|
|
13
13
|
delete schema.oneOf;
|
|
14
14
|
delete schema.anyOf;
|
|
15
15
|
normalizeSchemaObjects(spec, Object.values(schema.properties), visited);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/processing-plugins/normalize-schemas.ts"],
|
|
4
|
-
"sourcesContent": ["import { merge, uniq } from 'lodash-es';\nimport assert from 'node:assert';\nimport type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport { isEmpty, isRef, notRef, resolveRef, snakecase } from '@sdk-it/core';\n\nimport { findVarients } from '../find-polymorphic-varients.js';\nimport { formatName } from '../format-name.js';\nimport { isPrimitiveSchema } from '../is-primitive-schema.js';\nimport { coerceTypes } from '../is.js';\nimport type { ProcessingPlugin } from '../processing.js';\nimport type { IR } from '../types.js';\n\nfunction normalizeSchemaObjects(\n spec: IR,\n schemas: (SchemaObject | ReferenceObject)[],\n visited = new Set<string>(),\n) {\n for (const schema of schemas) {\n if (isRef(schema)) continue;\n\n if (!isEmpty(schema.properties)) {\n schema.type
|
|
5
|
-
"mappings": "AAAA,SAAS,OAAO,YAAY;AAC5B,OAAO,YAAY;AAGnB,SAAS,SAAS,OAAO,QAAQ,YAAY,iBAAiB;AAE9D,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;AAClC,SAAS,mBAAmB;AAI5B,SAAS,uBACP,MACA,SACA,UAAU,oBAAI,IAAY,GAC1B;AACA,aAAW,UAAU,SAAS;AAC5B,QAAI,MAAM,MAAM,EAAG;AAEnB,QAAI,CAAC,QAAQ,OAAO,UAAU,GAAG;AAC/B,aAAO,
|
|
4
|
+
"sourcesContent": ["import { merge, uniq } from 'lodash-es';\nimport assert from 'node:assert';\nimport type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport { isEmpty, isRef, notRef, resolveRef, snakecase } from '@sdk-it/core';\n\nimport { findVarients } from '../find-polymorphic-varients.js';\nimport { formatName } from '../format-name.js';\nimport { isPrimitiveSchema } from '../is-primitive-schema.js';\nimport { coerceTypes } from '../is.js';\nimport type { ProcessingPlugin } from '../processing.js';\nimport type { IR } from '../types.js';\n\nfunction normalizeSchemaObjects(\n spec: IR,\n schemas: (SchemaObject | ReferenceObject)[],\n visited = new Set<string>(),\n) {\n for (const schema of schemas) {\n if (isRef(schema)) continue;\n\n if (!isEmpty(schema.properties)) {\n schema.type ??= 'object';\n delete schema.oneOf;\n delete schema.anyOf;\n normalizeSchemaObjects(spec, Object.values(schema.properties), visited);\n for (const [key, value] of Object.entries(schema.properties)) {\n if (notRef(value) && isPrimitiveSchema(value)) {\n value.default ??= schema.default?.[key];\n delete schema.default?.[key];\n }\n }\n delete schema.default;\n }\n\n if (!isEmpty(schema['x-properties'])) {\n normalizeSchemaObjects(\n spec,\n Object.values(schema['x-properties']),\n visited,\n );\n }\n\n if (!isEmpty(schema.items)) {\n delete schema.oneOf;\n delete schema.anyOf;\n schema.type = 'array';\n normalizeSchemaObjects(spec, [schema.items], visited);\n const items = resolveRef<SchemaObject>(spec, schema.items);\n if (Array.isArray(items.default)) {\n schema.default ??= structuredClone(items.default);\n }\n delete items.default;\n }\n\n if (!isEmpty(schema.anyOf) && !isEmpty(schema.oneOf)) {\n delete schema.anyOf;\n }\n\n if (isEmpty(schema.enum)) {\n delete schema.enum;\n }\n\n if (!isEmpty(schema.enum)) {\n if (schema.enum.length === 1) {\n schema.const = schema.enum[0];\n delete schema.enum;\n } else {\n const valuesSet = new Set<string>();\n const valuesList = [];\n for (const value of schema.enum) {\n const formattedValue = formatName(snakecase(formatName(value)));\n if (!valuesSet.has(formattedValue)) {\n valuesSet.add(formattedValue);\n valuesList.push(value);\n }\n }\n schema.enum = valuesList;\n }\n delete schema.allOf;\n }\n\n if (schema.const !== undefined) {\n schema.default = schema.const;\n }\n\n if (!isEmpty(schema.allOf)) {\n const schemas = schema.allOf;\n const resolved = schemas.map((item) =>\n resolveRef<SchemaObject>(spec, item),\n );\n const hasObjects = resolved.some((item) => item.type === 'object');\n const hasOtherTypes = resolved.some(\n (item) => item.type && item.type !== 'object',\n );\n if (hasObjects && hasOtherTypes) {\n assert(false, `allOf must be an object`);\n }\n merge(\n schema,\n ...resolved.map((resolvedSchema, index) => {\n const sourceSchema = schemas[index];\n if (isRef(sourceSchema)) {\n if (visited.has(sourceSchema.$ref)) {\n throw new Error(\n `Circular allOf reference detected: ${[\n ...visited,\n sourceSchema.$ref,\n ].join(' -> ')}`,\n );\n }\n normalizeSchemaObjects(\n spec,\n [resolvedSchema],\n new Set(visited).add(sourceSchema.$ref),\n );\n } else {\n normalizeSchemaObjects(spec, [resolvedSchema], visited);\n }\n return resolvedSchema;\n }),\n );\n delete schema.allOf;\n } else {\n delete schema.allOf;\n }\n\n if (\n schema.type === 'object' &&\n isEmpty(schema.properties) &&\n typeof schema.additionalProperties === 'object' &&\n !isEmpty(schema.additionalProperties) &&\n notRef(schema.additionalProperties) &&\n !isEmpty(schema.additionalProperties.properties)\n ) {\n normalizeSchemaObjects(\n spec,\n Object.values(schema.additionalProperties.properties),\n visited,\n );\n }\n\n for (const kind of ['oneOf', 'anyOf'] as const) {\n if (!isEmpty(schema[kind])) {\n delete schema.type;\n normalizeSchemaObjects(spec, schema[kind], visited);\n if (isEmpty(schema[kind])) {\n continue;\n }\n\n let enumSchemaIndex = -1;\n const enumValues: string[] = [];\n for (let index = 0; index < schema[kind].length; index++) {\n const item = schema[kind][index];\n if (notRef(item) && item.type === 'string') {\n if (item.enum && item.enum.length > 1) {\n enumValues.push(...item.enum);\n if (enumSchemaIndex === -1) {\n enumSchemaIndex = index;\n }\n }\n }\n }\n if (enumSchemaIndex !== -1) {\n const enumSchema = schema[kind][enumSchemaIndex];\n if (notRef(enumSchema)) {\n enumSchema.enum = uniq(enumValues);\n }\n schema[kind] = schema[kind].filter(\n (item, index) => index === enumSchemaIndex || isRef(item),\n );\n }\n const otherTypes = schema[kind].filter(\n (item) => resolveRef<SchemaObject>(spec, item).type !== 'null',\n );\n if (otherTypes.length === 1) {\n const [only] = otherTypes;\n const droppedNull = otherTypes.length !== schema[kind].length;\n Object.assign(schema, only);\n delete schema[kind];\n if (droppedNull && notRef(only)) {\n const types = coerceTypes(only, false);\n if (types.length) {\n schema.type = uniq([...types, 'null']);\n }\n }\n continue;\n }\n\n schema['x-varients'] = findVarients(spec, schema[kind]);\n } else {\n delete schema[kind];\n }\n }\n }\n}\n\nexport function normalizeSchemas(): ProcessingPlugin {\n return {\n name: 'normalize-schemas',\n process({ spec }) {\n normalizeSchemaObjects(spec, Object.values(spec.components.schemas));\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,OAAO,YAAY;AAC5B,OAAO,YAAY;AAGnB,SAAS,SAAS,OAAO,QAAQ,YAAY,iBAAiB;AAE9D,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;AAClC,SAAS,mBAAmB;AAI5B,SAAS,uBACP,MACA,SACA,UAAU,oBAAI,IAAY,GAC1B;AACA,aAAW,UAAU,SAAS;AAC5B,QAAI,MAAM,MAAM,EAAG;AAEnB,QAAI,CAAC,QAAQ,OAAO,UAAU,GAAG;AAC/B,aAAO,SAAS;AAChB,aAAO,OAAO;AACd,aAAO,OAAO;AACd,6BAAuB,MAAM,OAAO,OAAO,OAAO,UAAU,GAAG,OAAO;AACtE,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,UAAU,GAAG;AAC5D,YAAI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I;AAClB,cAAI,eAAe,OAAO,IAAI,GAAG;AAC/B,kBAAM,QAAQ,YAAY,MAAM,KAAK;AACrC,gBAAI,MAAM,QAAQ;AAChB,qBAAO,OAAO,KAAK,CAAC,GAAG,OAAO,MAAM,CAAC;AAAA,YACvC;AAAA,UACF;AACA;AAAA,QACF;AAEA,eAAO,YAAY,IAAI,aAAa,MAAM,OAAO,IAAI,CAAC;AAAA,MACxD,OAAO;AACL,eAAO,OAAO,IAAI;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,mBAAqC;AACnD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,QAAQ,EAAE,KAAK,GAAG;AAChB,6BAAuB,MAAM,OAAO,OAAO,KAAK,WAAW,OAAO,CAAC;AAAA,IACrE;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["schemas"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processing.d.ts","sourceRoot":"","sources":["../../src/lib/processing.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"processing.d.ts","sourceRoot":"","sources":["../../src/lib/processing.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,KAAK,iBAAiB,EACtB,aAAa,IAAI,YAAY,EAC9B,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,YAAY,CAAC;AAErC,MAAM,MAAM,4BAA4B,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC;AAExE,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,4BAA4B,CAAC;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,EAAE,MAAM,CAAC,CAAC;AAE9E,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,EAAE,CAAC;IACT,OAAO,EAAE,iBAAiB,CAAC;IAC3B,WAAW,EAAE,oBAAoB,EAAE,CAAC;IACpC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,MAAM,CACJ,UAAU,EAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAC,GAC/C,oBAAoB,CAAC;CACzB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3D;AAED,MAAM,WAAW,iBAAkB,SAAQ,iBAAiB;IAC1D,OAAO,EAAE,SAAS,gBAAgB,EAAE,CAAC;IACrC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,YAAY,CAAC,EAAE,CAAC,UAAU,EAAE,oBAAoB,KAAK,IAAI,CAAC;CAC3D;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,EAAE,CAAC;IACT,WAAW,EAAE,oBAAoB,EAAE,CAAC;CACrC;AAED,wBAAsB,WAAW,CAC/B,MAAM,EAAE,iBAAiB,GACxB,OAAO,CAAC,gBAAgB,CAAC,CAoC3B"}
|
package/dist/lib/processing.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { untilAborted } from "@zukhruf/async";
|
|
1
2
|
import {
|
|
2
3
|
coeraceConfig as coerceConfig
|
|
3
4
|
} from "./options.js";
|
|
@@ -29,7 +30,7 @@ async function processSpec(config) {
|
|
|
29
30
|
return reported;
|
|
30
31
|
}
|
|
31
32
|
};
|
|
32
|
-
await plugin.process(context);
|
|
33
|
+
await untilAborted(Promise.resolve(plugin.process(context)), signal);
|
|
33
34
|
signal?.throwIfAborted();
|
|
34
35
|
}
|
|
35
36
|
spec["x-sdk-processing"] = { plugins: pluginNames, configuration };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/processing.ts"],
|
|
4
|
-
"sourcesContent": ["import type { OpenAPIDocument } from '@sdk-it/core';\n\nimport {\n type GenerateSdkConfig,\n coeraceConfig as coerceConfig,\n} from './options.js';\nimport type { IR } from './types.js';\n\nexport type ProcessingDiagnosticSeverity = 'info' | 'warning' | 'error';\n\nexport interface ProcessingDiagnostic {\n plugin: string;\n severity: ProcessingDiagnosticSeverity;\n code: string;\n message: string;\n path?: string;\n}\n\nexport type ProcessingOptions = Omit<ReturnType<typeof coerceConfig>, 'spec'>;\n\nexport interface ProcessingContext {\n spec: IR;\n options: ProcessingOptions;\n diagnostics: ProcessingDiagnostic[];\n signal?: AbortSignal;\n report(\n diagnostic: Omit<ProcessingDiagnostic, 'plugin'>,\n ): ProcessingDiagnostic;\n}\n\nexport interface ProcessingPlugin {\n name: string;\n process(context: ProcessingContext): void | Promise<void>;\n}\n\nexport interface ProcessSpecConfig extends GenerateSdkConfig {\n plugins: readonly ProcessingPlugin[];\n signal?: AbortSignal;\n onDiagnostic?: (diagnostic: ProcessingDiagnostic) => void;\n}\n\nexport interface ProcessingResult {\n spec: IR;\n diagnostics: ProcessingDiagnostic[];\n}\n\nexport async function processSpec(\n config: ProcessSpecConfig,\n): Promise<ProcessingResult> {\n const { plugins, signal, onDiagnostic, ...generateConfig } = config;\n signal?.throwIfAborted();\n const coerced = coerceConfig({\n ...generateConfig,\n spec: structuredClone(generateConfig.spec) as OpenAPIDocument,\n });\n const { spec, ...options } = coerced;\n const diagnostics: ProcessingDiagnostic[] = [];\n const pluginNames = plugins.map((plugin) => plugin.name);\n const configuration = JSON.stringify({\n pagination: options.pagination,\n responses: options.responses,\n });\n\n for (const plugin of plugins) {\n signal?.throwIfAborted();\n const context: ProcessingContext = {\n spec,\n options,\n diagnostics,\n signal,\n report(diagnostic) {\n const reported = { ...diagnostic, plugin: plugin.name };\n diagnostics.push(reported);\n onDiagnostic?.(reported);\n return reported;\n },\n };\n await plugin.process(context);\n signal?.throwIfAborted();\n }\n\n spec['x-sdk-processing'] = { plugins: pluginNames, configuration };\n\n return { spec, diagnostics };\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { untilAborted } from '@zukhruf/async';\n\nimport type { OpenAPIDocument } from '@sdk-it/core';\n\nimport {\n type GenerateSdkConfig,\n coeraceConfig as coerceConfig,\n} from './options.js';\nimport type { IR } from './types.js';\n\nexport type ProcessingDiagnosticSeverity = 'info' | 'warning' | 'error';\n\nexport interface ProcessingDiagnostic {\n plugin: string;\n severity: ProcessingDiagnosticSeverity;\n code: string;\n message: string;\n path?: string;\n}\n\nexport type ProcessingOptions = Omit<ReturnType<typeof coerceConfig>, 'spec'>;\n\nexport interface ProcessingContext {\n spec: IR;\n options: ProcessingOptions;\n diagnostics: ProcessingDiagnostic[];\n signal?: AbortSignal;\n report(\n diagnostic: Omit<ProcessingDiagnostic, 'plugin'>,\n ): ProcessingDiagnostic;\n}\n\nexport interface ProcessingPlugin {\n name: string;\n process(context: ProcessingContext): void | Promise<void>;\n}\n\nexport interface ProcessSpecConfig extends GenerateSdkConfig {\n plugins: readonly ProcessingPlugin[];\n signal?: AbortSignal;\n onDiagnostic?: (diagnostic: ProcessingDiagnostic) => void;\n}\n\nexport interface ProcessingResult {\n spec: IR;\n diagnostics: ProcessingDiagnostic[];\n}\n\nexport async function processSpec(\n config: ProcessSpecConfig,\n): Promise<ProcessingResult> {\n const { plugins, signal, onDiagnostic, ...generateConfig } = config;\n signal?.throwIfAborted();\n const coerced = coerceConfig({\n ...generateConfig,\n spec: structuredClone(generateConfig.spec) as OpenAPIDocument,\n });\n const { spec, ...options } = coerced;\n const diagnostics: ProcessingDiagnostic[] = [];\n const pluginNames = plugins.map((plugin) => plugin.name);\n const configuration = JSON.stringify({\n pagination: options.pagination,\n responses: options.responses,\n });\n\n for (const plugin of plugins) {\n signal?.throwIfAborted();\n const context: ProcessingContext = {\n spec,\n options,\n diagnostics,\n signal,\n report(diagnostic) {\n const reported = { ...diagnostic, plugin: plugin.name };\n diagnostics.push(reported);\n onDiagnostic?.(reported);\n return reported;\n },\n };\n await untilAborted(Promise.resolve(plugin.process(context)), signal);\n signal?.throwIfAborted();\n }\n\n spec['x-sdk-processing'] = { plugins: pluginNames, configuration };\n\n return { spec, diagnostics };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAI7B;AAAA,EAEE,iBAAiB;AAAA,OACZ;AAyCP,eAAsB,YACpB,QAC2B;AAC3B,QAAM,EAAE,SAAS,QAAQ,cAAc,GAAG,eAAe,IAAI;AAC7D,UAAQ,eAAe;AACvB,QAAM,UAAU,aAAa;AAAA,IAC3B,GAAG;AAAA,IACH,MAAM,gBAAgB,eAAe,IAAI;AAAA,EAC3C,CAAC;AACD,QAAM,EAAE,MAAM,GAAG,QAAQ,IAAI;AAC7B,QAAM,cAAsC,CAAC;AAC7C,QAAM,cAAc,QAAQ,IAAI,CAAC,WAAW,OAAO,IAAI;AACvD,QAAM,gBAAgB,KAAK,UAAU;AAAA,IACnC,YAAY,QAAQ;AAAA,IACpB,WAAW,QAAQ;AAAA,EACrB,CAAC;AAED,aAAW,UAAU,SAAS;AAC5B,YAAQ,eAAe;AACvB,UAAM,UAA6B;AAAA,MACjC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO,YAAY;AACjB,cAAM,WAAW,EAAE,GAAG,YAAY,QAAQ,OAAO,KAAK;AACtD,oBAAY,KAAK,QAAQ;AACzB,uBAAe,QAAQ;AACvB,eAAO;AAAA,MACT;AAAA,IACF;AACA,UAAM,aAAa,QAAQ,QAAQ,OAAO,QAAQ,OAAO,CAAC,GAAG,MAAM;AACnE,YAAQ,eAAe;AAAA,EACzB;AAEA,OAAK,kBAAkB,IAAI,EAAE,SAAS,aAAa,cAAc;AAEjE,SAAO,EAAE,MAAM,YAAY;AAC7B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdk-it/spec",
|
|
3
|
-
"version": "0.46.
|
|
3
|
+
"version": "0.46.9",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -27,15 +27,16 @@
|
|
|
27
27
|
"!**/*.test.*"
|
|
28
28
|
],
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@sdk-it/core": "0.46.
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"stringcase": "^4.3.1",
|
|
34
|
-
"yaml": "^2.7.0",
|
|
30
|
+
"@sdk-it/core": "0.46.9",
|
|
31
|
+
"@zukhruf/async": "^0.3.21",
|
|
32
|
+
"debug": "^4.4.1",
|
|
35
33
|
"fast-content-type-parse": "^3.0.0",
|
|
36
34
|
"lodash-es": "^4.17.21",
|
|
37
|
-
"debug": "^4.4.1",
|
|
38
35
|
"micromatch": "4.0.8",
|
|
39
|
-
"
|
|
36
|
+
"openapi3-ts": "4.5.0",
|
|
37
|
+
"p-limit": "3.1.0",
|
|
38
|
+
"pluralize": "^8.0.0",
|
|
39
|
+
"stringcase": "^4.3.1",
|
|
40
|
+
"yaml": "^2.7.0"
|
|
40
41
|
}
|
|
41
42
|
}
|