@composio/json-schema-to-zod 0.1.18 → 0.1.20

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.
package/dist/index.js DELETED
@@ -1,793 +0,0 @@
1
- // src/parsers/parse-schema.ts
2
- import * as z16 from "zod/v3";
3
-
4
- // src/parsers/parse-all-of.ts
5
- import { z } from "zod/v3";
6
-
7
- // src/utils/half.ts
8
- var half = (arr) => {
9
- return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
10
- };
11
-
12
- // src/parsers/parse-all-of.ts
13
- var originalIndex = Symbol("Original index");
14
- var ensureOriginalIndex = (arr) => {
15
- const newArr = [];
16
- for (let i = 0; i < arr.length; i++) {
17
- const item = arr[i];
18
- if (typeof item === "boolean") {
19
- newArr.push(item ? { [originalIndex]: i } : { [originalIndex]: i, not: {} });
20
- } else if (originalIndex in item) {
21
- return arr;
22
- } else {
23
- newArr.push({ ...item, [originalIndex]: i });
24
- }
25
- }
26
- return newArr;
27
- };
28
- function parseAllOf(jsonSchema, refs) {
29
- if (jsonSchema.allOf.length === 0) {
30
- return z.never();
31
- }
32
- if (jsonSchema.allOf.length === 1) {
33
- const item = jsonSchema.allOf[0];
34
- return parseSchema(item, {
35
- ...refs,
36
- path: [...refs.path, "allOf", item[originalIndex]]
37
- });
38
- }
39
- const [left, right] = half(ensureOriginalIndex(jsonSchema.allOf));
40
- return z.intersection(parseAllOf({ allOf: left }, refs), parseAllOf({ allOf: right }, refs));
41
- }
42
-
43
- // src/parsers/parse-any-of.ts
44
- import { z as z2 } from "zod/v3";
45
- var parseAnyOf = (jsonSchema, refs) => {
46
- return jsonSchema.anyOf.length ? jsonSchema.anyOf.length === 1 ? parseSchema(jsonSchema.anyOf[0], {
47
- ...refs,
48
- path: [...refs.path, "anyOf", 0]
49
- }) : z2.union(
50
- jsonSchema.anyOf.map(
51
- (schema, i) => parseSchema(schema, { ...refs, path: [...refs.path, "anyOf", i] })
52
- )
53
- ) : z2.any();
54
- };
55
-
56
- // src/parsers/parse-array.ts
57
- import { z as z3 } from "zod/v3";
58
-
59
- // src/utils/extend-schema.ts
60
- function extendSchemaWithMessage(zodSchema, jsonSchema, key, extend) {
61
- const value = jsonSchema[key];
62
- if (value !== void 0) {
63
- const errorMessage = jsonSchema.errorMessage?.[key];
64
- return extend(zodSchema, value, errorMessage);
65
- }
66
- return zodSchema;
67
- }
68
-
69
- // src/utils/its.ts
70
- var its = {
71
- an: {
72
- object: (x) => x.type === "object" || !x.type && (x.properties !== void 0 || x.additionalProperties !== void 0 || x.patternProperties !== void 0),
73
- array: (x) => x.type === "array",
74
- anyOf: (x) => x.anyOf !== void 0,
75
- allOf: (x) => x.allOf !== void 0,
76
- enum: (x) => x.enum !== void 0
77
- },
78
- a: {
79
- nullable: (x) => x.nullable === true,
80
- multipleType: (x) => Array.isArray(x.type),
81
- not: (x) => x.not !== void 0,
82
- const: (x) => x.const !== void 0,
83
- primitive: (x, p) => x.type === p,
84
- conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
85
- oneOf: (x) => x.oneOf !== void 0
86
- }
87
- };
88
-
89
- // src/parsers/parse-array.ts
90
- var parseArray = (jsonSchema, refs) => {
91
- if (its.an.anyOf(jsonSchema)) {
92
- const types = /* @__PURE__ */ new Set();
93
- const itemsSchemas = [];
94
- jsonSchema.anyOf.forEach((option) => {
95
- if (typeof option === "object" && option.type) {
96
- types.add(typeof option.type === "string" ? option.type : option.type[0]);
97
- }
98
- if (typeof option === "object" && option.items) {
99
- const optionItems = option.items;
100
- if (!Array.isArray(optionItems) && typeof optionItems === "object") {
101
- itemsSchemas.push(optionItems);
102
- }
103
- }
104
- });
105
- let finalItems;
106
- if (itemsSchemas.length === 1) {
107
- finalItems = itemsSchemas[0];
108
- } else if (itemsSchemas.length > 1) {
109
- finalItems = { anyOf: itemsSchemas };
110
- }
111
- const newSchema = {
112
- ...types.size > 0 ? { type: Array.from(types) } : { type: "array" },
113
- ...finalItems && { items: finalItems }
114
- };
115
- const metadataFields = ["default", "description", "examples", "title"];
116
- metadataFields.forEach((field) => {
117
- const value = jsonSchema[field];
118
- if (value !== void 0) {
119
- newSchema[field] = value;
120
- }
121
- });
122
- return parseSchema(newSchema, refs);
123
- }
124
- if (Array.isArray(jsonSchema.items)) {
125
- return z3.tuple(
126
- jsonSchema.items.map(
127
- (v, i) => parseSchema(v, { ...refs, path: [...refs.path, "items", i] })
128
- )
129
- );
130
- }
131
- let zodSchema = !jsonSchema.items ? z3.array(z3.any()) : z3.array(parseSchema(jsonSchema.items, { ...refs, path: [...refs.path, "items"] }));
132
- zodSchema = extendSchemaWithMessage(
133
- zodSchema,
134
- jsonSchema,
135
- "minItems",
136
- (zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
137
- );
138
- zodSchema = extendSchemaWithMessage(
139
- zodSchema,
140
- jsonSchema,
141
- "maxItems",
142
- (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
143
- );
144
- if (typeof jsonSchema.min === "number" && typeof jsonSchema.minItems !== "number") {
145
- zodSchema = extendSchemaWithMessage(
146
- zodSchema,
147
- { ...jsonSchema, minItems: jsonSchema.min },
148
- "minItems",
149
- (zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
150
- );
151
- }
152
- if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxItems !== "number") {
153
- zodSchema = extendSchemaWithMessage(
154
- zodSchema,
155
- { ...jsonSchema, maxItems: jsonSchema.max },
156
- "maxItems",
157
- (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
158
- );
159
- }
160
- return zodSchema;
161
- };
162
-
163
- // src/parsers/parse-boolean.ts
164
- import { z as z4 } from "zod/v3";
165
- var parseBoolean = (_jsonSchema) => {
166
- return z4.boolean();
167
- };
168
-
169
- // src/parsers/parse-const.ts
170
- import { z as z5 } from "zod/v3";
171
- var parseConst = (jsonSchema) => {
172
- return z5.literal(jsonSchema.const);
173
- };
174
-
175
- // src/parsers/parse-default.ts
176
- import { z as z6 } from "zod/v3";
177
- var parseDefault = (_jsonSchema) => {
178
- return z6.any();
179
- };
180
-
181
- // src/parsers/parse-enum.ts
182
- import { z as z7 } from "zod/v3";
183
- var parseEnum = (jsonSchema) => {
184
- if (jsonSchema.enum.length === 0) {
185
- return z7.never();
186
- }
187
- if (jsonSchema.enum.length === 1) {
188
- return z7.literal(jsonSchema.enum[0]);
189
- }
190
- if (jsonSchema.enum.every((x) => typeof x === "string")) {
191
- return z7.enum(jsonSchema.enum);
192
- }
193
- return z7.union(
194
- jsonSchema.enum.map((x) => z7.literal(x))
195
- );
196
- };
197
-
198
- // src/parsers/parse-if-then-else.ts
199
- import { z as z8 } from "zod/v3";
200
- var parseIfThenElse = (jsonSchema, refs) => {
201
- const $if = parseSchema(jsonSchema.if, { ...refs, path: [...refs.path, "if"] });
202
- const $then = parseSchema(jsonSchema.then, {
203
- ...refs,
204
- path: [...refs.path, "then"]
205
- });
206
- const $else = parseSchema(jsonSchema.else, {
207
- ...refs,
208
- path: [...refs.path, "else"]
209
- });
210
- return z8.union([$then, $else]).superRefine((value, ctx) => {
211
- const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
212
- if (!result.success) {
213
- result.error.errors.forEach((error) => ctx.addIssue(error));
214
- }
215
- });
216
- };
217
-
218
- // src/parsers/parse-multiple-type.ts
219
- import { z as z9 } from "zod/v3";
220
- var parseMultipleType = (jsonSchema, refs) => {
221
- return z9.union(
222
- jsonSchema.type.map((type) => parseSchema({ ...jsonSchema, type }, refs))
223
- );
224
- };
225
-
226
- // src/parsers/parse-not.ts
227
- import { z as z10 } from "zod/v3";
228
- var parseNot = (jsonSchema, refs) => {
229
- return z10.any().refine(
230
- (value) => !parseSchema(jsonSchema.not, {
231
- ...refs,
232
- path: [...refs.path, "not"]
233
- }).safeParse(value).success,
234
- "Invalid input: Should NOT be valid against schema"
235
- );
236
- };
237
-
238
- // src/parsers/parse-null.ts
239
- import { z as z11 } from "zod/v3";
240
- var parseNull = (_jsonSchema) => {
241
- return z11.null();
242
- };
243
-
244
- // src/utils/omit.ts
245
- var omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
246
- if (!keys.includes(key)) {
247
- acc[key] = obj[key];
248
- }
249
- return acc;
250
- }, {});
251
-
252
- // src/parsers/parse-nullable.ts
253
- var parseNullable = (jsonSchema, refs) => {
254
- const hasNullDefault = jsonSchema.default === null;
255
- const baseSchema = hasNullDefault ? omit(omit(jsonSchema, "nullable"), "default") : omit(jsonSchema, "nullable");
256
- const zodSchema = parseSchema(baseSchema, refs, true).nullable();
257
- return hasNullDefault ? zodSchema.default(null) : zodSchema;
258
- };
259
-
260
- // src/parsers/parse-number.ts
261
- import { z as z12 } from "zod/v3";
262
- var parseNumber = (jsonSchema) => {
263
- let zodSchema = z12.number();
264
- let isInteger = false;
265
- if (jsonSchema.type === "integer") {
266
- isInteger = true;
267
- zodSchema = extendSchemaWithMessage(
268
- zodSchema,
269
- jsonSchema,
270
- "type",
271
- (zs, _, errorMsg) => zs.int(errorMsg)
272
- );
273
- } else if (jsonSchema.format === "int64") {
274
- isInteger = true;
275
- zodSchema = extendSchemaWithMessage(
276
- zodSchema,
277
- jsonSchema,
278
- "format",
279
- (zs, _, errorMsg) => zs.int(errorMsg)
280
- );
281
- }
282
- zodSchema = extendSchemaWithMessage(
283
- zodSchema,
284
- jsonSchema,
285
- "multipleOf",
286
- (zs, multipleOf, errorMsg) => {
287
- if (multipleOf === 1) {
288
- if (isInteger) return zs;
289
- return zs.int(errorMsg);
290
- }
291
- return zs.multipleOf(multipleOf, errorMsg);
292
- }
293
- );
294
- if (typeof jsonSchema.minimum === "number") {
295
- if (jsonSchema.exclusiveMinimum === true) {
296
- zodSchema = extendSchemaWithMessage(
297
- zodSchema,
298
- jsonSchema,
299
- "minimum",
300
- (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg)
301
- );
302
- } else {
303
- zodSchema = extendSchemaWithMessage(
304
- zodSchema,
305
- jsonSchema,
306
- "minimum",
307
- (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
308
- );
309
- }
310
- } else if (typeof jsonSchema.exclusiveMinimum === "number") {
311
- zodSchema = extendSchemaWithMessage(
312
- zodSchema,
313
- jsonSchema,
314
- "exclusiveMinimum",
315
- (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum, errorMsg)
316
- );
317
- }
318
- if (typeof jsonSchema.maximum === "number") {
319
- if (jsonSchema.exclusiveMaximum === true) {
320
- zodSchema = extendSchemaWithMessage(
321
- zodSchema,
322
- jsonSchema,
323
- "maximum",
324
- (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg)
325
- );
326
- } else {
327
- zodSchema = extendSchemaWithMessage(
328
- zodSchema,
329
- jsonSchema,
330
- "maximum",
331
- (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
332
- );
333
- }
334
- } else if (typeof jsonSchema.exclusiveMaximum === "number") {
335
- zodSchema = extendSchemaWithMessage(
336
- zodSchema,
337
- jsonSchema,
338
- "exclusiveMaximum",
339
- (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum, errorMsg)
340
- );
341
- }
342
- if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number") {
343
- zodSchema = extendSchemaWithMessage(
344
- zodSchema,
345
- { ...jsonSchema, minimum: jsonSchema.min },
346
- "minimum",
347
- (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
348
- );
349
- }
350
- if (typeof jsonSchema.max === "number" && typeof jsonSchema.maximum !== "number") {
351
- zodSchema = extendSchemaWithMessage(
352
- zodSchema,
353
- { ...jsonSchema, maximum: jsonSchema.max },
354
- "maximum",
355
- (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
356
- );
357
- }
358
- return zodSchema;
359
- };
360
-
361
- // src/parsers/parse-object.ts
362
- import * as z14 from "zod/v3";
363
-
364
- // src/parsers/parse-one-of.ts
365
- import { z as z13 } from "zod/v3";
366
- var parseOneOf = (jsonSchema, refs) => {
367
- if (!jsonSchema.oneOf.length) {
368
- return z13.any();
369
- }
370
- if (jsonSchema.oneOf.length === 1) {
371
- return parseSchema(jsonSchema.oneOf[0], {
372
- ...refs,
373
- path: [...refs.path, "oneOf", 0]
374
- });
375
- }
376
- return z13.any().superRefine((x, ctx) => {
377
- const schemas = jsonSchema.oneOf.map(
378
- (schema, i) => parseSchema(schema, {
379
- ...refs,
380
- path: [...refs.path, "oneOf", i]
381
- })
382
- );
383
- const unionErrors = schemas.reduce(
384
- (errors, schema) => ((result) => result.error ? [...errors, result.error] : errors)(schema.safeParse(x)),
385
- []
386
- );
387
- if (schemas.length - unionErrors.length !== 1) {
388
- ctx.addIssue({
389
- path: ctx.path,
390
- code: "invalid_union",
391
- unionErrors,
392
- message: "Invalid input: Should pass single schema"
393
- });
394
- }
395
- });
396
- };
397
-
398
- // src/parsers/parse-object.ts
399
- function parseObjectProperties(objectSchema, refs) {
400
- if (!objectSchema.properties) {
401
- return z14.object({});
402
- }
403
- const propertyKeys = Object.keys(objectSchema.properties);
404
- if (propertyKeys.length === 0) {
405
- return z14.object({});
406
- }
407
- const properties = {};
408
- for (const key of propertyKeys) {
409
- const propJsonSchema = objectSchema.properties[key];
410
- const propZodSchema = parseSchema(propJsonSchema, {
411
- ...refs,
412
- path: [...refs.path, "properties", key]
413
- });
414
- const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
415
- if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) {
416
- if (propJsonSchema.default === null) {
417
- const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some(
418
- (schema) => typeof schema === "object" && schema !== null && schema.type === "null"
419
- );
420
- const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some(
421
- (schema) => typeof schema === "object" && schema !== null && schema.type === "null"
422
- );
423
- const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
424
- if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) {
425
- properties[key] = propZodSchema.optional().default(null);
426
- } else {
427
- properties[key] = propZodSchema.nullable().optional().default(null);
428
- }
429
- } else {
430
- properties[key] = propZodSchema.optional().default(propJsonSchema.default);
431
- }
432
- } else {
433
- properties[key] = required ? propZodSchema : propZodSchema.optional();
434
- }
435
- }
436
- return z14.object(properties);
437
- }
438
- function parseObject(objectSchema, refs) {
439
- const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
440
- const normalizedSchema = objectSchema.type === "object" ? objectSchema : { ...objectSchema, type: "object" };
441
- const propertiesSchema = parseObjectProperties(normalizedSchema, refs);
442
- let zodSchema = propertiesSchema;
443
- const additionalProperties = normalizedSchema.additionalProperties !== void 0 ? parseSchema(normalizedSchema.additionalProperties, {
444
- ...refs,
445
- path: [...refs.path, "additionalProperties"]
446
- }) : void 0;
447
- const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
448
- if (normalizedSchema.patternProperties) {
449
- const parsedPatternProperties = Object.fromEntries(
450
- Object.entries(normalizedSchema.patternProperties).map(([key, value]) => {
451
- return [
452
- key,
453
- parseSchema(value, {
454
- ...refs,
455
- path: [...refs.path, "patternProperties", key]
456
- })
457
- ];
458
- })
459
- );
460
- const patternPropertyValues = Object.values(parsedPatternProperties);
461
- if (propertiesSchema) {
462
- if (additionalProperties) {
463
- zodSchema = propertiesSchema.catchall(
464
- z14.union([...patternPropertyValues, additionalProperties])
465
- );
466
- } else if (Object.keys(parsedPatternProperties).length > 1) {
467
- zodSchema = propertiesSchema.catchall(
468
- z14.union(patternPropertyValues)
469
- );
470
- } else {
471
- zodSchema = propertiesSchema.catchall(patternPropertyValues[0]);
472
- }
473
- } else {
474
- if (additionalProperties) {
475
- zodSchema = z14.record(
476
- z14.union([...patternPropertyValues, additionalProperties])
477
- );
478
- } else if (patternPropertyValues.length > 1) {
479
- zodSchema = z14.record(z14.union(patternPropertyValues));
480
- } else {
481
- zodSchema = z14.record(patternPropertyValues[0]);
482
- }
483
- }
484
- const objectPropertyKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
485
- zodSchema = zodSchema.superRefine((value, ctx) => {
486
- for (const key in value) {
487
- let wasMatched = objectPropertyKeys.has(key);
488
- for (const patternPropertyKey in normalizedSchema.patternProperties) {
489
- const regex = new RegExp(patternPropertyKey);
490
- if (key.match(regex)) {
491
- wasMatched = true;
492
- const result = parsedPatternProperties[patternPropertyKey].safeParse(value[key]);
493
- if (!result.success) {
494
- ctx.addIssue({
495
- path: [...ctx.path, key],
496
- code: "custom",
497
- message: `Invalid input: Key matching regex /${key}/ must match schema`,
498
- params: {
499
- issues: result.error.issues
500
- }
501
- });
502
- }
503
- }
504
- }
505
- if (!wasMatched && additionalProperties) {
506
- const result = additionalProperties.safeParse(value[key]);
507
- if (!result.success) {
508
- ctx.addIssue({
509
- path: [...ctx.path, key],
510
- code: "custom",
511
- message: "Invalid input: must match catchall schema",
512
- params: {
513
- issues: result.error.issues
514
- }
515
- });
516
- }
517
- }
518
- }
519
- });
520
- }
521
- let output;
522
- if (propertiesSchema) {
523
- if (hasPatternProperties) {
524
- output = zodSchema;
525
- } else if (additionalProperties) {
526
- if (additionalProperties instanceof z14.ZodNever) {
527
- output = propertiesSchema.strict();
528
- } else if (isAdditionalPropertiesTrue) {
529
- output = propertiesSchema.passthrough();
530
- } else {
531
- output = propertiesSchema.catchall(additionalProperties);
532
- }
533
- } else {
534
- output = propertiesSchema.strict();
535
- }
536
- } else {
537
- if (hasPatternProperties) {
538
- output = zodSchema;
539
- } else if (additionalProperties) {
540
- if (additionalProperties instanceof z14.ZodNever) {
541
- output = z14.object({}).strict();
542
- } else if (isAdditionalPropertiesTrue) {
543
- output = z14.object({}).passthrough();
544
- } else {
545
- output = z14.record(additionalProperties);
546
- }
547
- } else {
548
- output = z14.object({}).passthrough();
549
- }
550
- }
551
- if (its.an.anyOf(objectSchema)) {
552
- output = output.and(
553
- parseAnyOf(
554
- {
555
- ...objectSchema,
556
- anyOf: objectSchema.anyOf.map(
557
- (x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? { ...x, type: "object" } : x
558
- )
559
- },
560
- refs
561
- )
562
- );
563
- }
564
- if (its.a.oneOf(objectSchema)) {
565
- output = output.and(
566
- parseOneOf(
567
- {
568
- ...objectSchema,
569
- oneOf: objectSchema.oneOf.map(
570
- (x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? { ...x, type: "object" } : x
571
- )
572
- },
573
- refs
574
- )
575
- );
576
- }
577
- if (its.an.allOf(objectSchema)) {
578
- output = output.and(
579
- parseAllOf(
580
- {
581
- ...objectSchema,
582
- allOf: objectSchema.allOf.map(
583
- (x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? { ...x, type: "object" } : x
584
- )
585
- },
586
- refs
587
- )
588
- );
589
- }
590
- return output;
591
- }
592
-
593
- // src/parsers/parse-string.ts
594
- import { z as z15 } from "zod/v3";
595
- var parseString = (jsonSchema) => {
596
- let zodSchema = z15.string();
597
- zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, format, errorMsg) => {
598
- switch (format) {
599
- case "email":
600
- return zs.email(errorMsg);
601
- case "ip":
602
- return zs.ip(errorMsg);
603
- case "ipv4":
604
- return zs.ip({ version: "v4", message: errorMsg });
605
- case "ipv6":
606
- return zs.ip({ version: "v6", message: errorMsg });
607
- case "uri":
608
- return zs.url(errorMsg);
609
- case "uuid":
610
- return zs.uuid(errorMsg);
611
- case "date-time":
612
- return zs.datetime({ offset: true, message: errorMsg });
613
- case "time":
614
- return zs.time(errorMsg);
615
- case "date":
616
- return zs.date(errorMsg);
617
- case "binary":
618
- return zs.base64(errorMsg);
619
- case "duration":
620
- return zs.duration(errorMsg);
621
- default:
622
- return zs;
623
- }
624
- });
625
- zodSchema = extendSchemaWithMessage(
626
- zodSchema,
627
- jsonSchema,
628
- "contentEncoding",
629
- (zs, _, errorMsg) => zs.base64(errorMsg)
630
- );
631
- zodSchema = extendSchemaWithMessage(
632
- zodSchema,
633
- jsonSchema,
634
- "pattern",
635
- (zs, pattern, errorMsg) => zs.regex(new RegExp(pattern), errorMsg)
636
- );
637
- zodSchema = extendSchemaWithMessage(
638
- zodSchema,
639
- jsonSchema,
640
- "minLength",
641
- (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
642
- );
643
- zodSchema = extendSchemaWithMessage(
644
- zodSchema,
645
- jsonSchema,
646
- "maxLength",
647
- (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
648
- );
649
- if (typeof jsonSchema.min === "number" && typeof jsonSchema.minLength !== "number") {
650
- zodSchema = extendSchemaWithMessage(
651
- zodSchema,
652
- { ...jsonSchema, minLength: jsonSchema.min },
653
- "minLength",
654
- (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
655
- );
656
- }
657
- if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxLength !== "number") {
658
- zodSchema = extendSchemaWithMessage(
659
- zodSchema,
660
- { ...jsonSchema, maxLength: jsonSchema.max },
661
- "maxLength",
662
- (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
663
- );
664
- }
665
- return zodSchema;
666
- };
667
-
668
- // src/parsers/parse-schema.ts
669
- var addDescribes = (jsonSchema, zodSchema) => {
670
- let description = "";
671
- if (jsonSchema.description) {
672
- description = jsonSchema.description;
673
- } else if (jsonSchema.title) {
674
- description = jsonSchema.title;
675
- }
676
- if (jsonSchema.example !== void 0) {
677
- const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
678
- description = description ? `${description}
679
- ${exampleText}` : exampleText;
680
- } else if (jsonSchema.examples !== void 0 && Array.isArray(jsonSchema.examples)) {
681
- const examples = jsonSchema.examples;
682
- if (examples && examples.length && examples.length > 0) {
683
- const exampleText = examples.length === 1 ? `Example: ${JSON.stringify(examples[0])}` : `Examples:
684
- ${examples.map((ex) => ` ${JSON.stringify(ex)}`).join("\n")}`;
685
- description = description ? `${description}
686
- ${exampleText}` : exampleText;
687
- }
688
- }
689
- if (description) {
690
- zodSchema = zodSchema.describe(description);
691
- }
692
- return zodSchema;
693
- };
694
- var addDefaults = (jsonSchema, zodSchema, refs) => {
695
- if (jsonSchema.default !== void 0) {
696
- if (jsonSchema.default === null) {
697
- const inAnyOfOrOneOf = refs?.path.some((segment) => segment === "anyOf" || segment === "oneOf");
698
- if (inAnyOfOrOneOf && jsonSchema.type && jsonSchema.type !== "null" && // @ts-ignore: `nullable` is not publicly available in Zod 4
699
- !jsonSchema.nullable) {
700
- return zodSchema;
701
- }
702
- }
703
- zodSchema = zodSchema.default(jsonSchema.default);
704
- }
705
- return zodSchema;
706
- };
707
- var addAnnotations = (jsonSchema, zodSchema) => {
708
- if (jsonSchema.readOnly) {
709
- zodSchema = zodSchema.readonly();
710
- }
711
- return zodSchema;
712
- };
713
- var selectParser = (schema, refs) => {
714
- if (its.a.nullable(schema)) {
715
- return parseNullable(schema, refs);
716
- } else if (its.an.object(schema)) {
717
- return parseObject(schema, refs);
718
- } else if (its.an.array(schema)) {
719
- return parseArray(schema, refs);
720
- } else if (its.an.anyOf(schema)) {
721
- return parseAnyOf(schema, refs);
722
- } else if (its.an.allOf(schema)) {
723
- return parseAllOf(schema, refs);
724
- } else if (its.a.oneOf(schema)) {
725
- return parseOneOf(schema, refs);
726
- } else if (its.a.not(schema)) {
727
- return parseNot(schema, refs);
728
- } else if (its.an.enum(schema)) {
729
- return parseEnum(schema);
730
- } else if (its.a.const(schema)) {
731
- return parseConst(schema);
732
- } else if (its.a.multipleType(schema)) {
733
- return parseMultipleType(schema, refs);
734
- } else if (its.a.primitive(schema, "string")) {
735
- return parseString(schema);
736
- } else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) {
737
- return parseNumber(schema);
738
- } else if (its.a.primitive(schema, "boolean")) {
739
- return parseBoolean(schema);
740
- } else if (its.a.primitive(schema, "null")) {
741
- return parseNull(schema);
742
- } else if (its.a.conditional(schema)) {
743
- return parseIfThenElse(schema, refs);
744
- } else {
745
- return parseDefault(schema);
746
- }
747
- };
748
- var parseSchema = (jsonSchema, refs = { seen: /* @__PURE__ */ new Map(), path: [] }, blockMeta) => {
749
- if (typeof jsonSchema !== "object") return jsonSchema ? z16.any() : z16.never();
750
- if (refs.parserOverride) {
751
- const custom = refs.parserOverride(jsonSchema, refs);
752
- if (custom instanceof z16.ZodType) {
753
- return custom;
754
- }
755
- }
756
- let seen = refs.seen.get(jsonSchema);
757
- if (seen) {
758
- if (seen.r !== void 0) {
759
- return seen.r;
760
- }
761
- if (refs.depth === void 0 || seen.n >= refs.depth) {
762
- return z16.any();
763
- }
764
- seen.n += 1;
765
- } else {
766
- seen = { r: void 0, n: 0 };
767
- refs.seen.set(jsonSchema, seen);
768
- }
769
- let parsedZodSchema = selectParser(jsonSchema, refs);
770
- if (!blockMeta) {
771
- if (!refs.withoutDescribes) {
772
- parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
773
- }
774
- if (!refs.withoutDefaults) {
775
- parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, refs);
776
- }
777
- parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
778
- }
779
- seen.r = parsedZodSchema;
780
- return parsedZodSchema;
781
- };
782
-
783
- // src/json-schema-to-zod.ts
784
- var jsonSchemaToZod = (schema, options = {}) => {
785
- return parseSchema(schema, {
786
- path: [],
787
- seen: /* @__PURE__ */ new Map(),
788
- ...options
789
- });
790
- };
791
- export {
792
- jsonSchemaToZod
793
- };