Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import ts from 'typescript'
3
4import type { ListedModelId as ClientListedModelId } from '../../packages/client/src/listed-model.ts'
5import {
6 TYPEGEN_VERSION,
7 emitTypesModule,
8 modelIdsKey,
9 moduleNames,
10 typesEtag,
11} from './typegen.ts'
12
13type InlinedListedModelId<TProvider extends string = string> = string & {
14 readonly __modelschemasListed: TProvider
15}
16const clientBrandMatchesInline: ClientListedModelId<'anthropic'> =
17 '' as InlinedListedModelId<'anthropic'>
18
19/** Typecheck `source` as a standalone module with the real compiler. */
20function diagnostics(
21 source: string,
22 overrides: Partial<ts.CompilerOptions> = {},
23): Array<string> {
24 const fileName = '/generated.ts'
25 const options: ts.CompilerOptions = {
26 strict: true,
27 noEmit: true,
28 skipLibCheck: true,
29 target: ts.ScriptTarget.ES2022,
30 module: ts.ModuleKind.ESNext,
31 ...overrides,
32 }
33 const host = ts.createCompilerHost(options)
34 const getSourceFile = host.getSourceFile.bind(host)
35 host.getSourceFile = (name, languageVersion, ...rest) =>
36 name === fileName
37 ? ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true)
38 : getSourceFile(name, languageVersion, ...rest)
39 const fileExists = host.fileExists.bind(host)
40 host.fileExists = (name) => name === fileName || fileExists(name)
41 const program = ts.createProgram([fileName], options, host)
42 return ts
43 .getPreEmitDiagnostics(program)
44 .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'))
45}
46
47/** Messages-shaped bundled schema exercising the emitter's full subset. */
48const fixture = {
49 type: 'object',
50 description: 'Create a message.',
51 required: ['model', 'messages', 'max_tokens'],
52 properties: {
53 model: { type: 'string', description: 'Model id, e.g. claude-sonnet-4-6.' },
54 max_tokens: { type: 'integer' },
55 temperature: { type: 'number', nullable: true },
56 stream: { type: 'boolean', default: false },
57 stop_sequences: { type: 'array', items: { type: 'string' } },
58 messages: { type: 'array', items: { $ref: '#/$defs/Message' } },
59 tool_choice: {
60 oneOf: [
61 { $ref: '#/$defs/ToolChoiceAuto' },
62 { $ref: '#/$defs/ToolChoiceTool' },
63 ],
64 },
65 metadata: {
66 type: 'object',
67 additionalProperties: { type: 'string' },
68 },
69 'odd-key': { const: 42 },
70 coords: {
71 type: 'array',
72 prefixItems: [{ type: 'number' }, { type: 'number' }],
73 items: false,
74 },
75 legacy: {
76 deprecated: true,
77 description: 'Ends with a tricky */ sequence.',
78 type: ['string', 'null'],
79 },
80 },
81 $defs: {
82 Message: {
83 type: 'object',
84 required: ['role', 'content'],
85 properties: {
86 role: { enum: ['user', 'assistant'] },
87 content: {
88 anyOf: [
89 { type: 'string' },
90 { type: 'array', items: { $ref: '#/$defs/ContentBlock' } },
91 ],
92 },
93 // Circular: a message can quote another message.
94 quoted: { $ref: '#/$defs/Message' },
95 },
96 },
97 ContentBlock: {
98 allOf: [
99 {
100 type: 'object',
101 required: ['type'],
102 properties: { type: { type: 'string' } },
103 },
104 { type: 'object', properties: { text: { type: 'string' } } },
105 ],
106 },
107 ToolChoiceAuto: {
108 type: 'object',
109 required: ['type'],
110 properties: { type: { const: 'auto' } },
111 additionalProperties: false,
112 },
113 ToolChoiceTool: {
114 type: 'object',
115 required: ['type', 'name'],
116 properties: { type: { const: 'tool' }, name: { type: 'string' } },
117 },
118 // Collides with the reserved alias name.
119 JsonSchema: { type: 'object', properties: { ok: { type: 'boolean' } } },
120 },
121} satisfies Record<string, unknown>
122
123function emitFixture(optionalStyle?: 'exact' | 'undefined') {
124 return emitTypesModule({
125 provider: 'anthropic',
126 endpointId: 'v1/messages',
127 kind: 'input',
128 contentHash: 'abc123def456',
129 schema: fixture,
130 optionalStyle,
131 sourceUrl:
132 'https://modelschemas.com/v1/schemas/anthropic/text/v1/messages?kind=input',
133 })
134}
135
136describe('emitTypesModule', () => {
137 it('compiles clean under strict, with and without exactOptionalPropertyTypes', () => {
138 const source = emitFixture()
139 expect(diagnostics(source)).toEqual([])
140 expect(diagnostics(source, { exactOptionalPropertyTypes: true })).toEqual(
141 [],
142 )
143 expect(
144 diagnostics(emitFixture('undefined'), {
145 exactOptionalPropertyTypes: true,
146 }),
147 ).toEqual([])
148 })
149
150 it('emits the documented module shape', () => {
151 const source = emitFixture()
152 expect(source).toContain(
153 `@generated by modelschemas typegen v${TYPEGEN_VERSION}`,
154 )
155 expect(source).toContain('// schema version: abc123def456')
156 expect(source).toContain(
157 'export const anthropicV1MessagesRequestSchema: JsonSchema =',
158 )
159 expect(source).toContain('export interface AnthropicV1MessagesRequest {')
160 // Required vs optional, with exact style by default.
161 expect(source).toContain('model: string')
162 expect(source).toContain('temperature?: number | null')
163 // Enum union + const literal + quoted member names.
164 expect(source).toContain('role: "user" | "assistant"')
165 expect(source).toContain('"odd-key"?: 42')
166 // Tuple, typed record, $defs as exported declarations.
167 expect(source).toContain('coords?: [number, number]')
168 expect(source).toContain('metadata?: Record<string, string>')
169 expect(source).toContain('export interface Message {')
170 expect(source).toContain('quoted?: Message')
171 // allOf intersection, closed object.
172 expect(source).toContain('export type ContentBlock =')
173 expect(source).toContain('@deprecated')
174 // Zero imports, zero `any`.
175 expect(source).not.toMatch(/^import /m)
176 expect(source).not.toMatch(/: any\b/)
177 })
178
179 it('renames $defs that collide with reserved names', () => {
180 const source = emitFixture()
181 expect(source).toContain('export interface JsonSchema2 {')
182 expect(source).toContain('export type JsonSchema = ')
183 })
184
185 it('optionalStyle=undefined widens optional members', () => {
186 const source = emitFixture('undefined')
187 expect(source).toContain('stream?: boolean | undefined')
188 })
189
190 it('is deterministic', () => {
191 expect(emitFixture()).toBe(emitFixture())
192 })
193
194 it('handles boolean and ref-rooted schemas', () => {
195 const refRooted = emitTypesModule({
196 provider: 'openai',
197 endpointId: 'chat/completions',
198 kind: 'output',
199 contentHash: 'deadbeef',
200 schema: {
201 $ref: '#/$defs/Completion',
202 $defs: {
203 Completion: {
204 type: 'object',
205 required: ['id'],
206 properties: { id: { type: 'string' } },
207 },
208 },
209 },
210 })
211 expect(refRooted).toContain(
212 'export type OpenaiChatCompletionsResponse = Completion',
213 )
214 expect(diagnostics(refRooted)).toEqual([])
215 })
216
217 it('overlays model as Known | ListedModelId when modelIds are passed', () => {
218 const source = emitFixture()
219 expect(source).toContain('model: string')
220 expect(source).not.toContain('ListedModelId')
221 void clientBrandMatchesInline
222
223 const overlaid = emitTypesModule({
224 provider: 'anthropic',
225 endpointId: 'v1/messages',
226 kind: 'input',
227 contentHash: 'abc123def456',
228 schema: fixture,
229 modelIds: ['claude-sonnet-4-5', 'claude-opus-4-1'],
230 })
231 expect(overlaid).toContain('export type ListedModelId')
232 expect(overlaid).toContain(
233 'model: "claude-opus-4-1" | "claude-sonnet-4-5" | ListedModelId<"anthropic">',
234 )
235 expect(overlaid).not.toMatch(/^import /m)
236 expect(diagnostics(overlaid)).toEqual([])
237 expect(overlaid).toContain('"model": {\n "type": "string"')
238 })
239
240 it('overlays ListedModelId only when the catalog is empty', () => {
241 const overlaid = emitTypesModule({
242 provider: 'anthropic',
243 endpointId: 'v1/messages',
244 kind: 'input',
245 contentHash: 'abc123def456',
246 schema: fixture,
247 modelIds: [],
248 })
249 expect(overlaid).toContain('model: ListedModelId<"anthropic">')
250 expect(overlaid).not.toContain('model: string')
251 expect(diagnostics(overlaid)).toEqual([])
252 })
253
254 it('does not overlay output schemas or schemas without a model field', () => {
255 const output = emitTypesModule({
256 provider: 'anthropic',
257 endpointId: 'v1/messages',
258 kind: 'output',
259 contentHash: 'abc',
260 schema: fixture,
261 modelIds: ['claude-sonnet-4-5'],
262 })
263 expect(output).not.toContain('ListedModelId')
264
265 const noModel = emitTypesModule({
266 provider: 'fal',
267 endpointId: 'fal-ai/flux/dev',
268 kind: 'input',
269 contentHash: 'abc',
270 schema: {
271 type: 'object',
272 properties: { prompt: { type: 'string' } },
273 },
274 modelIds: ['fal-ai/flux/dev'],
275 })
276 expect(noModel).not.toContain('ListedModelId')
277 })
278
279 it('keys the types ETag by the live model list, not the schema hash', () => {
280 const hash = 'f'.repeat(64)
281 expect(typesEtag(hash, 'exact', modelIdsKey(['b', 'a']))).toBe(
282 typesEtag(hash, 'exact', modelIdsKey(['a', 'b'])),
283 )
284 expect(typesEtag(hash, 'exact', modelIdsKey(['a']))).not.toBe(
285 typesEtag(hash, 'exact', modelIdsKey(['a', 'c'])),
286 )
287 expect(typesEtag(hash, 'exact')).not.toContain('-m')
288 })
289
290 it('accepts a structural ListedModelId from the client on an overlaid request', () => {
291 const module = emitTypesModule({
292 provider: 'anthropic',
293 endpointId: 'v1/messages',
294 kind: 'input',
295 contentHash: 'abc123def456',
296 schema: fixture,
297 modelIds: ['claude-sonnet-4-5'],
298 })
299 const listed = `
300type ClientListed<TProvider extends string = string> = string & {
301 readonly __modelschemasListed: TProvider
302}
303declare function asListed<TProvider extends string>(
304 provider: TProvider,
305 rawId: string,
306): ClientListed<TProvider>
307const body: AnthropicV1MessagesRequest = {
308 model: asListed("anthropic", "brand-new"),
309 max_tokens: 1,
310 messages: [{ role: "user", content: "hi" }],
311}
312`
313 expect(diagnostics(module + listed)).toEqual([])
314 expect(
315 diagnostics(
316 module +
317 `
318const bad: AnthropicV1MessagesRequest = {
319 model: "totally-new",
320 max_tokens: 1,
321 messages: [{ role: "user", content: "hi" }],
322}
323`,
324 ),
325 ).not.toEqual([])
326 })
327
328 it('derives stable export names', () => {
329 expect(moduleNames('anthropic', 'v1/messages', 'input')).toEqual({
330 rootType: 'AnthropicV1MessagesRequest',
331 schemaConst: 'anthropicV1MessagesRequestSchema',
332 })
333 expect(
334 moduleNames('elevenlabs', 'v1/text-to-speech/{voice_id}', 'output')
335 .rootType,
336 ).toBe('ElevenlabsV1TextToSpeechVoiceIdResponse')
337 })
338})
339
340/**
341 * `model` accepts a snapshot literal *or* a value that came from
342 * `listModels` (a branded string). An arbitrary string — literal or
343 * variable — is not assignable. TypeScript cannot see the live catalog
344 * members; the brand only records provenance.
345 */
346describe('listed-model brand (Known | ListedModelId)', () => {
347 const prelude = `
348type ListedModelId<TProvider extends string = string> = string & {
349 readonly __modelschemasListed: TProvider
350}
351type KnownModel = "claude-sonnet-4-5" | "claude-opus-4-1"
352type Model = KnownModel | ListedModelId<"anthropic">
353interface ChatRequest {
354 model: Model
355 max_tokens: number
356}
357declare function send(req: ChatRequest): void
358declare function listModels(): Array<ListedModelId<"anthropic">>
359`
360
361 function check(statement: string): Array<string> {
362 return diagnostics(`${prelude}\n${statement}`)
363 }
364
365 it('accepts a model that was in the build-time snapshot', () => {
366 expect(
367 check('send({ model: "claude-sonnet-4-5", max_tokens: 1024 })'),
368 ).toEqual([])
369 })
370
371 it('accepts a model id returned by listModels, even if it is not in the snapshot', () => {
372 expect(check('send({ model: listModels()[0], max_tokens: 1024 })')).toEqual(
373 [],
374 )
375 })
376
377 it('rejects a string literal that is not in the snapshot', () => {
378 expect(check('send({ model: "totally-new", max_tokens: 1024 })')).toEqual([
379 `Type '"totally-new"' is not assignable to type 'Model'.`,
380 ])
381 })
382
383 it('rejects an arbitrary string variable', () => {
384 expect(
385 check(
386 'const id: string = "claude-sonnet-4-5"; send({ model: id, max_tokens: 1024 })',
387 ),
388 ).toEqual([`Type 'string' is not assignable to type 'Model'.`])
389 })
390
391 it('rejects a ListedModelId from another provider', () => {
392 expect(
393 check(
394 'const id = "gpt-4o" as ListedModelId<"openai">; send({ model: id, max_tokens: 1024 })',
395 ),
396 ).not.toEqual([])
397 })
398
399 it('still rejects a wrong max_tokens when the model came from listModels', () => {
400 expect(
401 check('send({ model: listModels()[0], max_tokens: "nope" })'),
402 ).toEqual(["Type 'string' is not assignable to type 'number'."])
403 })
404})