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

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