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

provider-openapi.test.ts

428 lines12.4 KB

1import { describe, expect, it } from 'vitest'
2​
3import {
4 applyModelEnum,
5 endpointMatchesModel,
6 headerParams,
7 operationsFor,
8 pathParamsFromPath,
9 requestMedia,
10 hoistSchemaDefs,
11 responseMedia,
12 unresolvedRefs,
13} from './provider-openapi.ts'
14import { falProvider } from './providers/fal.ts'
15import { anthropicProvider } from './providers/anthropic.ts'
16import { getProvider } from './providers/index.ts'
17import {
18 MAX_QUEUE_SPEC_PATHS,
19 resolveConnect,
20 resolveSpecGrain,
21} from './providers/connect.ts'
22​
23describe('path + header helpers', () => {
24 it('extracts braced path params', () => {
25 expect(pathParamsFromPath('/v1/text-to-speech/{voice_id}')).toEqual([
26 {
27 name: 'voice_id',
28 in: 'path',
29 required: true,
30 schema: { type: 'string' },
31 },
32 ])
33 expect(pathParamsFromPath('/v1/messages')).toEqual([])
34 })
35​
36 it('emits a constant header as const and a client-supplied header as a rule', () => {
37 expect(
38 headerParams([
39 { name: 'anthropic-version', value: '2023-06-01' },
40 {
41 name: 'x-opencode-session',
42 description: 'A stable session id the client chooses.',
43 },
44 ]),
45 ).toEqual([
46 {
47 name: 'anthropic-version',
48 in: 'header',
49 required: true,
50 schema: { type: 'string', const: '2023-06-01' },
51 },
52 {
53 name: 'x-opencode-session',
54 in: 'header',
55 required: true,
56 description: 'A stable session id the client chooses.',
57 schema: { type: 'string' },
58 },
59 ])
60 })
61})
62​
63describe('applyModelEnum', () => {
64 it('pins properties.model and leaves other schemas alone', () => {
65 const schema = {
66 type: 'object',
67 properties: {
68 model: { type: 'string' },
69 max_tokens: { type: 'integer' },
70 },
71 }
72 expect(applyModelEnum(schema, ['claude-sonnet-4-5'])).toEqual({
73 type: 'object',
74 properties: {
75 model: { type: 'string', enum: ['claude-sonnet-4-5'] },
76 max_tokens: { type: 'integer' },
77 },
78 })
79 expect(applyModelEnum({ type: 'string' }, ['x'])).toEqual({
80 type: 'string',
81 })
82 })
83})
84​
85describe('generation media types', () => {
86 const schema = { type: 'object', properties: { id: { type: 'string' } } }
87​
88 it('defaults a recorded-before-content-types schema to JSON', () => {
89 expect(requestMedia(schema, null)).toEqual({
90 content: { 'application/json': { schema } },
91 })
92 expect(responseMedia(schema, null)).toEqual({
93 content: { 'application/json': { schema } },
94 })
95 expect(requestMedia(undefined, 'multipart/form-data')).toBeUndefined()
96 expect(responseMedia(undefined, null)).toBeUndefined()
97 })
98​
99 it('sends a file upload as multipart and a stream as event-stream', () => {
100 expect(requestMedia(schema, 'multipart/form-data')).toEqual({
101 content: { 'multipart/form-data': { schema } },
102 })
103 expect(responseMedia(schema, ['text/event-stream'])).toEqual({
104 content: { 'text/event-stream': { schema } },
105 })
106 expect(responseMedia(undefined, ['text/event-stream'])).toBeUndefined()
107 })
108​
109 it('keeps JSON and uses the stream schema for the event stream', () => {
110 const chunk = { type: 'object', properties: { delta: { type: 'string' } } }
111 expect(
112 responseMedia(schema, ['application/json', 'text/event-stream'], chunk),
113 ).toEqual({
114 content: {
115 'application/json': { schema },
116 'text/event-stream': { schema: chunk },
117 },
118 })
119 expect(
120 responseMedia(schema, ['application/json', 'text/event-stream']),
121 ).toEqual({
122 content: { 'application/json': { schema } },
123 })
124 expect(responseMedia(schema, ['application/json', 'text/plain'])).toEqual({
125 content: {
126 'application/json': { schema },
127 'text/plain': { schema: { type: 'string' } },
128 },
129 })
130 })
131​
132 it('emits GET with the path parameter and no request body', () => {
133 const ops = operationsFor(
134 'byteplus',
135 {
136 id: 'contents/generations/tasks/{id}',
137 path: '/contents/generations/tasks/{id}',
138 activity: 'video',
139 description: 'Retrieve a task',
140 method: 'GET',
141 input: {
142 type: 'object',
143 required: ['id'],
144 properties: {
145 id: {
146 type: 'string',
147 description: 'Task id from the create call.',
148 },
149 },
150 },
151 output: { type: 'object', properties: { status: { type: 'string' } } },
152 requestContentType: null,
153 responseContentTypes: null,
154 specRevision: null,
155 },
156 {
157 servers: [{ url: 'https://ark.example' }],
158 securitySchemes: {},
159 security: [],
160 },
161 [],
162 undefined,
163 )
164 expect(ops.map((op) => op.method)).toEqual(['get'])
165 expect(ops[0]?.operation.requestBody).toBeUndefined()
166 expect(ops[0]?.operation.parameters).toEqual([
167 {
168 name: 'id',
169 in: 'path',
170 required: true,
171 description: 'Task id from the create call.',
172 schema: { type: 'string' },
173 },
174 ])
175 })
176​
177 it('keeps JSON and SSE on one post, as the official OpenAI spec does', () => {
178 const chunk = { type: 'object', properties: { delta: { type: 'string' } } }
179 const ops = operationsFor(
180 'openai',
181 {
182 id: 'chat',
183 path: '/chat/completions',
184 activity: 'chat',
185 description: 'Create a completion',
186 method: 'POST',
187 input: schema,
188 output: schema,
189 streamSchema: chunk,
190 requestContentType: null,
191 responseContentTypes: ['application/json', 'text/event-stream'],
192 specRevision: null,
193 },
194 {
195 servers: [{ url: 'https://api.openai.com/v1' }],
196 securitySchemes: {},
197 security: [],
198 },
199 [],
200 undefined,
201 )
202 expect(ops.map((op) => [op.method, op.path])).toEqual([
203 ['post', '/chat/completions'],
204 ])
205 const responses = ops[0]?.operation.responses as {
206 '200': { content: Record<string, { schema: unknown }> }
207 }
208 expect(responses['200'].content).toEqual({
209 'application/json': { schema },
210 'text/event-stream': { schema: chunk },
211 })
212 })
213​
214 it('adds the model header with the ids bound to that route (Fish Audio)', () => {
215 const [op] = operationsFor(
216 'fish-audio',
217 {
218 id: 'v1/asr',
219 path: '/v1/asr',
220 activity: 'audio',
221 description: null,
222 method: 'POST',
223 input: schema,
224 requestContentType: 'multipart/form-data',
225 responseContentTypes: null,
226 specRevision: null,
227 },
228 {
229 servers: [{ url: 'https://api.fish.audio' }],
230 securitySchemes: {},
231 security: [],
232 modelHeader: 'model',
233 },
234 ['transcribe-1-pro', 'transcribe-1'],
235 undefined,
236 )
237 expect(op?.operation.parameters).toEqual([
238 {
239 name: 'model',
240 in: 'header',
241 required: false,
242 schema: { type: 'string', enum: ['transcribe-1-pro', 'transcribe-1'] },
243 },
244 ])
245 const [create] = operationsFor(
246 'fish-audio',
247 {
248 id: 'model',
249 path: '/model',
250 activity: 'audio',
251 description: null,
252 method: 'POST',
253 input: schema,
254 requestContentType: 'multipart/form-data',
255 responseContentTypes: null,
256 specRevision: null,
257 },
258 {
259 servers: [{ url: 'https://api.fish.audio' }],
260 securitySchemes: {},
261 security: [],
262 modelHeader: 'model',
263 },
264 [],
265 undefined,
266 )
267 expect(create?.operation.parameters).toBeUndefined()
268 })
269​
270 it('describes audio responses as binary and keeps a stream schema beside them', () => {
271 expect(
272 responseMedia(schema, [
273 'application/octet-stream',
274 'audio/mpeg',
275 'text/event-stream',
276 ]),
277 ).toEqual({
278 content: {
279 'application/octet-stream': {
280 schema: { type: 'string', format: 'binary' },
281 },
282 'audio/mpeg': { schema: { type: 'string', format: 'binary' } },
283 'text/event-stream': { schema },
284 },
285 })
286 })
287})
288​
289describe('endpointMatchesModel', () => {
290 it('matches exact aggregator paths, not prefixes', () => {
291 expect(
292 endpointMatchesModel(
293 'fal-ai/flux/dev',
294 '/fal-ai/flux/dev',
295 'fal-ai/flux/dev',
296 ),
297 ).toBe(true)
298 expect(
299 endpointMatchesModel(
300 'fal-ai/flux/dev/redux',
301 '/fal-ai/flux/dev/redux',
302 'fal-ai/flux/dev',
303 ),
304 ).toBe(false)
305 expect(
306 endpointMatchesModel('v1/messages', '/v1/messages', 'claude-sonnet-4-5'),
307 ).toBe(false)
308 })
309})
310​
311describe('connect profiles', () => {
312 it('declares FAL as model-grained and Anthropic as provider-grained', () => {
313 expect(resolveSpecGrain(falProvider)).toBe('model')
314 expect(resolveSpecGrain(anthropicProvider)).toBe('provider')
315 expect(MAX_QUEUE_SPEC_PATHS).toBe(1024)
316 })
317​
318 it('carries Anthropic version + x-api-key and FAL sibling GET', () => {
319 const anthropic = resolveConnect(anthropicProvider)
320 expect(anthropic?.servers[0]?.url).toBe('https://api.anthropic.com')
321 expect(anthropic?.requiredHeaders).toEqual([
322 { name: 'anthropic-version', value: '2023-06-01' },
323 ])
324 expect(
325 anthropic?.securitySchemes.apiKey &&
326 anthropic.securitySchemes.apiKey.type === 'apiKey'
327 ? anthropic.securitySchemes.apiKey.name
328 : undefined,
329 ).toBe('x-api-key')
330 const fal = resolveConnect(falProvider)
331 expect(fal?.siblingGet).toBe(true)
332 expect(
333 fal?.securitySchemes.apiKey &&
334 fal.securitySchemes.apiKey.type === 'apiKey'
335 ? fal.securitySchemes.apiKey.name
336 : undefined,
337 ).toBe('Authorization')
338 })
339​
340 it('does not guess a connect profile from modelsEndpoint', () => {
341 expect(resolveConnect(getProvider('voyage'))).toBeNull()
342 })
343})
344​
345describe('hoistSchemaDefs', () => {
346 const body = (schema: unknown) => ({
347 post: {
348 requestBody: { content: { 'application/json': { schema } } },
349 responses: { '200': { content: { 'application/json': { schema } } } },
350 },
351 })
352​
353 it('moves $defs into components, dedupes, and renames a clash by content', () => {
354 const a = {
355 type: 'object',
356 properties: {
357 x: { $ref: '#/$defs/Shared' },
358 y: { $ref: '#/$defs/Item' },
359 },
360 $defs: {
361 Shared: { type: 'string' },
362 Item: { type: 'object', properties: { s: { $ref: '#/$defs/Shared' } } },
363 },
364 }
365 const b = {
366 type: 'object',
367 properties: {
368 x: { $ref: '#/$defs/Shared' },
369 y: { $ref: '#/$defs/Item' },
370 },
371 $defs: { Shared: { type: 'string' }, Item: { type: 'integer' } },
372 discriminator: {
373 propertyName: 'kind',
374 mapping: { item: '#/components/schemas/Item' },
375 },
376 }
377 const paths: Record<string, Record<string, unknown>> = {
378 '/a': body(a),
379 '/b': body(b),
380 }
381 const schemas = hoistSchemaDefs(Object.values(paths), {})
382 const document = { paths, components: { schemas } }
383 expect(unresolvedRefs(document)).toEqual([])
384 expect(JSON.stringify(document)).not.toContain('$defs')
385 const names = Object.keys(schemas).sort()
386 expect(names).toHaveLength(3)
387 expect(names).toContain('Shared')
388 expect(names).toContain('Item')
389 expect(schemas.Item).toEqual({
390 type: 'object',
391 properties: { s: { $ref: '#/components/schemas/Shared' } },
392 })
393 const renamed = names.find((name) => name.startsWith('Item_'))
394 expect(renamed && schemas[renamed]).toEqual({ type: 'integer' })
395 const bBody = (
396 paths['/b']!.post as {
397 requestBody: {
398 content: Record<
399 string,
400 { schema: { discriminator: { mapping: Record<string, string> } } }
401 >
402 }
403 }
404 ).requestBody.content['application/json']?.schema
405 expect(bBody?.discriminator.mapping.item).toBe(
406 `#/components/schemas/${renamed ?? ''}`,
407 )
408 })
409​
410 it('turns a root self-reference into a component', () => {
411 const tree = {
412 type: 'object',
413 properties: { children: { type: 'array', items: { $ref: '#' } } },
414 }
415 const paths: Record<string, Record<string, unknown>> = { '/t': body(tree) }
416 const schemas = hoistSchemaDefs(Object.values(paths), { named: tree })
417 expect(unresolvedRefs({ paths, components: { schemas } })).toEqual([])
418 expect(schemas.named).toEqual({
419 type: 'object',
420 properties: {
421 children: {
422 type: 'array',
423 items: { $ref: '#/components/schemas/named' },
424 },
425 },
426 })
427 })
428})