Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

bundle.ts

357 lines11.2 KB

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 = '1'
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>
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 /** Bundled output schema; absent for binary-media endpoints (TTS audio, …). */
42 output?: Record<string, JsonValue>
43 warnings: Array<string>
45​
46function isObject(node: unknown): node is Record<string, JsonValue> {
47 return typeof node === 'object' && node !== null && !Array.isArray(node)
49​
50function collectComponentRefs(node: unknown, into: Set<string>): void {
51 if (typeof node !== 'object' || node === null) return
52 if (Array.isArray(node)) {
53 for (const value of node) collectComponentRefs(value, into)
54 return
55 }
56 for (const [key, value] of Object.entries(node)) {
57 if (
58 key === '$ref' &&
59 typeof value === 'string' &&
60 value.startsWith(COMPONENT_REF_PREFIX)
61 ) {
62 into.add(value.slice(COMPONENT_REF_PREFIX.length))
63 } else {
64 collectComponentRefs(value, into)
65 }
66 }
68​
69/**
70 * Rewrite component refs to their bundled location: refs to `rootName`
71 * become `#` (the schema itself — the PR let these dangle in $defs), all
72 * others move under `#/$defs/`.
73 */
74function rewriteRefs(node: JsonValue, rootName: string | null): JsonValue {
75 if (typeof node !== 'object' || node === null) return node
76 if (Array.isArray(node)) return node.map((v) => rewriteRefs(v, rootName))
77 const out: Record<string, JsonValue> = {}
78 for (const [key, value] of Object.entries(node)) {
79 if (
80 key === '$ref' &&
81 typeof value === 'string' &&
82 value.startsWith(COMPONENT_REF_PREFIX)
83 ) {
84 const refName = value.slice(COMPONENT_REF_PREFIX.length)
85 out[key] =
86 rootName !== null && refName === rootName
87 ? '#'
88 : DEFS_REF_PREFIX + refName
89 } else {
90 out[key] = rewriteRefs(value, rootName)
91 }
92 }
93 return out
95​
96/**
97 * Bundle a schema with its full `$ref` closure under `$defs`.
98 *
99 * `rootName` is the components key the root schema lives under (null for
100 * inline schemas); refs back to it are rewritten to `#`.
101 *
102 * Dedup-rename lesson from PR #622: when colliding schemas are renamed with
103 * a `-2` suffix, refs may say `Name-2` while the components key was
104 * sanitised to `Name_2` — resolve through the underscore alias so those
105 * defs don't dangle.
106 */
107export function bundleSchema(
108 root: JsonValue,
109 components: Record<string, JsonValue>,
110 rootName: string | null,
111 context: string,
112): BundleResult {
113 const warnings: Array<string> = []
114 const resolveSchema = (refName: string): JsonValue | undefined =>
115 components[refName] ?? components[refName.replace(/-/g, '_')]
116​
117 const closure = new Set<string>()
118 const queue: Array<string> = []
119 const seedRefs = new Set<string>()
120 collectComponentRefs(root, seedRefs)
121 for (const ref of seedRefs) {
122 if (ref !== rootName) queue.push(ref)
123 }
124 while (queue.length > 0) {
125 const current = queue.shift()
126 if (current === undefined || closure.has(current)) continue
127 closure.add(current)
128 const target = resolveSchema(current)
129 if (target === undefined) {
130 warnings.push(
131 `${context}: ref target '${current}' not found (transitively referenced)`,
132 )
133 continue
134 }
135 const subRefs = new Set<string>()
136 collectComponentRefs(target, subRefs)
137 for (const ref of subRefs) {
138 if (ref !== rootName && !closure.has(ref)) queue.push(ref)
139 }
140 }
141​
142 const rewrittenRoot = rewriteRefs(root, rootName)
143 const schema = isObject(rewrittenRoot) ? rewrittenRoot : { ...{} }
144 if (!isObject(rewrittenRoot)) {
145 warnings.push(`${context}: root schema is not an object`)
146 return { schema, warnings }
147 }
148 if (closure.size === 0) return { schema, warnings }
149​
150 const defs: Record<string, JsonValue> = {}
151 for (const refName of [...closure].sort()) {
152 const target = resolveSchema(refName)
153 if (target === undefined) continue
154 defs[refName] = rewriteRefs(target, rootName)
155 }
156 return { schema: { ...schema, $defs: defs }, warnings }
158​
159interface MediaContent {
160 schema?: JsonValue
162​
163interface OperationShape {
164 requestBody?: { content?: Record<string, MediaContent> }
165 responses?: Record<string, { content?: Record<string, MediaContent> }>
166 parameters?: Array<{
167 name?: string
168 in?: string
169 required?: boolean
170 description?: string
171 schema?: JsonValue
172 }>
174​
175/** Path parameters as an object schema, for GETs that have no body. */
176function pathParameterSchema(
177 operation: OperationShape,
178): Record<string, JsonValue> | undefined {
179 const params = (operation.parameters ?? []).filter(
180 (param) => param.in === 'path' && typeof param.name === 'string',
181 )
182 if (params.length === 0) return undefined
183 const properties: Record<string, JsonValue> = {}
184 const required: Array<string> = []
185 for (const param of params) {
186 const name = param.name
187 if (typeof name !== 'string') continue
188 const schema: Record<string, JsonValue> = isObject(param.schema)
189 ? { ...param.schema }
190 : { type: 'string' }
191 if (typeof param.description === 'string') {
192 schema.description = param.description
193 }
194 properties[name] = schema
195 if (param.required === true) required.push(name)
196 }
197 return {
198 type: 'object',
199 properties,
200 ...(required.length > 0 ? { required } : {}),
201 }
203​
204function schemaComponents(spec: OpenApiDocument): Record<string, JsonValue> {
205 return (spec.components?.schemas ?? {}) as Record<string, JsonValue>
207​
208/**
209 * Resolve a content node to (root schema, rootName). A `$ref` schema
210 * resolves through components; an inline schema is used as-is.
211 */
212function resolveContentSchema(
213 content: MediaContent | undefined,
214 components: Record<string, JsonValue>,
215 context: string,
216 warnings: Array<string>,
217): { root: JsonValue; rootName: string | null } | undefined {
218 const schema = content?.schema
219 if (schema === undefined) return undefined
220 if (isObject(schema) && typeof schema.$ref === 'string') {
221 if (!schema.$ref.startsWith(COMPONENT_REF_PREFIX)) {
222 warnings.push(`${context}: unsupported ref '${schema.$ref}'`)
223 return undefined
224 }
225 const rootName = schema.$ref.slice(COMPONENT_REF_PREFIX.length)
226 const root = components[rootName] ?? components[rootName.replace(/-/g, '_')]
227 if (root === undefined) {
228 warnings.push(`${context}: root ref '${rootName}' not found`)
229 return undefined
230 }
231 return { root, rootName }
232 }
233 return { root: schema, rootName: null }
235​
236/**
237 * Extract + bundle the input/output schemas for one endpoint.
238 *
239 * Input: request body — `application/json`, falling back to
240 * `multipart/form-data` (media endpoints take multipart uploads whose
241 * fields are described by an ordinary schema; the PR's multipart fix).
242 *
243 * Output:
244 * - 'post-200': first success response (200/201/202 — ElevenLabs dubbing
245 * acks with 201, OpenRouter video jobs with 202) carrying a JSON schema.
246 * - 'sibling-get': the sibling GET `${path}/requests/{request_id}` 200
247 * response (FAL: the POST returns a queue ack).
248 */
249export function extractEndpointSchemas(
250 spec: OpenApiDocument,
251 pathKey: string,
252 strategy: OutputStrategy = 'post-200',
253 method: 'post' | 'get' = 'post',
254): ExtractedEndpointSchemas {
255 const warnings: Array<string> = []
256 const components = schemaComponents(spec)
257 const operation = spec.paths?.[pathKey]?.[method] as
258 | OperationShape
259 | undefined
260 if (!operation) return { warnings }
261 const post = operation
262​
263 let input: Record<string, JsonValue> | undefined
264 const requestContent = post.requestBody?.content
265 const inputResolved = resolveContentSchema(
266 requestContent?.['application/json'] ??
267 requestContent?.['multipart/form-data'],
268 components,
269 `${pathKey} input`,
270 warnings,
271 )
272 if (inputResolved) {
273 const bundled = bundleSchema(
274 inputResolved.root,
275 components,
276 inputResolved.rootName,
277 `${pathKey} input`,
278 )
279 input = bundled.schema
280 warnings.push(...bundled.warnings)
281 } else if (method === 'get') {
282 input = pathParameterSchema(operation)
283 }
284​
285 let outputContent: MediaContent | undefined
286 if (strategy === 'sibling-get') {
287 const sibling = spec.paths?.[`${pathKey}/requests/{request_id}`]?.get as
288 | OperationShape
289 | undefined
290 outputContent = sibling?.responses?.['200']?.content?.['application/json']
291 } else {
292 for (const status of ['200', '201', '202']) {
293 outputContent = post.responses?.[status]?.content?.['application/json']
294 if (outputContent?.schema !== undefined) break
295 }
296 }
297​
298 let output: Record<string, JsonValue> | undefined
299 const outputResolved = resolveContentSchema(
300 outputContent,
301 components,
302 `${pathKey} output`,
303 warnings,
304 )
305 if (outputResolved) {
306 const bundled = bundleSchema(
307 outputResolved.root,
308 components,
309 outputResolved.rootName,
310 `${pathKey} output`,
311 )
312 output = bundled.schema
313 warnings.push(...bundled.warnings)
314 }
315​
316 return { input, output, warnings }
318​
319/** Endpoint id convention from the PR: the path minus its leading slash. */
320export function endpointIdFromPath(pathKey: string): string {
321 return pathKey.replace(/^\//, '')
323​
324/**
325 * Verify a bundled schema is self-contained: every `$ref` is either `#` or
326 * `#/$defs/<name>` with `<name>` present in the top-level `$defs`. Returns
327 * the list of violations (empty = self-contained). Exported for tests and
328 * sync-time sanity checks.
329 */
330export function findDanglingRefs(
331 schema: Record<string, JsonValue>,
332): Array<string> {
333 const defs = isObject(schema.$defs) ? schema.$defs : {}
334 const violations: Array<string> = []
335 const walk = (node: JsonValue): void => {
336 if (typeof node !== 'object' || node === null) return
337 if (Array.isArray(node)) {
338 node.forEach(walk)
339 return
340 }
341 for (const [key, value] of Object.entries(node)) {
342 if (key === '$ref' && typeof value === 'string') {
343 if (value === '#') continue
344 if (value.startsWith(DEFS_REF_PREFIX)) {
345 const name = value.slice(DEFS_REF_PREFIX.length)
346 if (!(name in defs)) violations.push(value)
347 continue
348 }
349 violations.push(value)
350 } else {
351 walk(value)
352 }
353 }
354 }
355 walk(schema)
356 return violations