@mastra/schema-compat 0.0.0-fix-fetching-workflow-snapshots-20250625000954 → 0.0.0-fix-zod-to-json-schema-ref-strategy-20250910193441

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +139 -1
  2. package/LICENSE.md +11 -42
  3. package/README.md +0 -4
  4. package/dist/chunk-7YUR5KZ5.cjs +34 -0
  5. package/dist/chunk-7YUR5KZ5.cjs.map +1 -0
  6. package/dist/chunk-GWTUXMDD.js +28 -0
  7. package/dist/chunk-GWTUXMDD.js.map +1 -0
  8. package/dist/index.cjs +847 -85
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +11 -31
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +846 -86
  13. package/dist/index.js.map +1 -0
  14. package/dist/provider-compats/anthropic.d.ts +13 -0
  15. package/dist/provider-compats/anthropic.d.ts.map +1 -0
  16. package/dist/provider-compats/deepseek.d.ts +13 -0
  17. package/dist/provider-compats/deepseek.d.ts.map +1 -0
  18. package/dist/provider-compats/google.d.ts +13 -0
  19. package/dist/provider-compats/google.d.ts.map +1 -0
  20. package/dist/provider-compats/meta.d.ts +13 -0
  21. package/dist/provider-compats/meta.d.ts.map +1 -0
  22. package/dist/provider-compats/openai-reasoning.d.ts +14 -0
  23. package/dist/provider-compats/openai-reasoning.d.ts.map +1 -0
  24. package/dist/provider-compats/openai.d.ts +13 -0
  25. package/dist/provider-compats/openai.d.ts.map +1 -0
  26. package/dist/schema-compatibility-v3.d.ts +319 -0
  27. package/dist/schema-compatibility-v3.d.ts.map +1 -0
  28. package/dist/schema-compatibility-v4.d.ts +310 -0
  29. package/dist/schema-compatibility-v4.d.ts.map +1 -0
  30. package/dist/schema-compatibility.d.ts +228 -0
  31. package/dist/schema-compatibility.d.ts.map +1 -0
  32. package/dist/types.d.ts +6 -0
  33. package/dist/types.d.ts.map +1 -0
  34. package/dist/utils-test-suite.d.ts +2 -0
  35. package/dist/utils-test-suite.d.ts.map +1 -0
  36. package/dist/utils.d.ts +96 -0
  37. package/dist/utils.d.ts.map +1 -0
  38. package/dist/zod-to-json.cjs +12 -0
  39. package/dist/zod-to-json.cjs.map +1 -0
  40. package/dist/zod-to-json.d.ts +6 -0
  41. package/dist/zod-to-json.d.ts.map +1 -0
  42. package/dist/zod-to-json.js +3 -0
  43. package/dist/zod-to-json.js.map +1 -0
  44. package/dist/zodTypes.d.ts +21 -0
  45. package/dist/zodTypes.d.ts.map +1 -0
  46. package/package.json +37 -13
  47. package/.turbo/turbo-build.log +0 -23
  48. package/dist/_tsup-dts-rollup.d.cts +0 -504
  49. package/dist/_tsup-dts-rollup.d.ts +0 -504
  50. package/dist/index.d.cts +0 -31
  51. package/eslint.config.js +0 -6
  52. package/src/index.ts +0 -39
  53. package/src/provider-compats/anthropic.ts +0 -44
  54. package/src/provider-compats/deepseek.ts +0 -35
  55. package/src/provider-compats/google.ts +0 -55
  56. package/src/provider-compats/meta.ts +0 -36
  57. package/src/provider-compats/openai-reasoning.ts +0 -87
  58. package/src/provider-compats/openai.ts +0 -56
  59. package/src/provider-compats.test.ts +0 -312
  60. package/src/schema-compatibility.test.ts +0 -471
  61. package/src/schema-compatibility.ts +0 -587
  62. package/src/utils.test.ts +0 -434
  63. package/src/utils.ts +0 -205
  64. package/tsconfig.json +0 -5
  65. package/vitest.config.ts +0 -7
@@ -1,587 +0,0 @@
1
- import type { Schema, LanguageModelV1 } from 'ai';
2
- import type { JSONSchema7 } from 'json-schema';
3
- import { z, ZodOptional, ZodObject, ZodArray, ZodUnion, ZodString, ZodNumber, ZodDate, ZodDefault } from 'zod';
4
- import type { ZodTypeAny } from 'zod';
5
- import type { Targets } from 'zod-to-json-schema';
6
- import { convertZodSchemaToAISDKSchema } from './utils';
7
-
8
- /**
9
- * All supported string validation check types that can be processed or converted to descriptions.
10
- * @constant
11
- */
12
- export const ALL_STRING_CHECKS = ['regex', 'emoji', 'email', 'url', 'uuid', 'cuid', 'min', 'max'] as const;
13
-
14
- /**
15
- * All supported number validation check types that can be processed or converted to descriptions.
16
- * @constant
17
- */
18
- export const ALL_NUMBER_CHECKS = [
19
- 'min', // gte internally
20
- 'max', // lte internally
21
- 'multipleOf',
22
- ] as const;
23
-
24
- /**
25
- * All supported array validation check types that can be processed or converted to descriptions.
26
- * @constant
27
- */
28
- export const ALL_ARRAY_CHECKS = ['min', 'max', 'length'] as const;
29
-
30
- export const isOptional = (v: ZodTypeAny): v is ZodOptional<any> => v instanceof ZodOptional;
31
- export const isObj = (v: ZodTypeAny): v is ZodObject<any, any, any> => v instanceof ZodObject;
32
- export const isArr = (v: ZodTypeAny): v is ZodArray<any, any> => v instanceof ZodArray;
33
- export const isUnion = (v: ZodTypeAny): v is ZodUnion<[ZodTypeAny, ...ZodTypeAny[]]> => v instanceof ZodUnion;
34
- export const isString = (v: ZodTypeAny): v is ZodString => v instanceof ZodString;
35
- export const isNumber = (v: ZodTypeAny): v is ZodNumber => v instanceof ZodNumber;
36
- export const isDate = (v: ZodTypeAny): v is ZodDate => v instanceof ZodDate;
37
- export const isDefault = (v: ZodTypeAny): v is ZodDefault<any> => v instanceof ZodDefault;
38
-
39
- /**
40
- * Zod types that are not supported by most AI model providers and should be avoided.
41
- * @constant
42
- */
43
- export const UNSUPPORTED_ZOD_TYPES = ['ZodIntersection', 'ZodNever', 'ZodNull', 'ZodTuple', 'ZodUndefined'] as const;
44
-
45
- /**
46
- * Zod types that are generally supported by AI model providers.
47
- * @constant
48
- */
49
- export const SUPPORTED_ZOD_TYPES = [
50
- 'ZodObject',
51
- 'ZodArray',
52
- 'ZodUnion',
53
- 'ZodString',
54
- 'ZodNumber',
55
- 'ZodDate',
56
- 'ZodAny',
57
- 'ZodDefault',
58
- ] as const;
59
-
60
- /**
61
- * All Zod types (both supported and unsupported).
62
- * @constant
63
- */
64
- export const ALL_ZOD_TYPES = [...SUPPORTED_ZOD_TYPES, ...UNSUPPORTED_ZOD_TYPES] as const;
65
-
66
- /**
67
- * Type representing string validation checks.
68
- */
69
- export type StringCheckType = (typeof ALL_STRING_CHECKS)[number];
70
-
71
- /**
72
- * Type representing number validation checks.
73
- */
74
- export type NumberCheckType = (typeof ALL_NUMBER_CHECKS)[number];
75
-
76
- /**
77
- * Type representing array validation checks.
78
- */
79
- export type ArrayCheckType = (typeof ALL_ARRAY_CHECKS)[number];
80
-
81
- /**
82
- * Type representing unsupported Zod schema types.
83
- */
84
- export type UnsupportedZodType = (typeof UNSUPPORTED_ZOD_TYPES)[number];
85
-
86
- /**
87
- * Type representing supported Zod schema types.
88
- */
89
- export type SupportedZodType = (typeof SUPPORTED_ZOD_TYPES)[number];
90
-
91
- /**
92
- * Type representing all Zod schema types (supported and unsupported).
93
- */
94
- export type AllZodType = (typeof ALL_ZOD_TYPES)[number];
95
-
96
- /**
97
- * Utility type to extract the shape of a Zod object schema.
98
- */
99
- export type ZodShape<T extends z.AnyZodObject> = T['shape'];
100
-
101
- /**
102
- * Utility type to extract the keys from a Zod object shape.
103
- */
104
- export type ShapeKey<T extends z.AnyZodObject> = keyof ZodShape<T>;
105
-
106
- /**
107
- * Utility type to extract the value types from a Zod object shape.
108
- */
109
- export type ShapeValue<T extends z.AnyZodObject> = ZodShape<T>[ShapeKey<T>];
110
-
111
- // Add constraint types at the top
112
-
113
- type StringConstraints = {
114
- minLength?: number;
115
- maxLength?: number;
116
- email?: boolean;
117
- url?: boolean;
118
- uuid?: boolean;
119
- cuid?: boolean;
120
- emoji?: boolean;
121
- regex?: { pattern: string; flags?: string };
122
- };
123
-
124
- type NumberConstraints = {
125
- gt?: number;
126
- gte?: number;
127
- lt?: number;
128
- lte?: number;
129
- multipleOf?: number;
130
- };
131
-
132
- type ArrayConstraints = {
133
- minLength?: number;
134
- maxLength?: number;
135
- exactLength?: number;
136
- };
137
-
138
- type DateConstraints = {
139
- minDate?: string;
140
- maxDate?: string;
141
- dateFormat?: string;
142
- };
143
-
144
- /**
145
- * Abstract base class for creating schema compatibility layers for different AI model providers.
146
- *
147
- * This class provides a framework for transforming Zod schemas to work with specific AI model
148
- * provider requirements and limitations. Each provider may have different support levels for
149
- * JSON Schema features, validation constraints, and data types.
150
- *
151
- * @abstract
152
- *
153
- * @example
154
- * ```typescript
155
- * import { SchemaCompatLayer } from '@mastra/schema-compat';
156
- * import type { LanguageModelV1 } from 'ai';
157
- *
158
- * class CustomProviderCompat extends SchemaCompatLayer {
159
- * constructor(model: LanguageModelV1) {
160
- * super(model);
161
- * }
162
- *
163
- * shouldApply(): boolean {
164
- * return this.getModel().provider === 'custom-provider';
165
- * }
166
- *
167
- * getSchemaTarget() {
168
- * return 'jsonSchema7';
169
- * }
170
- *
171
- * processZodType<T extends z.AnyZodObject>(value: z.ZodTypeAny): ShapeValue<T> {
172
- * // Custom processing logic for this provider
173
- * switch (value._def.typeName) {
174
- * case 'ZodString':
175
- * return this.defaultZodStringHandler(value, ['email', 'url']);
176
- * default:
177
- * return this.defaultUnsupportedZodTypeHandler(value);
178
- * }
179
- * }
180
- * }
181
- * ```
182
- */
183
- export abstract class SchemaCompatLayer {
184
- private model: LanguageModelV1;
185
-
186
- /**
187
- * Creates a new schema compatibility instance.
188
- *
189
- * @param model - The language model this compatibility layer applies to
190
- */
191
- constructor(model: LanguageModelV1) {
192
- this.model = model;
193
- }
194
-
195
- /**
196
- * Gets the language model associated with this compatibility layer.
197
- *
198
- * @returns The language model instance
199
- */
200
- getModel(): LanguageModelV1 {
201
- return this.model;
202
- }
203
-
204
- /**
205
- * Determines whether this compatibility layer should be applied for the current model.
206
- *
207
- * @returns True if this compatibility layer should be used, false otherwise
208
- * @abstract
209
- */
210
- abstract shouldApply(): boolean;
211
-
212
- /**
213
- * Returns the JSON Schema target format for this provider.
214
- *
215
- * @returns The schema target format, or undefined to use the default 'jsonSchema7'
216
- * @abstract
217
- */
218
- abstract getSchemaTarget(): Targets | undefined;
219
-
220
- /**
221
- * Processes a specific Zod type according to the provider's requirements.
222
- *
223
- * @param value - The Zod type to process
224
- * @returns The processed Zod type
225
- * @abstract
226
- */
227
- abstract processZodType(value: ZodTypeAny): ZodTypeAny;
228
-
229
- /**
230
- * Default handler for Zod object types. Recursively processes all properties in the object.
231
- *
232
- * @param value - The Zod object to process
233
- * @returns The processed Zod object
234
- */
235
- public defaultZodObjectHandler(
236
- value: ZodObject<any, any, any>,
237
- options: { passthrough?: boolean } = { passthrough: true },
238
- ): ZodObject<any, any, any> {
239
- const processedShape = Object.entries(value.shape).reduce<Record<string, ZodTypeAny>>((acc, [key, propValue]) => {
240
- acc[key] = this.processZodType(propValue as ZodTypeAny);
241
- return acc;
242
- }, {});
243
-
244
- let result: ZodObject<any, any, any> = z.object(processedShape);
245
-
246
- if (value._def.unknownKeys === 'strict') {
247
- result = result.strict();
248
- }
249
- if (value._def.catchall && !(value._def.catchall instanceof z.ZodNever)) {
250
- result = result.catchall(value._def.catchall);
251
- }
252
-
253
- if (value.description) {
254
- result = result.describe(value.description);
255
- }
256
-
257
- if (options.passthrough && value._def.unknownKeys === 'passthrough') {
258
- result = result.passthrough();
259
- }
260
-
261
- return result;
262
- }
263
-
264
- /**
265
- * Merges validation constraints into a parameter description.
266
- *
267
- * This helper method converts validation constraints that may not be supported
268
- * by a provider into human-readable descriptions.
269
- *
270
- * @param description - The existing parameter description
271
- * @param constraints - The validation constraints to merge
272
- * @returns The updated description with constraints, or undefined if no constraints
273
- */
274
- public mergeParameterDescription(
275
- description: string | undefined,
276
- constraints:
277
- | NumberConstraints
278
- | StringConstraints
279
- | ArrayConstraints
280
- | DateConstraints
281
- | { defaultValue?: unknown },
282
- ): string | undefined {
283
- if (Object.keys(constraints).length > 0) {
284
- return (description ? description + '\n' : '') + JSON.stringify(constraints);
285
- } else {
286
- return description;
287
- }
288
- }
289
-
290
- /**
291
- * Default handler for unsupported Zod types. Throws an error for specified unsupported types.
292
- *
293
- * @param value - The Zod type to check
294
- * @param throwOnTypes - Array of type names to throw errors for
295
- * @returns The original value if not in the throw list
296
- * @throws Error if the type is in the unsupported list
297
- */
298
- public defaultUnsupportedZodTypeHandler<T extends z.AnyZodObject>(
299
- value: z.ZodTypeAny,
300
- throwOnTypes: readonly UnsupportedZodType[] = UNSUPPORTED_ZOD_TYPES,
301
- ): ShapeValue<T> {
302
- if (throwOnTypes.includes(value._def.typeName as UnsupportedZodType)) {
303
- throw new Error(`${this.model.modelId} does not support zod type: ${value._def.typeName}`);
304
- }
305
- return value as ShapeValue<T>;
306
- }
307
-
308
- /**
309
- * Default handler for Zod array types. Processes array constraints according to provider support.
310
- *
311
- * @param value - The Zod array to process
312
- * @param handleChecks - Array constraints to convert to descriptions vs keep as validation
313
- * @returns The processed Zod array
314
- */
315
- public defaultZodArrayHandler(
316
- value: ZodArray<any, any>,
317
- handleChecks: readonly ArrayCheckType[] = ALL_ARRAY_CHECKS,
318
- ): ZodArray<any, any> {
319
- const zodArrayDef = value._def;
320
- const processedType = this.processZodType(zodArrayDef.type);
321
-
322
- let result = z.array(processedType);
323
-
324
- const constraints: ArrayConstraints = {};
325
-
326
- if (zodArrayDef.minLength?.value !== undefined) {
327
- if (handleChecks.includes('min')) {
328
- constraints.minLength = zodArrayDef.minLength.value;
329
- } else {
330
- result = result.min(zodArrayDef.minLength.value);
331
- }
332
- }
333
-
334
- if (zodArrayDef.maxLength?.value !== undefined) {
335
- if (handleChecks.includes('max')) {
336
- constraints.maxLength = zodArrayDef.maxLength.value;
337
- } else {
338
- result = result.max(zodArrayDef.maxLength.value);
339
- }
340
- }
341
-
342
- if (zodArrayDef.exactLength?.value !== undefined) {
343
- if (handleChecks.includes('length')) {
344
- constraints.exactLength = zodArrayDef.exactLength.value;
345
- } else {
346
- result = result.length(zodArrayDef.exactLength.value);
347
- }
348
- }
349
-
350
- const description = this.mergeParameterDescription(value.description, constraints);
351
- if (description) {
352
- result = result.describe(description);
353
- }
354
- return result;
355
- }
356
-
357
- /**
358
- * Default handler for Zod union types. Processes all union options.
359
- *
360
- * @param value - The Zod union to process
361
- * @returns The processed Zod union
362
- * @throws Error if union has fewer than 2 options
363
- */
364
- public defaultZodUnionHandler(value: ZodUnion<[ZodTypeAny, ...ZodTypeAny[]]>): ZodTypeAny {
365
- const processedOptions = value._def.options.map((option: ZodTypeAny) => this.processZodType(option));
366
- if (processedOptions.length < 2) throw new Error('Union must have at least 2 options');
367
- let result = z.union(processedOptions as [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]);
368
- if (value.description) {
369
- result = result.describe(value.description);
370
- }
371
- return result;
372
- }
373
-
374
- /**
375
- * Default handler for Zod string types. Processes string validation constraints.
376
- *
377
- * @param value - The Zod string to process
378
- * @param handleChecks - String constraints to convert to descriptions vs keep as validation
379
- * @returns The processed Zod string
380
- */
381
- public defaultZodStringHandler(
382
- value: ZodString,
383
- handleChecks: readonly StringCheckType[] = ALL_STRING_CHECKS,
384
- ): ZodString {
385
- const constraints: StringConstraints = {};
386
- const checks = value._def.checks || [];
387
- type ZodStringCheck = (typeof checks)[number];
388
- const newChecks: ZodStringCheck[] = [];
389
- for (const check of checks) {
390
- if ('kind' in check) {
391
- if (handleChecks.includes(check.kind as StringCheckType)) {
392
- switch (check.kind) {
393
- case 'regex': {
394
- constraints.regex = {
395
- pattern: check.regex.source,
396
- flags: check.regex.flags,
397
- };
398
- break;
399
- }
400
- case 'emoji': {
401
- constraints.emoji = true;
402
- break;
403
- }
404
- case 'email': {
405
- constraints.email = true;
406
- break;
407
- }
408
- case 'url': {
409
- constraints.url = true;
410
- break;
411
- }
412
- case 'uuid': {
413
- constraints.uuid = true;
414
- break;
415
- }
416
- case 'cuid': {
417
- constraints.cuid = true;
418
- break;
419
- }
420
- case 'min': {
421
- constraints.minLength = check.value;
422
- break;
423
- }
424
- case 'max': {
425
- constraints.maxLength = check.value;
426
- break;
427
- }
428
- }
429
- } else {
430
- newChecks.push(check);
431
- }
432
- }
433
- }
434
- let result = z.string();
435
- for (const check of newChecks) {
436
- result = result._addCheck(check);
437
- }
438
- const description = this.mergeParameterDescription(value.description, constraints);
439
- if (description) {
440
- result = result.describe(description);
441
- }
442
- return result;
443
- }
444
-
445
- /**
446
- * Default handler for Zod number types. Processes number validation constraints.
447
- *
448
- * @param value - The Zod number to process
449
- * @param handleChecks - Number constraints to convert to descriptions vs keep as validation
450
- * @returns The processed Zod number
451
- */
452
- public defaultZodNumberHandler(
453
- value: ZodNumber,
454
- handleChecks: readonly NumberCheckType[] = ALL_NUMBER_CHECKS,
455
- ): ZodNumber {
456
- const constraints: NumberConstraints = {};
457
- const checks = value._def.checks || [];
458
- type ZodNumberCheck = (typeof checks)[number];
459
- const newChecks: ZodNumberCheck[] = [];
460
- for (const check of checks) {
461
- if ('kind' in check) {
462
- if (handleChecks.includes(check.kind as NumberCheckType)) {
463
- switch (check.kind) {
464
- case 'min':
465
- if (check.inclusive) {
466
- constraints.gte = check.value;
467
- } else {
468
- constraints.gt = check.value;
469
- }
470
- break;
471
- case 'max':
472
- if (check.inclusive) {
473
- constraints.lte = check.value;
474
- } else {
475
- constraints.lt = check.value;
476
- }
477
- break;
478
- case 'multipleOf': {
479
- constraints.multipleOf = check.value;
480
- break;
481
- }
482
- }
483
- } else {
484
- newChecks.push(check);
485
- }
486
- }
487
- }
488
- let result = z.number();
489
- for (const check of newChecks) {
490
- switch (check.kind) {
491
- case 'int':
492
- result = result.int();
493
- break;
494
- case 'finite':
495
- result = result.finite();
496
- break;
497
- default:
498
- result = result._addCheck(check);
499
- }
500
- }
501
- const description = this.mergeParameterDescription(value.description, constraints);
502
- if (description) {
503
- result = result.describe(description);
504
- }
505
- return result;
506
- }
507
-
508
- /**
509
- * Default handler for Zod date types. Converts dates to ISO strings with constraint descriptions.
510
- *
511
- * @param value - The Zod date to process
512
- * @returns A Zod string schema representing the date in ISO format
513
- */
514
- public defaultZodDateHandler(value: ZodDate): ZodString {
515
- const constraints: DateConstraints = {};
516
- const checks = value._def.checks || [];
517
- type ZodDateCheck = (typeof checks)[number];
518
- const newChecks: ZodDateCheck[] = [];
519
- for (const check of checks) {
520
- if ('kind' in check) {
521
- switch (check.kind) {
522
- case 'min':
523
- const minDate = new Date(check.value);
524
- if (!isNaN(minDate.getTime())) {
525
- constraints.minDate = minDate.toISOString();
526
- }
527
- break;
528
- case 'max':
529
- const maxDate = new Date(check.value);
530
- if (!isNaN(maxDate.getTime())) {
531
- constraints.maxDate = maxDate.toISOString();
532
- }
533
- break;
534
- default:
535
- newChecks.push(check);
536
- }
537
- }
538
- }
539
- constraints.dateFormat = 'date-time';
540
- let result = z.string().describe('date-time');
541
- const description = this.mergeParameterDescription(value.description, constraints);
542
- if (description) {
543
- result = result.describe(description);
544
- }
545
- return result;
546
- }
547
-
548
- /**
549
- * Default handler for Zod optional types. Processes the inner type and maintains optionality.
550
- *
551
- * @param value - The Zod optional to process
552
- * @param handleTypes - Types that should be processed vs passed through
553
- * @returns The processed Zod optional
554
- */
555
- public defaultZodOptionalHandler(
556
- value: ZodOptional<any>,
557
- handleTypes: readonly AllZodType[] = SUPPORTED_ZOD_TYPES,
558
- ): ZodTypeAny {
559
- if (handleTypes.includes(value._def.innerType._def.typeName as AllZodType)) {
560
- return this.processZodType(value._def.innerType).optional();
561
- } else {
562
- return value;
563
- }
564
- }
565
-
566
- /**
567
- * Processes a Zod object schema and converts it to an AI SDK Schema.
568
- *
569
- * @param zodSchema - The Zod object schema to process
570
- * @returns An AI SDK Schema with provider-specific compatibility applied
571
- */
572
- public processToAISDKSchema(zodSchema: z.ZodSchema): Schema {
573
- const processedSchema = this.processZodType(zodSchema);
574
-
575
- return convertZodSchemaToAISDKSchema(processedSchema, this.getSchemaTarget());
576
- }
577
-
578
- /**
579
- * Processes a Zod object schema and converts it to a JSON Schema.
580
- *
581
- * @param zodSchema - The Zod object schema to process
582
- * @returns A JSONSchema7 object with provider-specific compatibility applied
583
- */
584
- public processToJSONSchema(zodSchema: z.ZodSchema): JSONSchema7 {
585
- return this.processToAISDKSchema(zodSchema).jsonSchema;
586
- }
587
- }