Open History to see the last commit
1/**
2 * Schema extraction + bundling (PLAN.md task 2.2) — ported from PR #622's
3 * generate-endpoint-maps.ts, minus codegen: pure JSON manipulation, so it
4 * runs on Workers.
5 *
6 * Given an OpenAPI document and an endpoint path, extract the input schema
7 * (request body) and output schema, then inline the `$ref` closure under
8 * `$defs` so every schema is fully self-contained.
9 */
10import type { OpenApiDocument } from '#/server/providers/types.ts'
11
12/**
13 * Version of the extraction pipeline (classification + bundling), recorded
14 * on every schema_versions row. Bump whenever a change here or in a
15 * provider's classify/fetchSpec could alter derived schemas — it tells
16 * verifiers which extractor produced a stored hash.
17 */
18export const EXTRACTOR_VERSION = '2'
19
20export type JsonValue =
21 | string
22 | number
23 | boolean
24 | null
25 | { [key: string]: JsonValue }
26 | Array<JsonValue>
27
28const COMPONENT_REF_PREFIX = '#/components/schemas/'
29const DEFS_REF_PREFIX = '#/$defs/'
30
31export type OutputStrategy = 'post-200' | 'sibling-get'
32
33export interface BundleResult {
34 schema: Record<string, JsonValue>
35 warnings: Array<string>
36}
37
38export interface ExtractedEndpointSchemas {
39 /** Bundled, self-contained input schema; absent when the endpoint has no JSON/multipart body. */
40 input?: Record<string, JsonValue>
41 /**
42 * Media type the input schema was taken from. `multipart/form-data` when
43 * the call uploads a file. Absent when there is no body.
44 */
45 inputContentType?: string
46 /** Bundled output schema; absent for binary-media endpoints (TTS audio, …). */
47 output?: Record<string, JsonValue>
48 /**
49 * Bundled SSE (or NDJSON) event schema, set only when the success body also has a
50 * JSON schema. The JSON schema stays `output`. Absent when the only
51 * stored body is already the stream schema (speech).
52 */
53 streamOutput?: Record<string, JsonValue>
54 /**
55 * Success-response media types to publish. JSON and `text/event-stream`
56 * are both kept, on one operation in the generation document. Audio and
57 * other non-JSON types stay.
58 */
59 outputContentTypes?: Array<string>
60 warnings: Array<string>
61}
62
63function isObject(node: unknown): node is Record<string, JsonValue> {
64 return typeof node === 'object' && node !== null && !Array.isArray(node)
65}
66
67function collectComponentRefs(node: unknown, into: Set<string>): void {
68 if (typeof node !== 'object' || node === null) return
69 if (Array.isArray(node)) {
70 for (const value of node) collectComponentRefs(value, into)
71 return
72 }
73 for (const [key, value] of Object.entries(node)) {
74 if (
75 key === '$ref' &&
76 typeof value === 'string' &&
77 value.startsWith(COMPONENT_REF_PREFIX)
78 ) {
79 into.add(value.slice(COMPONENT_REF_PREFIX.length))
80 } else {
81 collectComponentRefs(value, into)
82 }
83 }
84}
85
86/**
87 * Rewrite component refs to their bundled location: refs to `rootName`
88 * become `#` (the schema itself — the PR let these dangle in $defs), all
89 * others move under `#/$defs/`.
90 */
91function rewriteRefs(node: JsonValue, rootName: string | null): JsonValue {
92 if (typeof node !== 'object' || node === null) return node
93 if (Array.isArray(node)) return node.map((v) => rewriteRefs(v, rootName))
94 const out: Record<string, JsonValue> = {}
95 for (const [key, value] of Object.entries(node)) {
96 if (
97 key === '$ref' &&
98 typeof value === 'string' &&
99 value.startsWith(COMPONENT_REF_PREFIX)
100 ) {
101 const refName = value.slice(COMPONENT_REF_PREFIX.length)
102 out[key] =
103 rootName !== null && refName === rootName
104 ? '#'
105 : DEFS_REF_PREFIX + refName
106 } else {
107 out[key] = rewriteRefs(value, rootName)
108 }
109 }
110 return out
111}
112
113/**
114 * Bundle a schema with its full `$ref` closure under `$defs`.
115 *
116 * `rootName` is the components key the root schema lives under (null for
117 * inline schemas); refs back to it are rewritten to `#`.
118 *
119 * Dedup-rename lesson from PR #622: when colliding schemas are renamed with
120 * a `-2` suffix, refs may say `Name-2` while the components key was
121 * sanitised to `Name_2` — resolve through the underscore alias so those
122 * defs don't dangle.
123 */
124export function bundleSchema(
125 root: JsonValue,
126 components: Record<string, JsonValue>,
127 rootName: string | null,
128 context: string,
129): BundleResult {
130 const warnings: Array<string> = []
131 const resolveSchema = (refName: string): JsonValue | undefined =>
132 components[refName] ?? components[refName.replace(/-/g, '_')]
133
134 const closure = new Set<string>()
135 const queue: Array<string> = []
136 const seedRefs = new Set<string>()
137 collectComponentRefs(root, seedRefs)
138 for (const ref of seedRefs) {
139 if (ref !== rootName) queue.push(ref)
140 }
141 while (queue.length > 0) {
142 const current = queue.shift()
143 if (current === undefined || closure.has(current)) continue
144 closure.add(current)
145 const target = resolveSchema(current)
146 if (target === undefined) {
147 warnings.push(
148 `${context}: ref target '${current}' not found (transitively referenced)`,
149 )
150 continue
151 }
152 const subRefs = new Set<string>()
153 collectComponentRefs(target, subRefs)
154 for (const ref of subRefs) {
155 if (ref !== rootName && !closure.has(ref)) queue.push(ref)
156 }
157 }
158
159 const rewrittenRoot = rewriteRefs(root, rootName)
160 const schema = isObject(rewrittenRoot) ? rewrittenRoot : {}
161 if (!isObject(rewrittenRoot)) {
162 warnings.push(`${context}: root schema is not an object`)
163 return { schema, warnings }
164 }
165 if (closure.size === 0) return { schema, warnings }
166
167 // An inline schema can carry its own `$defs` (Mistral's speech stream):
168 // keep them beside the component closure.
169 const defs: Record<string, JsonValue> = isObject(schema.$defs)
170 ? { ...schema.$defs }
171 : {}
172 for (const refName of [...closure].sort()) {
173 const target = resolveSchema(refName)
174 if (target === undefined) continue
175 const rewritten = rewriteRefs(target, rootName)
176 const local = defs[refName]
177 if (
178 local !== undefined &&
179 JSON.stringify(local) !== JSON.stringify(rewritten)
180 ) {
181 warnings.push(
182 `${context}: local $defs '${refName}' differs from the component of the same name; kept the local one`,
183 )
184 continue
185 }
186 defs[refName] = rewritten
187 }
188 return { schema: { ...schema, $defs: defs }, warnings }
189}
190
191interface MediaContent {
192 schema?: JsonValue
193}
194
195interface OperationShape {
196 requestBody?: { content?: Record<string, MediaContent> }
197 responses?: Record<string, { content?: Record<string, MediaContent> }>
198 parameters?: Array<{
199 name?: string
200 in?: string
201 required?: boolean
202 description?: string
203 schema?: JsonValue
204 }>
205}
206
207/** Path parameters as an object schema, for GETs that have no body. */
208function pathParameterSchema(
209 operation: OperationShape,
210): Record<string, JsonValue> | undefined {
211 const params = (operation.parameters ?? []).filter(
212 (param) => param.in === 'path' && typeof param.name === 'string',
213 )
214 if (params.length === 0) return undefined
215 const properties: Record<string, JsonValue> = {}
216 const required: Array<string> = []
217 for (const param of params) {
218 const name = param.name
219 if (typeof name !== 'string') continue
220 const schema: Record<string, JsonValue> = isObject(param.schema)
221 ? { ...param.schema }
222 : { type: 'string' }
223 if (typeof param.description === 'string') {
224 schema.description = param.description
225 }
226 properties[name] = schema
227 if (param.required === true) required.push(name)
228 }
229 return {
230 type: 'object',
231 properties,
232 ...(required.length > 0 ? { required } : {}),
233 }
234}
235
236function schemaComponents(spec: OpenApiDocument): Record<string, JsonValue> {
237 return (spec.components?.schemas ?? {}) as Record<string, JsonValue>
238}
239
240/**
241 * Resolve a content node to (root schema, rootName). A `$ref` schema
242 * resolves through components; an inline schema is used as-is.
243 */
244function resolveContentSchema(
245 content: MediaContent | undefined,
246 components: Record<string, JsonValue>,
247 context: string,
248 warnings: Array<string>,
249): { root: JsonValue; rootName: string | null } | undefined {
250 const schema = content?.schema
251 if (schema === undefined) return undefined
252 if (isObject(schema) && typeof schema.$ref === 'string') {
253 if (!schema.$ref.startsWith(COMPONENT_REF_PREFIX)) {
254 warnings.push(`${context}: unsupported ref '${schema.$ref}'`)
255 return undefined
256 }
257 const rootName = schema.$ref.slice(COMPONENT_REF_PREFIX.length)
258 const root = components[rootName] ?? components[rootName.replace(/-/g, '_')]
259 if (root === undefined) {
260 warnings.push(`${context}: root ref '${rootName}' not found`)
261 return undefined
262 }
263 return { root, rootName }
264 }
265 return { root: schema, rootName: null }
266}
267
268/** Media type without parameters, lowercased. */
269function mediaTypeBase(value: string): string {
270 return value.split(';')[0]?.trim().toLowerCase() ?? ''
271}
272
273function isJsonType(value: string): boolean {
274 const base = mediaTypeBase(value)
275 return base === 'application/json' || base.endsWith('+json')
276}
277
278function isEventStream(value: string): boolean {
279 const base = mediaTypeBase(value)
280 return base === 'text/event-stream' || base.endsWith('/event-stream')
281}
282
283/** SSE, or Ollama's newline-delimited JSON (`application/x-ndjson`). */
284function isStreamType(value: string): boolean {
285 return isEventStream(value) || mediaTypeBase(value) === 'application/x-ndjson'
286}
287
288/** AWS binary event stream. Not SSE, so it is not rewritten to `text/event-stream`. */
289function isAwsEventStream(value: string): boolean {
290 return mediaTypeBase(value) === 'application/vnd.amazon.eventstream'
291}
292
293function isMultipart(value: string): boolean {
294 return mediaTypeBase(value) === 'multipart/form-data'
295}
296
297/**
298 * Type stored and published. Stream types collapse to `text/event-stream`
299 * so hey-api's exact media-type check selects the SSE client.
300 */
301function canonicalMediaType(value: string): string {
302 if (isEventStream(value)) return 'text/event-stream'
303 if (isMultipart(value)) return 'multipart/form-data'
304 if (isJsonType(value)) return 'application/json'
305 return mediaTypeBase(value)
306}
307
308function schemaHasBinary(node: JsonValue, depth = 0): boolean {
309 if (depth > 8 || typeof node !== 'object' || node === null) return false
310 if (Array.isArray(node)) {
311 return node.some((item) => schemaHasBinary(item, depth + 1))
312 }
313 if (node.format === 'binary' || typeof node.contentMediaType === 'string') {
314 return true
315 }
316 return Object.values(node).some((value) => schemaHasBinary(value, depth + 1))
317}
318
319/**
320 * Content types to put on the generation document's success response.
321 * See `ExtractedEndpointSchemas.outputContentTypes`. A boolean `stream`
322 * field is not a media type: SSE is published only when the success
323 * body lists an event-stream type.
324 */
325export function responseContentTypesFor(
326 content: Record<string, MediaContent> | undefined,
327): Array<string> | undefined {
328 if (!content) return undefined
329 const types: Array<string> = []
330 for (const raw of Object.keys(content)) {
331 const type = canonicalMediaType(raw)
332 if (type !== '' && !types.includes(type)) types.push(type)
333 }
334 return types.length > 0 ? types : undefined
335}
336
337/**
338 * Extract + bundle the input/output schemas for one endpoint.
339 *
340 * Input: request body. A file upload (`multipart/form-data`, or a multipart
341 * schema that contains a binary field) wins over `application/json` —
342 * declaring both makes `@hey-api/openapi-ts` send the file as JSON.
343 *
344 * Output schema stays the JSON success body when one exists (200/201/202,
345 * or the sibling GET for FAL). When that body also lists an event-stream
346 * schema, `streamOutput` is that schema. A boolean `stream` property does
347 * not invent a stream response.
348 */
349export function extractEndpointSchemas(
350 spec: OpenApiDocument,
351 pathKey: string,
352 strategy: OutputStrategy = 'post-200',
353 method: 'post' | 'get' | 'delete' = 'post',
354): ExtractedEndpointSchemas {
355 const warnings: Array<string> = []
356 const components = schemaComponents(spec)
357 const operation = spec.paths?.[pathKey]?.[method] as
358 | OperationShape
359 | undefined
360 if (!operation) return { warnings }
361 const post = operation
362
363 let input: Record<string, JsonValue> | undefined
364 let inputContentType: string | undefined
365 const chosenRequest = chooseRequestContent(post.requestBody?.content)
366 if (chosenRequest) {
367 const probe: Array<string> = []
368 const probed = resolveContentSchema(
369 chosenRequest.media,
370 components,
371 `${pathKey} input`,
372 probe,
373 )
374 const multipartLosesToJson =
375 chosenRequest.contentType === 'multipart/form-data' &&
376 probed !== undefined &&
377 !schemaHasBinary(probed.root) &&
378 hasJsonBody(post.requestBody?.content)
379 const requestMedia = multipartLosesToJson
380 ? jsonBody(post.requestBody?.content)
381 : chosenRequest
382 if (requestMedia) {
383 inputContentType = requestMedia.contentType
384 const resolved =
385 requestMedia === chosenRequest
386 ? probed
387 : resolveContentSchema(
388 requestMedia.media,
389 components,
390 `${pathKey} input`,
391 warnings,
392 )
393 if (requestMedia === chosenRequest) warnings.push(...probe)
394 if (resolved) {
395 const bundled = bundleSchema(
396 resolved.root,
397 components,
398 resolved.rootName,
399 `${pathKey} input`,
400 )
401 input = bundled.schema
402 warnings.push(...bundled.warnings)
403 }
404 }
405 } else if (method === 'get' || method === 'delete') {
406 input = pathParameterSchema(operation)
407 }
408
409 const responses =
410 strategy === 'sibling-get'
411 ? (
412 spec.paths?.[`${pathKey}/requests/{request_id}`]?.get as
413 | OperationShape
414 | undefined
415 )?.responses
416 : post.responses
417 const bound = bindSuccessContent(responses)
418 const outputMedia =
419 bound?.json ??
420 (bound?.stream?.schema !== undefined ? bound.stream : undefined)
421
422 let output: Record<string, JsonValue> | undefined
423 const outputResolved = resolveContentSchema(
424 outputMedia,
425 components,
426 `${pathKey} output`,
427 warnings,
428 )
429 if (outputResolved) {
430 const bundled = bundleSchema(
431 outputResolved.root,
432 components,
433 outputResolved.rootName,
434 `${pathKey} output`,
435 )
436 output = bundled.schema
437 warnings.push(...bundled.warnings)
438 }
439
440 let streamOutput: Record<string, JsonValue> | undefined
441 if (bound?.json && bound.stream?.schema !== undefined) {
442 const streamResolved = resolveContentSchema(
443 bound.stream,
444 components,
445 `${pathKey} stream`,
446 warnings,
447 )
448 if (streamResolved) {
449 const bundled = bundleSchema(
450 streamResolved.root,
451 components,
452 streamResolved.rootName,
453 `${pathKey} stream`,
454 )
455 streamOutput = bundled.schema
456 warnings.push(...bundled.warnings)
457 }
458 }
459
460 const outputContentTypes = responseContentTypesFor(bound?.content)
461
462 return {
463 ...(input ? { input } : {}),
464 ...(inputContentType ? { inputContentType } : {}),
465 ...(output ? { output } : {}),
466 ...(streamOutput ? { streamOutput } : {}),
467 ...(outputContentTypes ? { outputContentTypes } : {}),
468 warnings,
469 }
470}
471
472interface ChosenContent {
473 media: MediaContent
474 contentType: string
475}
476
477function chooseRequestContent(
478 content: Record<string, MediaContent> | undefined,
479): ChosenContent | undefined {
480 if (!content) return undefined
481 const entries = Object.entries(content).filter(
482 (entry): entry is [string, MediaContent] => entry[1].schema !== undefined,
483 )
484 const multipart = entries.find(([type]) => isMultipart(type))
485 if (multipart) {
486 return {
487 media: multipart[1],
488 contentType: canonicalMediaType(multipart[0]),
489 }
490 }
491 const json = entries.find(([type]) => isJsonType(type))
492 const chosen = json ?? entries[0]
493 if (!chosen) return undefined
494 return { media: chosen[1], contentType: canonicalMediaType(chosen[0]) }
495}
496
497function hasJsonBody(
498 content: Record<string, MediaContent> | undefined,
499): boolean {
500 return jsonBody(content) !== undefined
501}
502
503function jsonBody(
504 content: Record<string, MediaContent> | undefined,
505): ChosenContent | undefined {
506 if (!content) return undefined
507 const json = Object.entries(content).find(
508 ([type, media]) => isJsonType(type) && media.schema !== undefined,
509 )
510 if (!json) return undefined
511 return { media: json[1], contentType: 'application/json' }
512}
513
514interface BoundSuccess {
515 content: Record<string, MediaContent>
516 json?: MediaContent
517 stream?: MediaContent
518}
519
520/**
521 * First success status that carries a JSON schema, otherwise the first
522 * success status that carries any content. The JSON schema is what we
523 * store; `content` is the map whose media types are published.
524 */
525function bindSuccessContent(
526 responses: OperationShape['responses'],
527): BoundSuccess | undefined {
528 if (!responses) return undefined
529 let first: Record<string, MediaContent> | undefined
530 for (const status of ['200', '201', '202']) {
531 const content = responses[status]?.content
532 if (!content || Object.keys(content).length === 0) continue
533 if (!first) first = content
534 const json = Object.entries(content).find(
535 ([type, media]) => isJsonType(type) && media.schema !== undefined,
536 )
537 if (json) {
538 const stream = Object.entries(content).find(([type]) =>
539 isStreamType(type),
540 )
541 return {
542 content,
543 json: json[1],
544 ...(stream ? { stream: stream[1] } : {}),
545 }
546 }
547 }
548 if (!first) return undefined
549 const stream = Object.entries(first).find(
550 ([type, media]) =>
551 (isStreamType(type) || isAwsEventStream(type)) &&
552 media.schema !== undefined,
553 )
554 return { content: first, ...(stream ? { stream: stream[1] } : {}) }
555}
556
557/** Endpoint id convention from the PR: the path minus its leading slash. */
558export function endpointIdFromPath(pathKey: string): string {
559 return pathKey.replace(/^\//, '')
560}
561
562/**
563 * Verify a bundled schema is self-contained: every `$ref` is either `#` or
564 * `#/$defs/<name>` with `<name>` present in the top-level `$defs`. Returns
565 * the list of violations (empty = self-contained). Exported for tests and
566 * sync-time sanity checks.
567 */
568export function findDanglingRefs(
569 schema: Record<string, JsonValue>,
570): Array<string> {
571 const defs = isObject(schema.$defs) ? schema.$defs : {}
572 const violations: Array<string> = []
573 const walk = (node: JsonValue): void => {
574 if (typeof node !== 'object' || node === null) return
575 if (Array.isArray(node)) {
576 node.forEach(walk)
577 return
578 }
579 for (const [key, value] of Object.entries(node)) {
580 if (key === '$ref' && typeof value === 'string') {
581 if (value === '#') continue
582 if (value.startsWith(DEFS_REF_PREFIX)) {
583 const name = value.slice(DEFS_REF_PREFIX.length)
584 if (!(name in defs)) violations.push(value)
585 continue
586 }
587 violations.push(value)
588 } else {
589 walk(value)
590 }
591 }
592 }
593 walk(schema)
594 return violations
595}