@composio/json-schema-to-zod 0.1.19 → 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.mjs ADDED
@@ -0,0 +1,628 @@
1
+ import * as z$1 from "zod/v3";
2
+ import { z } from "zod/v3";
3
+
4
+ //#region src/utils/half.ts
5
+ const half = (arr) => {
6
+ return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
7
+ };
8
+
9
+ //#endregion
10
+ //#region src/parsers/parse-all-of.ts
11
+ const originalIndex = Symbol("Original index");
12
+ const ensureOriginalIndex = (arr) => {
13
+ const newArr = [];
14
+ for (let i = 0; i < arr.length; i++) {
15
+ const item = arr[i];
16
+ if (typeof item === "boolean") newArr.push(item ? { [originalIndex]: i } : {
17
+ [originalIndex]: i,
18
+ not: {}
19
+ });
20
+ else if (originalIndex in item) return arr;
21
+ else newArr.push({
22
+ ...item,
23
+ [originalIndex]: i
24
+ });
25
+ }
26
+ return newArr;
27
+ };
28
+ function parseAllOf(jsonSchema, refs) {
29
+ if (jsonSchema.allOf.length === 0) return z.never();
30
+ if (jsonSchema.allOf.length === 1) {
31
+ const item = jsonSchema.allOf[0];
32
+ return parseSchema(item, {
33
+ ...refs,
34
+ path: [
35
+ ...refs.path,
36
+ "allOf",
37
+ item[originalIndex]
38
+ ]
39
+ });
40
+ }
41
+ const [left, right] = half(ensureOriginalIndex(jsonSchema.allOf));
42
+ return z.intersection(parseAllOf({ allOf: left }, refs), parseAllOf({ allOf: right }, refs));
43
+ }
44
+
45
+ //#endregion
46
+ //#region src/parsers/parse-any-of.ts
47
+ const parseAnyOf = (jsonSchema, refs) => {
48
+ return jsonSchema.anyOf.length ? jsonSchema.anyOf.length === 1 ? parseSchema(jsonSchema.anyOf[0], {
49
+ ...refs,
50
+ path: [
51
+ ...refs.path,
52
+ "anyOf",
53
+ 0
54
+ ]
55
+ }) : z.union(jsonSchema.anyOf.map((schema, i) => parseSchema(schema, {
56
+ ...refs,
57
+ path: [
58
+ ...refs.path,
59
+ "anyOf",
60
+ i
61
+ ]
62
+ }))) : z.any();
63
+ };
64
+
65
+ //#endregion
66
+ //#region src/utils/extend-schema.ts
67
+ function extendSchemaWithMessage(zodSchema, jsonSchema, key, extend) {
68
+ const value = jsonSchema[key];
69
+ if (value !== void 0) {
70
+ const errorMessage = jsonSchema.errorMessage?.[key];
71
+ return extend(zodSchema, value, errorMessage);
72
+ }
73
+ return zodSchema;
74
+ }
75
+
76
+ //#endregion
77
+ //#region src/utils/its.ts
78
+ const its = {
79
+ an: {
80
+ object: (x) => x.type === "object" || !x.type && (x.properties !== void 0 || x.additionalProperties !== void 0 || x.patternProperties !== void 0),
81
+ array: (x) => x.type === "array",
82
+ anyOf: (x) => x.anyOf !== void 0,
83
+ allOf: (x) => x.allOf !== void 0,
84
+ enum: (x) => x.enum !== void 0
85
+ },
86
+ a: {
87
+ nullable: (x) => x.nullable === true,
88
+ multipleType: (x) => Array.isArray(x.type),
89
+ not: (x) => x.not !== void 0,
90
+ const: (x) => x.const !== void 0,
91
+ primitive: (x, p) => x.type === p,
92
+ conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
93
+ oneOf: (x) => x.oneOf !== void 0
94
+ }
95
+ };
96
+
97
+ //#endregion
98
+ //#region src/parsers/parse-array.ts
99
+ const parseArray = (jsonSchema, refs) => {
100
+ if (its.an.anyOf(jsonSchema)) {
101
+ const types = /* @__PURE__ */ new Set();
102
+ const itemsSchemas = [];
103
+ jsonSchema.anyOf.forEach((option) => {
104
+ if (typeof option === "object" && option.type) types.add(typeof option.type === "string" ? option.type : option.type[0]);
105
+ if (typeof option === "object" && option.items) {
106
+ const optionItems = option.items;
107
+ if (!Array.isArray(optionItems) && typeof optionItems === "object") itemsSchemas.push(optionItems);
108
+ }
109
+ });
110
+ let finalItems;
111
+ if (itemsSchemas.length === 1) finalItems = itemsSchemas[0];
112
+ else if (itemsSchemas.length > 1) finalItems = { anyOf: itemsSchemas };
113
+ const newSchema = {
114
+ ...types.size > 0 ? { type: Array.from(types) } : { type: "array" },
115
+ ...finalItems && { items: finalItems }
116
+ };
117
+ [
118
+ "default",
119
+ "description",
120
+ "examples",
121
+ "title"
122
+ ].forEach((field) => {
123
+ const value = jsonSchema[field];
124
+ if (value !== void 0) newSchema[field] = value;
125
+ });
126
+ return parseSchema(newSchema, refs);
127
+ }
128
+ if (Array.isArray(jsonSchema.items)) return z.tuple(jsonSchema.items.map((v, i) => parseSchema(v, {
129
+ ...refs,
130
+ path: [
131
+ ...refs.path,
132
+ "items",
133
+ i
134
+ ]
135
+ })));
136
+ let zodSchema = !jsonSchema.items ? z.array(z.any()) : z.array(parseSchema(jsonSchema.items, {
137
+ ...refs,
138
+ path: [...refs.path, "items"]
139
+ }));
140
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
141
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
142
+ if (typeof jsonSchema.min === "number" && typeof jsonSchema.minItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
143
+ ...jsonSchema,
144
+ minItems: jsonSchema.min
145
+ }, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
146
+ if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
147
+ ...jsonSchema,
148
+ maxItems: jsonSchema.max
149
+ }, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
150
+ return zodSchema;
151
+ };
152
+
153
+ //#endregion
154
+ //#region src/parsers/parse-boolean.ts
155
+ const parseBoolean = (_jsonSchema) => {
156
+ return z.boolean();
157
+ };
158
+
159
+ //#endregion
160
+ //#region src/parsers/parse-const.ts
161
+ const parseConst = (jsonSchema) => {
162
+ return z.literal(jsonSchema.const);
163
+ };
164
+
165
+ //#endregion
166
+ //#region src/parsers/parse-default.ts
167
+ const parseDefault = (_jsonSchema) => {
168
+ return z.any();
169
+ };
170
+
171
+ //#endregion
172
+ //#region src/parsers/parse-enum.ts
173
+ const parseEnum = (jsonSchema) => {
174
+ if (jsonSchema.enum.length === 0) return z.never();
175
+ if (jsonSchema.enum.length === 1) return z.literal(jsonSchema.enum[0]);
176
+ if (jsonSchema.enum.every((x) => typeof x === "string")) return z.enum(jsonSchema.enum);
177
+ return z.union(jsonSchema.enum.map((x) => z.literal(x)));
178
+ };
179
+
180
+ //#endregion
181
+ //#region src/parsers/parse-if-then-else.ts
182
+ const parseIfThenElse = (jsonSchema, refs) => {
183
+ const $if = parseSchema(jsonSchema.if, {
184
+ ...refs,
185
+ path: [...refs.path, "if"]
186
+ });
187
+ const $then = parseSchema(jsonSchema.then, {
188
+ ...refs,
189
+ path: [...refs.path, "then"]
190
+ });
191
+ const $else = parseSchema(jsonSchema.else, {
192
+ ...refs,
193
+ path: [...refs.path, "else"]
194
+ });
195
+ return z.union([$then, $else]).superRefine((value, ctx) => {
196
+ const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
197
+ if (!result.success) result.error.errors.forEach((error) => ctx.addIssue(error));
198
+ });
199
+ };
200
+
201
+ //#endregion
202
+ //#region src/parsers/parse-multiple-type.ts
203
+ const parseMultipleType = (jsonSchema, refs) => {
204
+ return z.union(jsonSchema.type.map((type) => parseSchema({
205
+ ...jsonSchema,
206
+ type
207
+ }, refs)));
208
+ };
209
+
210
+ //#endregion
211
+ //#region src/parsers/parse-not.ts
212
+ const parseNot = (jsonSchema, refs) => {
213
+ return z.any().refine((value) => !parseSchema(jsonSchema.not, {
214
+ ...refs,
215
+ path: [...refs.path, "not"]
216
+ }).safeParse(value).success, "Invalid input: Should NOT be valid against schema");
217
+ };
218
+
219
+ //#endregion
220
+ //#region src/parsers/parse-null.ts
221
+ const parseNull = (_jsonSchema) => {
222
+ return z.null();
223
+ };
224
+
225
+ //#endregion
226
+ //#region src/utils/omit.ts
227
+ const omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
228
+ if (!keys.includes(key)) acc[key] = obj[key];
229
+ return acc;
230
+ }, {});
231
+
232
+ //#endregion
233
+ //#region src/parsers/parse-nullable.ts
234
+ /**
235
+ * For compatibility with open api 3.0 nullable
236
+ */
237
+ const parseNullable = (jsonSchema, refs) => {
238
+ const hasNullDefault = jsonSchema.default === null;
239
+ const zodSchema = parseSchema(hasNullDefault ? omit(omit(jsonSchema, "nullable"), "default") : omit(jsonSchema, "nullable"), refs, true).nullable();
240
+ return hasNullDefault ? zodSchema.default(null) : zodSchema;
241
+ };
242
+
243
+ //#endregion
244
+ //#region src/parsers/parse-number.ts
245
+ const parseNumber = (jsonSchema) => {
246
+ let zodSchema = z.number();
247
+ let isInteger = false;
248
+ if (jsonSchema.type === "integer") {
249
+ isInteger = true;
250
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "type", (zs, _, errorMsg) => zs.int(errorMsg));
251
+ } else if (jsonSchema.format === "int64") {
252
+ isInteger = true;
253
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, _, errorMsg) => zs.int(errorMsg));
254
+ }
255
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "multipleOf", (zs, multipleOf, errorMsg) => {
256
+ if (multipleOf === 1) {
257
+ if (isInteger) return zs;
258
+ return zs.int(errorMsg);
259
+ }
260
+ return zs.multipleOf(multipleOf, errorMsg);
261
+ });
262
+ if (typeof jsonSchema.minimum === "number") if (jsonSchema.exclusiveMinimum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg));
263
+ else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
264
+ else if (typeof jsonSchema.exclusiveMinimum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMinimum", (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum, errorMsg));
265
+ if (typeof jsonSchema.maximum === "number") if (jsonSchema.exclusiveMaximum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg));
266
+ else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
267
+ else if (typeof jsonSchema.exclusiveMaximum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMaximum", (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum, errorMsg));
268
+ if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
269
+ ...jsonSchema,
270
+ minimum: jsonSchema.min
271
+ }, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
272
+ if (typeof jsonSchema.max === "number" && typeof jsonSchema.maximum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
273
+ ...jsonSchema,
274
+ maximum: jsonSchema.max
275
+ }, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
276
+ return zodSchema;
277
+ };
278
+
279
+ //#endregion
280
+ //#region src/parsers/parse-one-of.ts
281
+ const parseOneOf = (jsonSchema, refs) => {
282
+ if (!jsonSchema.oneOf.length) return z.any();
283
+ if (jsonSchema.oneOf.length === 1) return parseSchema(jsonSchema.oneOf[0], {
284
+ ...refs,
285
+ path: [
286
+ ...refs.path,
287
+ "oneOf",
288
+ 0
289
+ ]
290
+ });
291
+ return z.any().superRefine((x, ctx) => {
292
+ const schemas = jsonSchema.oneOf.map((schema, i) => parseSchema(schema, {
293
+ ...refs,
294
+ path: [
295
+ ...refs.path,
296
+ "oneOf",
297
+ i
298
+ ]
299
+ }));
300
+ const unionErrors = schemas.reduce((errors, schema) => ((result) => result.error ? [...errors, result.error] : errors)(schema.safeParse(x)), []);
301
+ if (schemas.length - unionErrors.length !== 1) ctx.addIssue({
302
+ path: ctx.path,
303
+ code: "invalid_union",
304
+ unionErrors,
305
+ message: "Invalid input: Should pass single schema"
306
+ });
307
+ });
308
+ };
309
+
310
+ //#endregion
311
+ //#region src/parsers/parse-object.ts
312
+ function parseObjectProperties(objectSchema, refs) {
313
+ if (!objectSchema.properties) return z$1.object({});
314
+ const propertyKeys = Object.keys(objectSchema.properties);
315
+ if (propertyKeys.length === 0) return z$1.object({});
316
+ const properties = {};
317
+ for (const key of propertyKeys) {
318
+ const propJsonSchema = objectSchema.properties[key];
319
+ const propZodSchema = parseSchema(propJsonSchema, {
320
+ ...refs,
321
+ path: [
322
+ ...refs.path,
323
+ "properties",
324
+ key
325
+ ]
326
+ });
327
+ const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
328
+ if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) if (propJsonSchema.default === null) {
329
+ const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
330
+ const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
331
+ const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
332
+ if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) properties[key] = propZodSchema.optional().default(null);
333
+ else properties[key] = propZodSchema.nullable().optional().default(null);
334
+ } else properties[key] = propZodSchema.optional().default(propJsonSchema.default);
335
+ else properties[key] = required ? propZodSchema : propZodSchema.optional();
336
+ }
337
+ return z$1.object(properties);
338
+ }
339
+ function parseObject(objectSchema, refs) {
340
+ const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
341
+ const normalizedSchema = objectSchema.type === "object" ? objectSchema : {
342
+ ...objectSchema,
343
+ type: "object"
344
+ };
345
+ const propertiesSchema = parseObjectProperties(normalizedSchema, refs);
346
+ let zodSchema = propertiesSchema;
347
+ const additionalProperties = normalizedSchema.additionalProperties !== void 0 ? parseSchema(normalizedSchema.additionalProperties, {
348
+ ...refs,
349
+ path: [...refs.path, "additionalProperties"]
350
+ }) : void 0;
351
+ const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
352
+ if (normalizedSchema.patternProperties) {
353
+ const parsedPatternProperties = Object.fromEntries(Object.entries(normalizedSchema.patternProperties).map(([key, value]) => {
354
+ return [key, parseSchema(value, {
355
+ ...refs,
356
+ path: [
357
+ ...refs.path,
358
+ "patternProperties",
359
+ key
360
+ ]
361
+ })];
362
+ }));
363
+ const patternPropertyValues = Object.values(parsedPatternProperties);
364
+ if (propertiesSchema) if (additionalProperties) zodSchema = propertiesSchema.catchall(z$1.union([...patternPropertyValues, additionalProperties]));
365
+ else if (Object.keys(parsedPatternProperties).length > 1) zodSchema = propertiesSchema.catchall(z$1.union(patternPropertyValues));
366
+ else zodSchema = propertiesSchema.catchall(patternPropertyValues[0]);
367
+ else if (additionalProperties) zodSchema = z$1.record(z$1.union([...patternPropertyValues, additionalProperties]));
368
+ else if (patternPropertyValues.length > 1) zodSchema = z$1.record(z$1.union(patternPropertyValues));
369
+ else zodSchema = z$1.record(patternPropertyValues[0]);
370
+ const objectPropertyKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
371
+ zodSchema = zodSchema.superRefine((value, ctx) => {
372
+ for (const key in value) {
373
+ let wasMatched = objectPropertyKeys.has(key);
374
+ for (const patternPropertyKey in normalizedSchema.patternProperties) {
375
+ const regex = new RegExp(patternPropertyKey);
376
+ if (key.match(regex)) {
377
+ wasMatched = true;
378
+ const result = parsedPatternProperties[patternPropertyKey].safeParse(value[key]);
379
+ if (!result.success) ctx.addIssue({
380
+ path: [...ctx.path, key],
381
+ code: "custom",
382
+ message: `Invalid input: Key matching regex /${key}/ must match schema`,
383
+ params: { issues: result.error.issues }
384
+ });
385
+ }
386
+ }
387
+ if (!wasMatched && additionalProperties) {
388
+ const result = additionalProperties.safeParse(value[key]);
389
+ if (!result.success) ctx.addIssue({
390
+ path: [...ctx.path, key],
391
+ code: "custom",
392
+ message: "Invalid input: must match catchall schema",
393
+ params: { issues: result.error.issues }
394
+ });
395
+ }
396
+ }
397
+ });
398
+ }
399
+ let output;
400
+ if (propertiesSchema) if (hasPatternProperties) output = zodSchema;
401
+ else if (additionalProperties) if (additionalProperties instanceof z$1.ZodNever) output = propertiesSchema.strict();
402
+ else if (isAdditionalPropertiesTrue) output = propertiesSchema.passthrough();
403
+ else output = propertiesSchema.catchall(additionalProperties);
404
+ else output = propertiesSchema.strict();
405
+ else if (hasPatternProperties) output = zodSchema;
406
+ else if (additionalProperties) if (additionalProperties instanceof z$1.ZodNever) output = z$1.object({}).strict();
407
+ else if (isAdditionalPropertiesTrue) output = z$1.object({}).passthrough();
408
+ else output = z$1.record(additionalProperties);
409
+ else output = z$1.object({}).passthrough();
410
+ if (its.an.anyOf(objectSchema)) output = output.and(parseAnyOf({
411
+ ...objectSchema,
412
+ anyOf: objectSchema.anyOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
413
+ ...x,
414
+ type: "object"
415
+ } : x)
416
+ }, refs));
417
+ if (its.a.oneOf(objectSchema)) output = output.and(parseOneOf({
418
+ ...objectSchema,
419
+ oneOf: objectSchema.oneOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
420
+ ...x,
421
+ type: "object"
422
+ } : x)
423
+ }, refs));
424
+ if (its.an.allOf(objectSchema)) output = output.and(parseAllOf({
425
+ ...objectSchema,
426
+ allOf: objectSchema.allOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
427
+ ...x,
428
+ type: "object"
429
+ } : x)
430
+ }, refs));
431
+ return output;
432
+ }
433
+
434
+ //#endregion
435
+ //#region src/parsers/parse-string.ts
436
+ const parseString = (jsonSchema) => {
437
+ let zodSchema = z.string();
438
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, format, errorMsg) => {
439
+ switch (format) {
440
+ case "email": return zs.email(errorMsg);
441
+ case "ip": return zs.ip(errorMsg);
442
+ case "ipv4": return zs.ip({
443
+ version: "v4",
444
+ message: errorMsg
445
+ });
446
+ case "ipv6": return zs.ip({
447
+ version: "v6",
448
+ message: errorMsg
449
+ });
450
+ case "uri": return zs.url(errorMsg);
451
+ case "uuid": return zs.uuid(errorMsg);
452
+ case "date-time": return zs.datetime({
453
+ offset: true,
454
+ message: errorMsg
455
+ });
456
+ case "time": return zs.time(errorMsg);
457
+ case "date": return zs.date(errorMsg);
458
+ case "binary": return zs.base64(errorMsg);
459
+ case "duration": return zs.duration(errorMsg);
460
+ default: return zs;
461
+ }
462
+ });
463
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "contentEncoding", (zs, _, errorMsg) => zs.base64(errorMsg));
464
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "pattern", (zs, pattern, errorMsg) => zs.regex(new RegExp(pattern), errorMsg));
465
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minLength", (zs, minLength, errorMsg) => zs.min(minLength, errorMsg));
466
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maxLength", (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg));
467
+ if (typeof jsonSchema.min === "number" && typeof jsonSchema.minLength !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
468
+ ...jsonSchema,
469
+ minLength: jsonSchema.min
470
+ }, "minLength", (zs, minLength, errorMsg) => zs.min(minLength, errorMsg));
471
+ if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxLength !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
472
+ ...jsonSchema,
473
+ maxLength: jsonSchema.max
474
+ }, "maxLength", (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg));
475
+ return zodSchema;
476
+ };
477
+
478
+ //#endregion
479
+ //#region src/parsers/parse-schema.ts
480
+ const addDescribes = (jsonSchema, zodSchema) => {
481
+ let description = "";
482
+ if (jsonSchema.description) description = jsonSchema.description;
483
+ else if (jsonSchema.title) description = jsonSchema.title;
484
+ if (jsonSchema.example !== void 0) {
485
+ const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
486
+ description = description ? `${description}\n${exampleText}` : exampleText;
487
+ } else if (jsonSchema.examples !== void 0 && Array.isArray(jsonSchema.examples)) {
488
+ const examples = jsonSchema.examples;
489
+ if (examples && examples.length && examples.length > 0) {
490
+ const exampleText = examples.length === 1 ? `Example: ${JSON.stringify(examples[0])}` : `Examples:\n${examples.map((ex) => ` ${JSON.stringify(ex)}`).join("\n")}`;
491
+ description = description ? `${description}\n${exampleText}` : exampleText;
492
+ }
493
+ }
494
+ if (description) zodSchema = zodSchema.describe(description);
495
+ return zodSchema;
496
+ };
497
+ const addDefaults = (jsonSchema, zodSchema, refs) => {
498
+ if (jsonSchema.default !== void 0) {
499
+ if (jsonSchema.default === null) {
500
+ if (refs?.path.some((segment) => segment === "anyOf" || segment === "oneOf") && jsonSchema.type && jsonSchema.type !== "null" && !jsonSchema.nullable) return zodSchema;
501
+ }
502
+ zodSchema = zodSchema.default(jsonSchema.default);
503
+ }
504
+ return zodSchema;
505
+ };
506
+ const addAnnotations = (jsonSchema, zodSchema) => {
507
+ if (jsonSchema.readOnly) zodSchema = zodSchema.readonly();
508
+ return zodSchema;
509
+ };
510
+ const selectParser = (schema, refs) => {
511
+ if (its.a.nullable(schema)) return parseNullable(schema, refs);
512
+ else if (its.an.object(schema)) return parseObject(schema, refs);
513
+ else if (its.an.array(schema)) return parseArray(schema, refs);
514
+ else if (its.an.anyOf(schema)) return parseAnyOf(schema, refs);
515
+ else if (its.an.allOf(schema)) return parseAllOf(schema, refs);
516
+ else if (its.a.oneOf(schema)) return parseOneOf(schema, refs);
517
+ else if (its.a.not(schema)) return parseNot(schema, refs);
518
+ else if (its.an.enum(schema)) return parseEnum(schema);
519
+ else if (its.a.const(schema)) return parseConst(schema);
520
+ else if (its.a.multipleType(schema)) return parseMultipleType(schema, refs);
521
+ else if (its.a.primitive(schema, "string")) return parseString(schema);
522
+ else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) return parseNumber(schema);
523
+ else if (its.a.primitive(schema, "boolean")) return parseBoolean(schema);
524
+ else if (its.a.primitive(schema, "null")) return parseNull(schema);
525
+ else if (its.a.conditional(schema)) return parseIfThenElse(schema, refs);
526
+ else return parseDefault(schema);
527
+ };
528
+ const parseSchema = (jsonSchema, refs = {
529
+ seen: /* @__PURE__ */ new Map(),
530
+ path: []
531
+ }, blockMeta) => {
532
+ if (typeof jsonSchema !== "object") return jsonSchema ? z$1.any() : z$1.never();
533
+ if (refs.parserOverride) {
534
+ const custom = refs.parserOverride(jsonSchema, refs);
535
+ if (custom instanceof z$1.ZodType) return custom;
536
+ }
537
+ let seen = refs.seen.get(jsonSchema);
538
+ if (seen) {
539
+ if (seen.r !== void 0) return seen.r;
540
+ if (refs.depth === void 0 || seen.n >= refs.depth) return z$1.any();
541
+ seen.n += 1;
542
+ } else {
543
+ seen = {
544
+ r: void 0,
545
+ n: 0
546
+ };
547
+ refs.seen.set(jsonSchema, seen);
548
+ }
549
+ let parsedZodSchema = selectParser(jsonSchema, refs);
550
+ if (!blockMeta) {
551
+ if (!refs.withoutDescribes) parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
552
+ if (!refs.withoutDefaults) parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, refs);
553
+ parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
554
+ }
555
+ seen.r = parsedZodSchema;
556
+ return parsedZodSchema;
557
+ };
558
+
559
+ //#endregion
560
+ //#region src/parsers/parse-object-shape.ts
561
+ /**
562
+ * Parses a JSON Schema object and returns the raw shape (property keys mapped to Zod types).
563
+ * This is useful when you need ZodRawShape instead of a complete ZodObject.
564
+ *
565
+ * @param objectSchema - The JSON Schema object to parse
566
+ * @param refs - Parser references for handling nested schemas
567
+ * @returns A Zod raw shape object
568
+ */
569
+ function parseObjectShape(objectSchema, refs) {
570
+ if (!objectSchema.properties) return {};
571
+ const propertyKeys = Object.keys(objectSchema.properties);
572
+ if (propertyKeys.length === 0) return {};
573
+ const properties = {};
574
+ for (const key of propertyKeys) {
575
+ const propJsonSchema = objectSchema.properties[key];
576
+ const propZodSchema = parseSchema(propJsonSchema, {
577
+ ...refs,
578
+ path: [
579
+ ...refs.path,
580
+ "properties",
581
+ key
582
+ ]
583
+ });
584
+ const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
585
+ if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) if (propJsonSchema.default === null) {
586
+ const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
587
+ const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
588
+ const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
589
+ if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) properties[key] = propZodSchema.optional().default(null);
590
+ else properties[key] = propZodSchema.nullable().optional().default(null);
591
+ } else properties[key] = propZodSchema.optional().default(propJsonSchema.default);
592
+ else properties[key] = required ? propZodSchema : propZodSchema.optional();
593
+ }
594
+ return properties;
595
+ }
596
+
597
+ //#endregion
598
+ //#region src/json-schema-to-zod.ts
599
+ const jsonSchemaToZod = (schema, options = {}) => {
600
+ return parseSchema(schema, {
601
+ path: [],
602
+ seen: /* @__PURE__ */ new Map(),
603
+ ...options
604
+ });
605
+ };
606
+ /**
607
+ * Converts a JSON Schema object to a Zod raw shape.
608
+ * This is useful when you need the shape object (e.g., `{ name: z.string(), age: z.number() }`)
609
+ * rather than a complete ZodObject schema.
610
+ *
611
+ * This is particularly useful for APIs that expect ZodRawShape instead of ZodType,
612
+ * such as the Claude Agent SDK's `tool()` function.
613
+ *
614
+ * @param schema - The JSON Schema to convert (must be an object schema)
615
+ * @param options - Optional configuration for the conversion
616
+ * @returns A Zod raw shape object with property keys mapped to Zod types
617
+ */
618
+ const jsonSchemaToZodShape = (schema, options = {}) => {
619
+ if (typeof schema !== "object" || schema === null) return {};
620
+ return parseObjectShape(schema, {
621
+ path: [],
622
+ seen: /* @__PURE__ */ new Map(),
623
+ ...options
624
+ });
625
+ };
626
+
627
+ //#endregion
628
+ export { jsonSchemaToZod, jsonSchemaToZodShape };
package/package.json CHANGED
@@ -1,17 +1,25 @@
1
1
  {
2
2
  "name": "@composio/json-schema-to-zod",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "description": "",
5
- "main": "dist/index.js",
6
- "type": "module",
5
+ "main": "dist/index.mjs",
7
6
  "publishConfig": {
8
7
  "access": "public"
9
8
  },
10
9
  "exports": {
11
10
  ".": {
12
- "import": "./dist/index.js",
13
- "types": "./dist/index.d.ts",
14
- "require": "./dist/index.cjs"
11
+ "import": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ },
19
+ "default": {
20
+ "types": "./dist/index.d.cts",
21
+ "default": "./dist/index.cjs"
22
+ }
15
23
  }
16
24
  },
17
25
  "files": [
@@ -24,21 +32,21 @@
24
32
  "devDependencies": {
25
33
  "@types/json-schema": "^7.0.15",
26
34
  "@types/node": "^24.0.1",
27
- "tsup": "^8.5.0",
35
+ "tsdown": "^0.18.4",
28
36
  "typescript": "^5.9.2",
29
37
  "vitest": "^3.2.4",
30
38
  "zod": "^4.1.0"
31
39
  },
32
40
  "peerDependencies": {
33
- "zod": ">=3.25.76 <4 || >=4.1 <5"
41
+ "zod": ">=3.25.76 <5"
34
42
  },
35
43
  "scripts": {
36
44
  "clean": "git clean -xdf node_modules",
37
- "build": "tsup",
45
+ "build": "bun run --bun tsdown",
38
46
  "test": "vitest run",
39
47
  "typecheck:src": "tsc --noEmit -p ./tsconfig.src.json",
40
48
  "typecheck:test": "tsc --noEmit -p ./tsconfig.test.json",
41
49
  "typecheck": "pnpm run typecheck:src && pnpm run typecheck:test"
42
50
  },
43
- "types": "dist/index.d.ts"
51
+ "types": "dist/index.d.mts"
44
52
  }