Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/utils.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844import { joinPath, pathParameters } from './path.ts';import * as catalog from '@okikio/catalog'import * as record from '@okikio/record'import { freeze as freezeOpenApi } from '../openapi/value.ts'import type { StandardSchemaV1 } from '@standard-schema/spec'import type { ProblemDefinition } from '@okikio/http/problem'import type { ResponseDefinition, ResponseExample } from '@okikio/http/response'
import { schemaOf, validate } from './definition.ts'import type { EndpointCompositionInput, EndpointDefinition, EndpointEntry, EndpointExample, EndpointGroup, EndpointInputSlot, EndpointInputSource, EndpointOperation,} from './types.ts'
/** Minimal Standard JSON Schema trait used without coupling to a schema library. */export interface StandardJsonSchemaV1 { readonly '~standard-json-schema': { readonly version: 1 readonly vendor: string readonly jsonSchema: unknown | (() => unknown | Promise<unknown>) }}
/** Context supplied when OpenAPI needs a schema-library-specific projection. */export interface OpenApiSchemaProjectionContext { readonly purpose: 'request' | 'response'}
/** Optional adapter used when a Standard Schema does not expose Standard JSON Schema directly. */export type OpenApiSchemaProjector = ( schema: StandardSchemaV1, context: OpenApiSchemaProjectionContext,) => unknown | undefined | Promise<unknown | undefined>
/** One server origin advertised by an OpenAPI document. */export interface OpenApiServer { readonly url: string readonly description?: string}
/** OpenAPI 3.1 document generated from one endpoint composition. */export interface OpenApiDocument { readonly openapi: '3.1.0' readonly info: Readonly<{ readonly title: string readonly version: string readonly description?: string }> readonly paths: Readonly<Record<string, Readonly<Record<string, unknown>>>> readonly servers?: readonly OpenApiServer[]}
/** Options for the endpoint-only OpenAPI projection. */export interface OpenApiOptions { readonly title: string readonly version: string readonly description?: string readonly includeInternal?: boolean /** Server origins advertised to generated clients and API reference tooling. */ readonly servers?: readonly OpenApiServer[] /** Project schemas from libraries such as Zod when they do not expose the Standard JSON Schema trait. */ readonly schemaProjector?: OpenApiSchemaProjector}
interface EndpointVisit { readonly endpoint: EndpointDefinition readonly path: string readonly groups: readonly EndpointGroup[]}
/** * Generate an endpoint-only OpenAPI document from the exact imported graph. * * Service-level authentication schemes, servers, and compiler-generated * failures are added after effective-operation resolution by `service.openapi`. */export async function openapi( input: EndpointCompositionInput, options: OpenApiOptions,): Promise<OpenApiDocument> { const normalizedOptions = normalizeOptions(options) const validation = validate(input) if (!validation.valid) { throw new TypeError( `Cannot project invalid endpoint definitions:\n${validation.issues.map((issue) => `- ${issue.message}`).join('\n')}`, ) }
const paths: Record<string, Record<string, unknown>> = Object.create(null) for (const visit of walk(input)) { const path = openApiPath(visit.path) const pathItem = paths[path] ??= Object.create(null) as Record<string, unknown> for (const operation of visit.endpoint.operations) { const internal = isInternal(visit.groups, visit.endpoint, operation) if (internal && !normalizedOptions.includeInternal) continue if (pathItem[operation.method] !== undefined) { throw new TypeError( `OpenAPI path ${operation.method.toUpperCase()} ${path} is declared more than once.`, ) } pathItem[operation.method] = await operationObject(visit, operation, internal, normalizedOptions) } }
return freezeOpenApi({ openapi: '3.1.0' as const, info: { title: normalizedOptions.title, version: normalizedOptions.version, ...(normalizedOptions.description !== undefined ? { description: normalizedOptions.description } : {}), }, paths, ...(normalizedOptions.servers !== undefined ? { servers: Object.freeze(normalizedOptions.servers.map((server) => freezeOpenApi({ ...server }))) } : {}), })}
/** * Projects one endpoint operation into its OpenAPI request parameters, body, responses, and internal-operation metadata. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */async function operationObject( visit: EndpointVisit, operation: EndpointOperation, internal: boolean, options: OpenApiOptions,): Promise<Readonly<Record<string, unknown>>> { const parameters: unknown[] = [] let requestBody: unknown for (const source of [ 'param', 'query', 'header', 'cookie', 'json', 'form', 'raw', ] as const satisfies readonly EndpointInputSource[]) { const slot = operation.inputs[source] ?? visit.endpoint.inputs[source] if (!slot) continue const schema = await projectSchema(slot, internal, options) if (source === 'json' || source === 'form' || source === 'raw') { requestBody = requestBodyObject(source, slot, schema) continue } parameters.push(...parameterObjects(source, slot, schema, visit.path)) }
const responses = await responseObjects( operation, problemDefinitions(visit.groups, visit.endpoint, operation), internal, options, ) const tags = uniqueStrings([ ...visit.groups.flatMap((group) => group.tags ?? []), ...(visit.endpoint.tags ?? []), ...(operation.tags ?? []), ])
return freezeOpenApi({ operationId: operation.operationId, ...(operation.summary !== undefined ? { summary: operation.summary } : {}), ...(operation.description !== undefined ? { description: operation.description } : {}), ...(tags.length > 0 ? { tags } : {}), ...(operation.deprecated === true ? { deprecated: true } : {}), ...(parameters.length > 0 ? { parameters } : {}), ...(requestBody !== undefined ? { requestBody } : {}), responses, })}
/** * Projects a validated endpoint input slot into OpenAPI parameter objects with the correct source and requiredness. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function parameterObjects( source: 'param' | 'query' | 'header' | 'cookie', slot: EndpointInputSlot, schema: unknown, path: string,): readonly Readonly<Record<string, unknown>>[] { const object = asJsonObject(schema) const documentedInput = documented(slot) if (!object || !isRecord(object.properties)) { if (source === 'param') { throw new TypeError(`Path schema for ${path} must project an object with one property per route parameter.`) } return [freezeOpenApi({ in: source, name: source, required: documentedInput?.required ?? false, schema, ...(documentedInput?.description !== undefined ? { description: documentedInput.description } : {}), ...examplesObject(documentedInput?.examples), })] }
const properties = object.properties const required = new Set(Array.isArray(object.required) ? object.required.filter(isString) : []) const pathNames = source === 'param' ? pathParameters(path) : [] if (source === 'param') { const projectedNames = Object.keys(properties) const missing = pathNames.filter((name) => !projectedNames.includes(name)) const extra = projectedNames.filter((name) => !pathNames.includes(name)) if (missing.length > 0 || extra.length > 0) { throw new TypeError( `Path parameter schema for ${path} does not match the route template ` + `(missing: ${missing.join(', ') || 'none'}; extra: ${extra.join(', ') || 'none'}).`, ) } }
return Object.freeze(Object.entries(properties).map(([name, property]) => { const nestedObject = asJsonObject(property)?.type === 'object' const nestedArray = asJsonObject(property)?.type === 'array' if (source === 'query' && nestedObject) { throw new TypeError( `Nested query parameter ${JSON.stringify(name)} has no declared wire serialization. ` + 'Use a flat query schema or add an explicit transport parser before documenting deep-object syntax.', ) } return freezeOpenApi({ in: source, name, required: source === 'param' || required.has(name), schema: property, ...(documentedInput?.description !== undefined && Object.keys(properties).length === 1 ? { description: documentedInput.description } : {}), ...(source === 'query' && nestedArray ? { style: 'form', explode: true } : {}), }) }))}
/** * Projects JSON, form, or raw endpoint input into the OpenAPI request-body shape. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function requestBodyObject( source: 'json' | 'form' | 'raw', slot: EndpointInputSlot, schema: unknown,): Readonly<Record<string, unknown>> { const input = documented(slot) const mediaType = input?.contentType ?? defaultContentType(source) return freezeOpenApi({ required: input?.required ?? true, ...(input?.description !== undefined ? { description: input.description } : {}), content: { [mediaType]: { schema, ...examplesObject(input?.examples), }, }, })}
/** * Projects declared successful responses and problems into the OpenAPI response map for one operation. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */async function responseObjects( operation: EndpointOperation, problems: readonly ProblemDefinition[], internal: boolean, options: OpenApiOptions,): Promise<Readonly<Record<string, unknown>>> { const byStatus = new Map<string, Readonly<Record<string, unknown>>[]>() for (const definition of definitionValues<ResponseDefinition>(operation.responses)) { appendStatus(byStatus, String(definition.status), await successResponseObject(definition, internal, options)) } for (const definition of problems) { if (definition.exposure === 'internal' && !internal) continue appendStatus(byStatus, String(definition.status), await problemResponseObject(definition, internal, options)) } if (byStatus.size === 0) { if (!operation.rawResponse) { throw new TypeError(`Public operation ${operation.id} declares no response or problem definitions.`) } byStatus.set('default', [freezeOpenApi({ description: 'Undocumented raw response.' })]) }
const result: Record<string, unknown> = Object.create(null) for (const [status, candidates] of byStatus) { result[status] = candidates.length === 1 ? candidates[0] : mergeResponses(candidates) } return freezeOpenApi(result)}
/** * Builds the success response object consumed by the endpoint OpenAPI projection. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */async function successResponseObject( definition: ResponseDefinition, internal: boolean, options: OpenApiOptions,): Promise<Readonly<Record<string, unknown>>> { const contentType = definition.contentType ?? defaultResponseContentType(definition) const result: Record<string, unknown> = { description: definition.description, } if (definition.headers && Object.keys(definition.headers).length > 0) { result.headers = Object.fromEntries(Object.entries(definition.headers).map(([name, value]) => [ name, freezeOpenApi({ schema: { type: 'string' }, example: value }), ])) } if (definition.schema !== undefined && definition.mode !== 'empty' && definition.mode !== 'redirect') { const projected = await projectBareSchema(definition.schema, internal, options, 'response') result.content = { [contentType]: { schema: responseBodySchema(definition, projected), ...responseExamplesObject(definition.examples), }, } } if (definition.mode === 'redirect') { result.headers = { ...(isRecord(result.headers) ? result.headers : {}), Location: { schema: { type: 'string', format: 'uri-reference' } }, } } return freezeOpenApi(result)}
/** * Builds the response body schema used to validate data entering the endpoint OpenAPI projection. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function responseBodySchema(definition: ResponseDefinition, schema: unknown): unknown { if (definition.mode === 'page') { const pagination = definition.pagination return freezeOpenApi({ type: 'object', required: ['data', 'meta'], properties: { data: { type: 'array', items: schema }, meta: { type: 'object', required: ['pagination'], properties: { pagination: paginationMetadataSchema( pagination?.totals === 'body' || pagination?.totals === 'both', ), }, additionalProperties: true, }, ...((pagination?.links === 'body' || pagination?.links === 'both') ? { links: paginationLinksSchema() } : {}), }, additionalProperties: false, }) } if (definition.envelope === 'data' || definition.timestamp) { return freezeOpenApi({ type: 'object', required: ['data'], properties: { data: schema, meta: { type: 'object', ...(definition.timestamp ? { properties: { timestamp: { type: 'string', format: 'date-time' } } } : {}), additionalProperties: true, }, }, additionalProperties: false, }) } return schema}
/** * Builds the pagination metadata schema used to validate data entering the endpoint OpenAPI projection. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function paginationMetadataSchema(includeTotals: boolean): Readonly<Record<string, unknown>> { return freezeOpenApi({ type: 'object', required: ['kind', 'limit', 'hasMore'], properties: { kind: { type: 'string', enum: ['cursor', 'offset'] }, limit: { type: 'integer', minimum: 1 }, hasMore: { type: 'boolean' }, cursor: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, page: { type: 'integer', minimum: 1 }, perPage: { type: 'integer', minimum: 1 }, ...(includeTotals ? { total: { type: 'integer', minimum: 0 }, approximateTotal: { type: 'integer', minimum: 0 }, totalPages: { type: 'integer', minimum: 0 }, } : {}), expiresAt: { type: 'string', format: 'date-time' }, }, additionalProperties: false, })}
/** * Builds the pagination links schema used to validate data entering the endpoint OpenAPI projection. * * @internal */function paginationLinksSchema(): Readonly<Record<string, unknown>> { const link = { type: 'string', format: 'uri-reference' } return freezeOpenApi({ type: 'object', properties: { self: link, first: link, previous: link, next: link, last: link }, additionalProperties: false, })}
/** * Builds the problem response object consumed by the endpoint OpenAPI projection. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */async function problemResponseObject( definition: ProblemDefinition, internal: boolean, options: OpenApiOptions,): Promise<Readonly<Record<string, unknown>>> { const extensionSchema = definition.extensions === undefined ? undefined : await projectBareSchema(definition.extensions.schema, internal, options, 'response') const extensionObject = asJsonObject(extensionSchema) const properties = { type: { type: 'string', const: definition.type, format: 'uri-reference' }, title: { type: 'string', const: definition.title }, status: { type: 'integer', const: definition.status }, detail: { type: 'string' }, instance: { type: 'string', format: 'uri-reference' }, ...(extensionObject && isRecord(extensionObject.properties) ? extensionObject.properties : {}), } return freezeOpenApi({ description: definition.description, content: { 'application/problem+json': { schema: { type: 'object', properties, required: ['type', 'title', 'status'], additionalProperties: extensionObject?.additionalProperties ?? true, }, ...problemExamplesObject(definition), }, }, })}
/** * Merges response projections while rejecting status-code collisions between success and problem definitions. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function mergeResponses( responses: readonly Readonly<Record<string, unknown>>[],): Readonly<Record<string, unknown>> { const descriptions = uniqueStrings(responses.map((response) => String(response.description ?? '')).filter(Boolean)) const media = new Map<string, unknown[]>() const headers: Record<string, unknown> = Object.create(null) for (const response of responses) { if (isRecord(response.headers)) Object.assign(headers, response.headers) if (!isRecord(response.content)) continue for (const [contentType, value] of Object.entries(response.content)) { if (!isRecord(value)) continue const schemas = media.get(contentType) ?? [] if (value.schema !== undefined) schemas.push(value.schema) media.set(contentType, schemas) } } const content: Record<string, unknown> = Object.create(null) for (const [contentType, schemas] of media) { content[contentType] = { schema: schemas.length === 1 ? schemas[0] : { oneOf: schemas }, } } return freezeOpenApi({ description: descriptions.join(' / ') || 'Response.', ...(Object.keys(headers).length > 0 ? { headers } : {}), ...(Object.keys(content).length > 0 ? { content } : {}), })}
/** * Adds one status-code response to the OpenAPI map and rejects a duplicate status owner. * * @internal */function appendStatus( byStatus: Map<string, Readonly<Record<string, unknown>>[]>, status: string, value: Readonly<Record<string, unknown>>,): void { const values = byStatus.get(status) ?? [] values.push(value) byStatus.set(status, values)}
/** * Projects schema into the narrower representation used by the endpoint OpenAPI projection. * * @internal */async function projectSchema( slot: EndpointInputSlot, internal: boolean, options: OpenApiOptions,): Promise<unknown> { const input = documented(slot) if (input?.jsonSchema !== undefined) return freezeOpenApi(input.jsonSchema) return await projectBareSchema(schemaOf(slot), internal, options, 'request')}
/** * Projects bare schema into the narrower representation used by the endpoint OpenAPI projection. * * @internal */async function projectBareSchema( schema: StandardSchemaV1, internal: boolean, options: OpenApiOptions, purpose: OpenApiSchemaProjectionContext['purpose'],): Promise<unknown> { const trait = (schema as StandardSchemaV1 & Partial<StandardJsonSchemaV1>)['~standard-json-schema'] if (trait) return freezeOpenApi(typeof trait.jsonSchema === 'function' ? await trait.jsonSchema() : trait.jsonSchema) const projected = await options.schemaProjector?.(schema, { purpose }) if (projected !== undefined) return freezeOpenApi(projected) if (internal) return freezeOpenApi({}) throw new TypeError('Public endpoint schema has no Standard JSON Schema projection or configured projector.')}
/** * Collects the problem definitions that the endpoint OpenAPI projection can expose as transport failures. * * @internal */function problemDefinitions( groups: readonly EndpointGroup[], endpoint: EndpointDefinition, operation: EndpointOperation,): readonly ProblemDefinition[] { return uniqueDefinitions([ ...groups.flatMap((group) => definitionValues<ProblemDefinition>(group.problems)), ...definitionValues<ProblemDefinition>(endpoint.problems), ...definitionValues<ProblemDefinition>(operation.problems), ])}
/** * Returns the definition values consumed by the endpoint OpenAPI projection. * * @internal */function definitionValues<Entry extends { readonly id: string; readonly kind: string }>( input: unknown,): readonly Entry[] { if (input === undefined) return Object.freeze([]) return catalog.values(input as Parameters<typeof catalog.values<Entry>>[0])}
/** * Traverses walk in deterministic order for the endpoint OpenAPI projection. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function walk(input: EndpointCompositionInput): readonly EndpointVisit[] { const result: EndpointVisit[] = [] const visit = ( value: EndpointCompositionInput, prefix: string, groups: readonly EndpointGroup[], ): void => { for (const entry of flatten(value)) { if (entry.kind === 'endpoint') { result.push(Object.freeze({ endpoint: entry, path: joinPath(prefix, entry.path), groups })) continue } if (entry.kind === 'endpoint-group-selection') { visit(entry.endpoints, prefix, groups) continue } visit(entry.endpoints, joinPath(prefix, entry.path), Object.freeze([...groups, entry])) } } visit(input, '', Object.freeze([])) return Object.freeze(result)}
/** * Flattens flatten into the ordered representation consumed by the endpoint OpenAPI projection. * * @internal */function flatten(input: EndpointCompositionInput): readonly EndpointEntry[] { return Array.isArray(input) ? Object.freeze(input.flatMap((entry) => flatten(entry))) : Object.freeze([input as EndpointEntry])}
/** * Checks whether internal satisfies the condition required by the endpoint OpenAPI projection. * * @internal */function isInternal( groups: readonly EndpointGroup[], endpoint: EndpointDefinition, operation: EndpointOperation,): boolean { return groups.some((group) => group.internal === true) || endpoint.internal === true || operation.internal === true}
/** * Projects schema documentation metadata only when the Standard Schema implementation exposes it. * * @internal */function documented(slot: EndpointInputSlot) { return typeof slot === 'object' && slot !== null && (slot as { kind?: unknown }).kind === 'endpoint-input' ? slot as Extract<EndpointInputSlot, { kind: 'endpoint-input' }> : undefined}
/** * Builds the examples object consumed by the endpoint OpenAPI projection. * * @internal */function examplesObject(examples: readonly EndpointExample[] | undefined): Readonly<Record<string, unknown>> { if (!examples || examples.length === 0) return Object.freeze({}) return freezeOpenApi({ examples: Object.fromEntries(examples.map((example) => [example.key, { ...(example.summary !== undefined ? { summary: example.summary } : {}), ...(example.description !== undefined ? { description: example.description } : {}), value: example.value, }])), })}
/** * Builds the response examples object consumed by the endpoint OpenAPI projection. * * @internal */function responseExamplesObject(examples: readonly ResponseExample[] | undefined): Readonly<Record<string, unknown>> { if (!examples || examples.length === 0) return Object.freeze({}) return freezeOpenApi({ examples: Object.fromEntries(examples.map((example) => [example.key, { ...(example.summary !== undefined ? { summary: example.summary } : {}), ...(example.description !== undefined ? { description: example.description } : {}), value: example.value, }])), })}
/** * Builds the problem examples object consumed by the endpoint OpenAPI projection. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function problemExamplesObject(definition: ProblemDefinition): Readonly<Record<string, unknown>> { if (!definition.examples || definition.examples.length === 0) return Object.freeze({}) return freezeOpenApi({ examples: Object.fromEntries(definition.examples.map((example) => [example.key, { ...(example.summary !== undefined ? { summary: example.summary } : {}), value: { type: definition.type, title: definition.title, status: definition.status, ...example.value, }, }])), })}
/** * Creates the fallback content type used when the endpoint OpenAPI projection receives no explicit value. * * @internal */function defaultContentType(source: 'json' | 'form' | 'raw'): string { if (source === 'json') return 'application/json' if (source === 'form') return 'application/x-www-form-urlencoded' return 'application/octet-stream'}
/** * Creates the fallback response content type used when the endpoint OpenAPI projection receives no explicit value. * * @internal */function defaultResponseContentType(definition: ResponseDefinition): string { if (definition.mode === 'download' || definition.mode === 'stream') return 'application/octet-stream' if (definition.mode === 'html') return 'text/html; charset=utf-8' return 'application/json'}
/** Normalize OpenAPI options before projection can observe caller mutation or accessors. @internal */function normalizeOptions(options: OpenApiOptions): OpenApiOptions { record.assert(options, 'OpenAPI options') if (typeof options.title !== 'string' || options.title.length === 0) throw new TypeError('OpenAPI title must be a non-empty string.') if (typeof options.version !== 'string' || options.version.length === 0) throw new TypeError('OpenAPI version must be a non-empty string.') if (options.description !== undefined && typeof options.description !== 'string') throw new TypeError('OpenAPI description must be a string.') if (options.includeInternal !== undefined && typeof options.includeInternal !== 'boolean') throw new TypeError('includeInternal must be a boolean.') if (options.schemaProjector !== undefined && typeof options.schemaProjector !== 'function') throw new TypeError('schemaProjector must be a function.') const servers = options.servers === undefined ? undefined : normalizeServers(options.servers) return Object.freeze({ title: options.title, version: options.version, ...(options.description !== undefined ? { description: options.description } : {}), ...(options.includeInternal !== undefined ? { includeInternal: options.includeInternal } : {}), ...(servers !== undefined ? { servers } : {}), ...(options.schemaProjector !== undefined ? { schemaProjector: options.schemaProjector } : {}), })}
/** Snapshot advertised servers as inert OpenAPI data. @internal */function normalizeServers(servers: readonly OpenApiServer[]): readonly OpenApiServer[] { if (!Array.isArray(servers)) throw new TypeError('OpenAPI servers must be an array.') const result: OpenApiServer[] = [] for (const server of servers) { record.assert(server, 'OpenAPI server') if (typeof server.url !== 'string' || server.url.length === 0) throw new TypeError('OpenAPI server URL must be a non-empty string.') if (server.description !== undefined && typeof server.description !== 'string') throw new TypeError('OpenAPI server description must be a string.') result.push(Object.freeze({ url: server.url, ...(server.description !== undefined ? { description: server.description } : {}) })) } return Object.freeze(result)}
/** * Opens api path for the endpoint OpenAPI projection and leaves its cleanup with the established owner. * * @internal */function openApiPath(path: string): string { return path.replace(/:([A-Za-z0-9_]+)/g, '{$1}')}
/** * Builds the as json object consumed by the endpoint OpenAPI projection. * * @internal */function asJsonObject(value: unknown): Readonly<Record<string, unknown>> | undefined { return isRecord(value) ? value : undefined}
/** * Checks whether record satisfies the condition required by the endpoint OpenAPI projection. * * @internal */function isRecord(value: unknown): value is Readonly<Record<string, unknown>> { return typeof value === 'object' && value !== null && !Array.isArray(value)}
/** * Checks whether string satisfies the condition required by the endpoint OpenAPI projection. * * @internal */function isString(value: unknown): value is string { return typeof value === 'string'}
/** * Generates the unique strings without colliding with identities already owned by the endpoint OpenAPI projection. * * @internal */function uniqueStrings(values: readonly string[]): readonly string[] { return Object.freeze([...new Set(values)])}
/** * Generates the unique definitions without colliding with identities already owned by the endpoint OpenAPI projection. * * The projection is derived from the exact imported endpoint graph so generated documentation cannot drift from executable contracts. * * @internal */function uniqueDefinitions<Entry extends { readonly id: string }>(values: readonly Entry[]): readonly Entry[] { const result: Entry[] = [] const owners = new Map<string, Entry>() const seen = new Set<Entry>() for (const value of values) { const owner = owners.get(value.id) if (owner && owner !== value) throw new TypeError(`Definition ID ${JSON.stringify(value.id)} belongs to different objects.`) owners.set(value.id, value) if (!seen.has(value)) { seen.add(value) result.push(value) } } return Object.freeze(result)}