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

bundle.test.ts

385 lines12.0 KB

1import { describe, expect, it } from 'vitest'
2​
3import type { OpenApiDocument } from '#/server/providers/types.ts'
4import {
5 bundleSchema,
6 endpointIdFromPath,
7 extractEndpointSchemas,
8 findDanglingRefs,
9} from './bundle.ts'
10import type { JsonValue } from './bundle.ts'
11​
12const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` })
13​
14function fixtureSpec(): OpenApiDocument {
15 return {
16 openapi: '3.1.0',
17 paths: {
18 '/v1/messages': {
19 post: {
20 requestBody: {
21 content: { 'application/json': { schema: ref('CreateMessage') } },
22 },
23 responses: {
24 '200': {
25 content: { 'application/json': { schema: ref('Message') } },
26 },
27 },
28 },
29 },
30 '/v1/audio/transcriptions': {
31 post: {
32 requestBody: {
33 content: {
34 'multipart/form-data': { schema: ref('TranscriptionRequest') },
35 },
36 },
37 responses: {
38 '201': {
39 content: { 'application/json': { schema: ref('Transcription') } },
40 },
41 },
42 },
43 },
44 '/v1/audio/speech': {
45 post: {
46 requestBody: {
47 content: { 'application/json': { schema: ref('SpeechRequest') } },
48 },
49 responses: {
50 '200': { content: { 'audio/mpeg': {} } },
51 },
52 },
53 },
54 '/fal-ai/veo': {
55 post: {
56 requestBody: {
57 content: { 'application/json': { schema: ref('VeoInput') } },
58 },
59 responses: {
60 '200': {
61 content: { 'application/json': { schema: ref('QueueStatus') } },
62 },
63 },
64 },
65 },
66 '/fal-ai/veo/requests/{request_id}': {
67 get: {
68 responses: {
69 '200': {
70 content: { 'application/json': { schema: ref('VeoOutput') } },
71 },
72 },
73 },
74 },
75 },
76 components: {
77 schemas: {
78 CreateMessage: {
79 type: 'object',
80 properties: {
81 content: { type: 'array', items: ref('ContentBlock') },
82 tool: ref('Tool'),
83 },
84 },
85 ContentBlock: {
86 type: 'object',
87 properties: { nested: ref('Tool') },
88 },
89 Tool: { type: 'object', properties: { name: { type: 'string' } } },
90 Message: {
91 type: 'object',
92 properties: { blocks: { type: 'array', items: ref('ContentBlock') } },
93 },
94 TranscriptionRequest: {
95 type: 'object',
96 properties: { file: { type: 'string', format: 'binary' } },
97 },
98 Transcription: { type: 'object' },
99 SpeechRequest: { type: 'object' },
100 VeoInput: { type: 'object' },
101 QueueStatus: { type: 'object' },
102 VeoOutput: {
103 type: 'object',
104 properties: { video: ref('VideoFile') },
105 },
106 VideoFile: { type: 'object' },
107 },
108 },
109 }
111​
112describe('extractEndpointSchemas', () => {
113 it('bundles json input + post-200 output with the full $ref closure', () => {
114 const result = extractEndpointSchemas(fixtureSpec(), '/v1/messages')
115 expect(result.warnings).toEqual([])
116 expect(result.input?.type).toBe('object')
117 const defs = result.input?.$defs as Record<string, unknown>
118 expect(Object.keys(defs).sort()).toEqual(['ContentBlock', 'Tool'])
119 expect(findDanglingRefs(result.input ?? {})).toEqual([])
120 expect(findDanglingRefs(result.output ?? {})).toEqual([])
121 })
122​
123 it('handles multipart/form-data bodies and 201 success responses', () => {
124 const result = extractEndpointSchemas(
125 fixtureSpec(),
126 '/v1/audio/transcriptions',
127 )
128 expect(result.input).toBeDefined()
129 expect(result.inputContentType).toBe('multipart/form-data')
130 expect(
131 (result.input!.properties as Record<string, Record<string, unknown>>).file
132 ?.format,
133 ).toBe('binary')
134 expect(result.output).toBeDefined()
135 expect(result.outputContentTypes).toEqual(['application/json'])
136 })
137​
138 it('omits output for binary-media endpoints and keeps the audio type', () => {
139 const result = extractEndpointSchemas(fixtureSpec(), '/v1/audio/speech')
140 expect(result.input).toBeDefined()
141 expect(result.inputContentType).toBe('application/json')
142 expect(result.output).toBeUndefined()
143 expect(result.outputContentTypes).toEqual(['audio/mpeg'])
144 })
145​
146 it('keeps JSON and stores the event-stream schema separately', () => {
147 const spec = structuredClone(fixtureSpec())
148 const post = spec.paths?.['/v1/messages']?.post as
149 | {
150 responses?: Record<string, { content?: Record<string, unknown> }>
151 }
152 | undefined
153 const ok = post?.responses?.['200']
154 const schemas = spec.components?.schemas
155 if (!ok?.content || !schemas)
156 throw new Error('fixture missing /v1/messages')
157 schemas.Chunk = {
158 type: 'object',
159 properties: { delta: { type: 'string' } },
160 }
161 ok.content['text/event-stream'] = {
162 schema: { $ref: '#/components/schemas/Chunk' },
163 }
164 const result = extractEndpointSchemas(spec, '/v1/messages')
165 expect(result.inputContentType).toBe('application/json')
166 expect(result.outputContentTypes).toEqual([
167 'application/json',
168 'text/event-stream',
169 ])
170 expect(result.output?.$defs).toBeDefined()
171 expect(result.streamOutput).toMatchObject({
172 type: 'object',
173 properties: { delta: { type: 'string' } },
174 })
175 expect(result.streamOutput?.$defs).toBeUndefined()
176 })
177​
178 it('stores an AWS event stream as the output schema', () => {
179 const result = extractEndpointSchemas(
180 {
181 openapi: '3.1.0',
182 paths: {
183 '/model/{modelId}/converse-stream': {
184 post: {
185 responses: {
186 '200': {
187 content: {
188 'application/vnd.amazon.eventstream': {
189 schema: {
190 type: 'object',
191 minProperties: 1,
192 maxProperties: 1,
193 properties: {
194 messageStart: { type: 'object' },
195 },
196 },
197 },
198 },
199 },
200 },
201 },
202 },
203 },
204 },
205 '/model/{modelId}/converse-stream',
206 )
207 expect(result.outputContentTypes).toEqual([
208 'application/vnd.amazon.eventstream',
209 ])
210 expect(result.streamOutput).toBeUndefined()
211 expect(result.output).toEqual({
212 type: 'object',
213 minProperties: 1,
214 maxProperties: 1,
215 properties: { messageStart: { type: 'object' } },
216 })
217 })
218​
219 it('does not treat a boolean stream field as an event stream', () => {
220 const spec = structuredClone(fixtureSpec())
221 const create = spec.components?.schemas?.CreateMessage as
222 | { properties?: Record<string, unknown> }
223 | undefined
224 if (!create?.properties) throw new Error('fixture missing CreateMessage')
225 create.properties.stream = {
226 type: 'boolean',
227 description: 'Whether to stream the response using server-sent events.',
228 }
229 const result = extractEndpointSchemas(spec, '/v1/messages')
230 expect(result.outputContentTypes).toEqual(['application/json'])
231 expect(result.streamOutput).toBeUndefined()
232 })
233​
234 it('keeps audio types beside an event stream when the success body is not JSON', () => {
235 const spec = structuredClone(fixtureSpec())
236 const post = spec.paths?.['/v1/audio/speech']?.post as
237 | {
238 responses?: Record<string, { content?: Record<string, unknown> }>
239 }
240 | undefined
241 const ok = post?.responses?.['200']
242 if (!ok) throw new Error('fixture missing speech')
243 ok.content = {
244 'application/octet-stream': { schema: { type: 'string' } },
245 'audio/mpeg': { schema: { type: 'string' } },
246 'text/event-stream': {
247 schema: { $ref: '#/components/schemas/Message' },
248 },
249 }
250 const result = extractEndpointSchemas(spec, '/v1/audio/speech')
251 expect(result.outputContentTypes).toEqual([
252 'application/octet-stream',
253 'audio/mpeg',
254 'text/event-stream',
255 ])
256 expect(result.output?.type).toBe('object')
257 })
258​
259 it('uses the sibling GET for the sibling-get strategy', () => {
260 const result = extractEndpointSchemas(
261 fixtureSpec(),
262 '/fal-ai/veo',
263 'sibling-get',
264 )
265 const defs = result.output?.$defs as Record<string, unknown>
266 expect(Object.keys(defs)).toEqual(['VideoFile'])
267 expect(findDanglingRefs(result.output ?? {})).toEqual([])
268 })
269​
270 it('returns nothing for unknown paths', () => {
271 expect(extractEndpointSchemas(fixtureSpec(), '/nope')).toEqual({
272 warnings: [],
273 })
274 })
275})
276​
277describe('bundleSchema', () => {
278 const components: Record<string, JsonValue> = {
279 Root: {
280 type: 'object',
281 properties: {
282 child: { $ref: '#/components/schemas/Child' },
283 self: { $ref: '#/components/schemas/Root' },
284 },
285 },
286 Child: {
287 type: 'object',
288 properties: { parent: { $ref: '#/components/schemas/Root' } },
289 },
290 }
291​
292 it('rewrites self-references to # instead of leaving dangling defs', () => {
293 const { schema, warnings } = bundleSchema(
294 components.Root ?? null,
295 components,
296 'Root',
297 'test',
298 )
299 expect(warnings).toEqual([])
300 const props = schema.properties as Record<string, Record<string, unknown>>
301 expect(props.self?.$ref).toBe('#')
302 expect(props.child?.$ref).toBe('#/$defs/Child')
303 const defs = schema.$defs as Record<string, Record<string, unknown>>
304 expect(Object.keys(defs)).toEqual(['Child'])
305 expect(
306 (defs.Child!.properties as Record<string, Record<string, unknown>>).parent
307 ?.$ref,
308 ).toBe('#')
309 expect(findDanglingRefs(schema)).toEqual([])
310 })
311​
312 it('resolves dedup-renamed refs through the underscore alias (PR #622 lesson)', () => {
313 const merged: Record<string, JsonValue> = {
314 Input: {
315 type: 'object',
316 properties: { shared: { $ref: '#/components/schemas/Shared-2' } },
317 },
318 // The merge step sanitised the components key to an underscore...
319 Shared_2: { type: 'object', properties: { ok: { type: 'boolean' } } },
320 }
321 const { schema, warnings } = bundleSchema(
322 merged.Input ?? null,
323 merged,
324 'Input',
325 'test',
326 )
327 expect(warnings).toEqual([])
328 // ...so the bundled $defs carries the ref's spelling, resolved via alias.
329 const defs = schema.$defs as Record<string, unknown>
330 expect(defs['Shared-2']).toBeDefined()
331 expect(findDanglingRefs(schema)).toEqual([])
332 })
333​
334 it("keeps an inline schema's own $defs beside the component closure (Mistral speech stream)", () => {
335 const { schema, warnings } = bundleSchema(
336 {
337 type: 'object',
338 properties: {
339 event: { $ref: '#/$defs/EventTypes' },
340 data: { $ref: '#/components/schemas/Delta' },
341 },
342 $defs: { EventTypes: { type: 'string', enum: ['delta'] } },
343 },
344 { Delta: { type: 'object' } },
345 null,
346 'test',
347 )
348 expect(warnings).toEqual([])
349 expect(Object.keys(schema.$defs as object).sort()).toEqual([
350 'Delta',
351 'EventTypes',
352 ])
353 expect(findDanglingRefs(schema)).toEqual([])
354 })
355​
356 it('records warnings for dangling refs instead of throwing', () => {
357 const { schema, warnings } = bundleSchema(
358 {
359 type: 'object',
360 properties: { x: { $ref: '#/components/schemas/Missing' } },
361 },
362 {},
363 null,
364 'ctx',
365 )
366 expect(warnings).toHaveLength(1)
367 expect(warnings[0]).toContain("'Missing' not found")
368 expect(findDanglingRefs(schema)).toEqual(['#/$defs/Missing'])
369 })
370})
371​
372describe('endpointIdFromPath / findDanglingRefs', () => {
373 it('derives endpoint ids by stripping the leading slash', () => {
374 expect(endpointIdFromPath('/v1/messages')).toBe('v1/messages')
375 expect(endpointIdFromPath('/fal-ai/veo')).toBe('fal-ai/veo')
376 })
377​
378 it('flags refs that escape the bundle', () => {
379 expect(
380 findDanglingRefs({
381 $ref: '#/components/schemas/Escaped',
382 }),
383 ).toEqual(['#/components/schemas/Escaped'])
384 })
385})