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

provider-openapi.worker.test.ts

440 lines12.3 KB

1import { beforeAll, describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3​
4import { getDb } from '#/db/index.ts'
5import type { Db } from '#/db/index.ts'
6import { endpoints, models, providers, schemaVersions } from '#/db/schema.ts'
7import { assembleProviderOpenApi } from './provider-openapi.ts'
8​
9const NOW = 1_781_150_000
10const INPUT = {
11 type: 'object',
12 required: ['model'],
13 properties: { model: { type: 'string' }, max_tokens: { type: 'integer' } },
15const OUTPUT = { type: 'object', properties: { id: { type: 'string' } } }
16​
17let db: Db
18​
19beforeAll(async () => {
20 db = getDb(env)
21 await db
22 .insert(providers)
23 .values([
24 {
25 id: 'anthropic',
26 displayName: 'Anthropic',
27 specSourceUrl: 'https://example.com/a.json',
28 },
29 {
30 id: 'fal',
31 displayName: 'FAL',
32 specSourceUrl: 'https://example.com/f.json',
33 },
34 ])
35 .onConflictDoNothing()
36 await db
37 .insert(endpoints)
38 .values([
39 {
40 id: 'anthropic/v1/messages',
41 providerId: 'anthropic',
42 activity: 'chat',
43 method: 'POST',
44 path: '/v1/messages',
45 description: 'Create a message',
46 },
47 {
48 id: 'fal/fal-ai/flux/dev',
49 providerId: 'fal',
50 activity: 'image',
51 method: 'POST',
52 path: '/fal-ai/flux/dev',
53 },
54 {
55 id: 'fal/fal-ai/other',
56 providerId: 'fal',
57 activity: 'image',
58 method: 'POST',
59 path: '/fal-ai/other',
60 },
61 ])
62 .onConflictDoNothing()
63 await db
64 .insert(schemaVersions)
65 .values([
66 {
67 id: 'anthropic/v1/messages:input',
68 endpointId: 'anthropic/v1/messages',
69 kind: 'input',
70 contentHash: 'a'.repeat(64),
71 schema: JSON.stringify(INPUT),
72 createdAt: NOW,
73 },
74 {
75 id: 'anthropic/v1/messages:output',
76 endpointId: 'anthropic/v1/messages',
77 kind: 'output',
78 contentHash: 'b'.repeat(64),
79 schema: JSON.stringify(OUTPUT),
80 createdAt: NOW,
81 },
82 {
83 id: 'fal/fal-ai/flux/dev:input',
84 endpointId: 'fal/fal-ai/flux/dev',
85 kind: 'input',
86 contentHash: 'c'.repeat(64),
87 schema: JSON.stringify({
88 type: 'object',
89 properties: { prompt: { type: 'string' } },
90 }),
91 createdAt: NOW,
92 },
93 {
94 id: 'fal/fal-ai/flux/dev:output',
95 endpointId: 'fal/fal-ai/flux/dev',
96 kind: 'output',
97 contentHash: 'd'.repeat(64),
98 schema: JSON.stringify(OUTPUT),
99 createdAt: NOW,
100 },
101 {
102 id: 'fal/fal-ai/other:input',
103 endpointId: 'fal/fal-ai/other',
104 kind: 'input',
105 contentHash: 'e'.repeat(64),
106 schema: JSON.stringify({ type: 'object' }),
107 createdAt: NOW,
108 },
109 ])
110 .onConflictDoNothing()
111 await db
112 .insert(models)
113 .values([
114 {
115 id: 'fal-fal-ai-flux-dev',
116 providerId: 'fal',
117 rawId: 'fal-ai/flux/dev',
118 activity: 'image',
119 firstSeenAt: NOW,
120 lastSeenAt: NOW,
121 },
122 {
123 id: 'anthropic-claude-sonnet-4-5',
124 providerId: 'anthropic',
125 rawId: 'claude-sonnet-4-5',
126 activity: 'chat',
127 firstSeenAt: NOW,
128 lastSeenAt: NOW,
129 },
130 ])
131 .onConflictDoNothing()
132})
133​
134describe('assembleProviderOpenApi', () => {
135 it('assembles a connectable Anthropic document', async () => {
136 const result = await assembleProviderOpenApi(db, 'anthropic')
137 expect(result.ok).toBe(true)
138 if (!result.ok) return
139 expect(result.document.openapi).toBe('3.1.0')
140 const paths = result.document.paths as Record<
141 string,
142 { post?: { parameters?: Array<{ name: string }>; requestBody?: unknown } }
143 >
144 expect(paths['/v1/messages']?.post?.requestBody).toBeDefined()
145 const headers = paths['/v1/messages']?.post?.parameters ?? []
146 expect(headers.some((p) => p.name === 'anthropic-version')).toBe(true)
147 expect((result.document.servers as Array<{ url: string }>)[0]?.url).toBe(
148 'https://api.anthropic.com',
149 )
150 const body = paths['/v1/messages']?.post?.requestBody as
151 | {
152 content: {
153 'application/json': {
154 schema: { properties?: { model?: { enum?: Array<string> } } }
155 }
156 }
157 }
158 | undefined
159 expect(
160 body?.content['application/json'].schema.properties?.model?.enum,
161 ).toEqual(['claude-sonnet-4-5'])
162 })
163​
164 it('pins the model enum when ?model= is passed', async () => {
165 const result = await assembleProviderOpenApi(db, 'anthropic', {
166 model: 'claude-sonnet-4-5',
167 })
168 expect(result.ok).toBe(true)
169 if (!result.ok) return
170 const paths = result.document.paths as Record<
171 string,
172 {
173 post?: {
174 requestBody?: {
175 content: {
176 'application/json': {
177 schema: { properties?: { model?: { enum?: Array<string> } } }
178 }
179 }
180 }
181 }
182 }
183 >
184 expect(
185 paths['/v1/messages']?.post?.requestBody?.content['application/json']
186 .schema.properties?.model?.enum,
187 ).toEqual(['claude-sonnet-4-5'])
188 })
189​
190 it('refuses a combined FAL spec and serves one model with sibling GET', async () => {
191 const bare = await assembleProviderOpenApi(db, 'fal')
192 expect(bare).toMatchObject({
193 ok: false,
194 status: 400,
195 code: 'spec_requires_selector',
196 })
197​
198 const pinned = await assembleProviderOpenApi(db, 'fal', {
199 model: 'fal-ai/flux/dev',
200 })
201 expect(pinned.ok).toBe(true)
202 if (!pinned.ok) return
203 const paths = pinned.document.paths as Record<
204 string,
205 {
206 post?: {
207 responses?: { '200'?: { content?: unknown } }
208 }
209 get?: {
210 parameters?: Array<{ name: string }>
211 responses?: {
212 '200'?: {
213 content?: {
214 'application/json': {
215 schema: { properties?: { id?: unknown } }
216 }
217 }
218 }
219 }
220 }
221 }
222 >
223 expect(paths['/fal-ai/flux/dev']?.post).toBeDefined()
224 expect(
225 paths['/fal-ai/flux/dev']?.post?.responses?.['200']?.content,
226 ).toBeUndefined()
227 const sibling = paths['/fal-ai/flux/dev/requests/{request_id}']?.get
228 expect(sibling).toBeDefined()
229 expect(sibling?.parameters?.some((p) => p.name === 'request_id')).toBe(true)
230 expect(
231 sibling?.responses?.['200']?.content?.['application/json'].schema
232 .properties?.id,
233 ).toBeDefined()
234 expect(paths['/fal-ai/other']).toBeUndefined()
235​
236 expect(
237 await assembleProviderOpenApi(db, 'fal', { activity: 'image' }),
238 ).toMatchObject({
239 ok: false,
240 status: 400,
241 code: 'spec_requires_selector',
242 })
243 })
244​
245 it('refuses empty paths instead of returning 200', async () => {
246 expect(
247 await assembleProviderOpenApi(db, 'anthropic', { activity: 'video' }),
248 ).toMatchObject({
249 ok: false,
250 status: 400,
251 code: 'spec_requires_selector',
252 })
253​
254 await db
255 .insert(providers)
256 .values({
257 id: 'grok',
258 displayName: 'xAI Grok',
259 specSourceUrl: 'https://example.com/g.json',
260 })
261 .onConflictDoNothing()
262 expect(await assembleProviderOpenApi(db, 'grok')).toMatchObject({
263 ok: false,
264 status: 404,
265 code: 'no_endpoints',
266 })
267 })
268​
269 it('does not assemble adapters that have no declared connect profile', async () => {
270 await db
271 .insert(providers)
272 .values({
273 id: 'voyage',
274 displayName: 'Voyage',
275 specSourceUrl: 'https://example.com/v.json',
276 })
277 .onConflictDoNothing()
278 await db
279 .insert(endpoints)
280 .values({
281 id: 'voyage/embeddings',
282 providerId: 'voyage',
283 activity: 'embeddings',
284 method: 'POST',
285 path: '/embeddings',
286 })
287 .onConflictDoNothing()
288 expect(await assembleProviderOpenApi(db, 'voyage')).toMatchObject({
289 ok: false,
290 status: 500,
291 code: 'missing_connect',
292 })
293 })
294​
295 it('splits BytePlus Ark and Seed Speech onto their own connect profiles', async () => {
296 await db
297 .insert(providers)
298 .values({
299 id: 'byteplus',
300 displayName: 'BytePlus',
301 specSourceUrl: 'https://example.com/b.json',
302 })
303 .onConflictDoNothing()
304 await db
305 .insert(endpoints)
306 .values([
307 {
308 id: 'byteplus/chat/completions',
309 providerId: 'byteplus',
310 activity: 'chat',
311 method: 'POST',
312 path: '/chat/completions',
313 },
314 {
315 id: 'byteplus/tts/create',
316 providerId: 'byteplus',
317 activity: 'audio',
318 method: 'POST',
319 path: '/tts/create',
320 },
321 ])
322 .onConflictDoNothing()
323 const combined = await assembleProviderOpenApi(db, 'byteplus')
324 expect(combined.ok).toBe(true)
325 if (!combined.ok) return
326 const combinedPaths = combined.document.paths as Record<string, unknown>
327 expect(combinedPaths['/chat/completions']).toBeDefined()
328 expect(combinedPaths['/tts/create']).toBeUndefined()
329 expect((combined.document.servers as Array<{ url: string }>)[0]?.url).toBe(
330 'https://ark.ap-southeast.bytepluses.com/api/v3',
331 )
332​
333 const audio = await assembleProviderOpenApi(db, 'byteplus', {
334 activity: 'audio',
335 })
336 expect(audio.ok).toBe(true)
337 if (!audio.ok) return
338 const audioPaths = audio.document.paths as Record<string, unknown>
339 expect(audioPaths['/tts/create']).toBeDefined()
340 expect(audioPaths['/chat/completions']).toBeUndefined()
341 expect((audio.document.servers as Array<{ url: string }>)[0]?.url).toBe(
342 'https://voice.ap-southeast-1.bytepluses.com/api/v3',
343 )
344 })
345​
346 it('refuses assembly over the endpoint cap', async () => {
347 await db
348 .insert(providers)
349 .values({
350 id: 'cap-prov',
351 displayName: 'Cap',
352 specSourceUrl: 'https://example.com/c.json',
353 })
354 .onConflictDoNothing()
355 const rows = Array.from({ length: 41 }, (_, i) => ({
356 id: `cap-prov/e${String(i)}`,
357 providerId: 'cap-prov',
358 activity: 'chat' as const,
359 method: 'POST',
360 path: `/e${String(i)}`,
361 }))
362 for (let i = 0; i < rows.length; i += 10) {
363 await db
364 .insert(endpoints)
365 .values(rows.slice(i, i + 10))
366 .onConflictDoNothing()
367 }
368 const overCap = await assembleProviderOpenApi(db, 'cap-prov')
369 expect(overCap).toMatchObject({
370 ok: false,
371 status: 400,
372 code: 'spec_requires_selector',
373 })
374 if (overCap.ok) return
375 expect(overCap.message).toContain('does not drop endpoints')
376 expect(overCap.message).toContain('?activity=')
377 })
378​
379 it('refuses OpenAPI assembly for AsyncAPI-flagged FAL models', async () => {
380 await db
381 .insert(models)
382 .values({
383 id: 'fal-minimax-h3-max-director',
384 providerId: 'fal',
385 rawId: 'minimax/h3-max/director',
386 activity: 'video',
387 capabilities: { asyncapi: true },
388 providerMetadata: { category: 'text-to-video' },
389 firstSeenAt: NOW,
390 lastSeenAt: NOW,
391 })
392 .onConflictDoNothing()
393 await db
394 .insert(endpoints)
395 .values({
396 id: 'fal/minimax/h3-max/director',
397 providerId: 'fal',
398 activity: 'video',
399 method: 'POST',
400 path: '/minimax/h3-max/director',
401 })
402 .onConflictDoNothing()
403 await db
404 .insert(schemaVersions)
405 .values({
406 id: 'fal/minimax/h3-max/director:input',
407 endpointId: 'fal/minimax/h3-max/director',
408 kind: 'input',
409 contentHash: 'aa'.repeat(32),
410 schema: JSON.stringify({
411 oneOf: [
412 { type: 'object', properties: { type: { const: 'configure' } } },
413 ],
414 }),
415 createdAt: NOW,
416 })
417 .onConflictDoNothing()
418​
419 const result = await assembleProviderOpenApi(db, 'fal', {
420 model: 'minimax/h3-max/director',
421 })
422 expect(result).toMatchObject({
423 ok: false,
424 status: 404,
425 code: 'unknown_model',
426 })
427 if (!result.ok) expect(result.message).toContain('AsyncAPI')
428 })
429​
430 it('404s unknown provider and unknown model', async () => {
431 expect(await assembleProviderOpenApi(db, 'nope')).toMatchObject({
432 ok: false,
433 status: 404,
434 code: 'unknown_provider',
435 })
436 expect(
437 await assembleProviderOpenApi(db, 'fal', { model: 'missing' }),
438 ).toMatchObject({ ok: false, status: 404, code: 'unknown_model' })
439 })
440})