@composio/json-schema-to-zod 0.3.3 → 0.4.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/README.md +31 -3
- package/dist/compile-pattern-blQMRxo5.d.mts +214 -0
- package/dist/convert-CqEY5vMX.mjs +1801 -0
- package/dist/index.d.mts +4 -206
- package/dist/index.mjs +121 -965
- package/dist/v4.d.mts +16 -0
- package/dist/v4.mjs +249 -0
- package/package.json +17 -7
package/dist/index.mjs
CHANGED
|
@@ -1,973 +1,138 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import { dequal } from "dequal/lite";
|
|
4
|
-
import { Validator, encodePointer } from "@cfworker/json-schema";
|
|
1
|
+
import { a as composeGuards, i as buildTuple, n as InvalidPatternError, o as run, r as applyObjectPolicy, s as withPath, t as createConverter } from "./convert-CqEY5vMX.mjs";
|
|
2
|
+
import * as z from "zod/v3";
|
|
5
3
|
|
|
6
|
-
//#region src/
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
//#endregion
|
|
33
|
-
//#region src/parsers/parse-all-of.ts
|
|
34
|
-
const originalIndex = Symbol("Original index");
|
|
35
|
-
const ensureOriginalIndex = (arr) => {
|
|
36
|
-
const newArr = [];
|
|
37
|
-
for (let i = 0; i < arr.length; i++) {
|
|
38
|
-
const item = arr[i];
|
|
39
|
-
if (typeof item === "boolean") newArr.push(item ? { [originalIndex]: i } : {
|
|
40
|
-
[originalIndex]: i,
|
|
41
|
-
not: {}
|
|
42
|
-
});
|
|
43
|
-
else if (originalIndex in item) return arr;
|
|
44
|
-
else newArr.push({
|
|
45
|
-
...item,
|
|
46
|
-
[originalIndex]: i
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
return newArr;
|
|
50
|
-
};
|
|
51
|
-
const isClosedObjectBranch = (branch) => typeof branch === "object" && its.an.object(branch) && branch.properties !== void 0 && Object.keys(branch.properties).length > 0 && branch.additionalProperties === void 0 && branch.patternProperties === void 0 && !("$ref" in branch);
|
|
52
|
-
const intersect = (branches, refs) => {
|
|
53
|
-
if (branches.length === 1) {
|
|
54
|
-
const item = branches[0];
|
|
55
|
-
return parseSchema(item, {
|
|
56
|
-
...refs,
|
|
57
|
-
path: [
|
|
58
|
-
...refs.path,
|
|
59
|
-
"allOf",
|
|
60
|
-
item[originalIndex]
|
|
61
|
-
]
|
|
62
|
-
});
|
|
4
|
+
//#region src/backend/zod-v3.ts
|
|
5
|
+
const guardedSchemaClasses = /* @__PURE__ */ new WeakMap();
|
|
6
|
+
/**
|
|
7
|
+
* A subclass of the parsed schema's own class that checks the source value
|
|
8
|
+
* against the guard before parsing it. Keeping the class, rather than wrapping
|
|
9
|
+
* it in a pipeline, keeps the schema's kind: a guarded object is still a
|
|
10
|
+
* `ZodObject` with a `shape`, which is what zod-to-json-schema and the MCP SDK
|
|
11
|
+
* need to emit a root `type: "object"` for LLM tool parameters. The guard lives
|
|
12
|
+
* on `_def`, so copies such as `.describe()` keep it.
|
|
13
|
+
*/
|
|
14
|
+
const guardedSchemaClass = (Base) => {
|
|
15
|
+
const cached = guardedSchemaClasses.get(Base);
|
|
16
|
+
if (cached) return cached;
|
|
17
|
+
const parseAsBase = Base.prototype._parse;
|
|
18
|
+
class Guarded extends Base {
|
|
19
|
+
_parse(input) {
|
|
20
|
+
const failure = this._def.wholeSchemaGuard?.(input.data);
|
|
21
|
+
if (failure === void 0) return parseAsBase.call(this, input);
|
|
22
|
+
z.addIssueToContext(this._getOrReturnCtx(input), {
|
|
23
|
+
code: z.ZodIssueCode.custom,
|
|
24
|
+
message: failure
|
|
25
|
+
});
|
|
26
|
+
return z.DIRTY(input.data);
|
|
27
|
+
}
|
|
63
28
|
}
|
|
64
|
-
|
|
65
|
-
|
|
29
|
+
guardedSchemaClasses.set(Base, Guarded);
|
|
30
|
+
guardedSchemaClasses.set(Guarded, Guarded);
|
|
31
|
+
return Guarded;
|
|
66
32
|
};
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
additionalProperties: true
|
|
73
|
-
} : branch);
|
|
74
|
-
const parsed = intersect(ensureOriginalIndex(opened), refs);
|
|
75
|
-
if (!jsonSchema.allOf.every(isClosedObjectBranch)) return parsed;
|
|
76
|
-
const declaredKeys = new Set(jsonSchema.allOf.flatMap((branch) => Object.keys(branch.properties ?? {})));
|
|
77
|
-
return parsed.superRefine((value, ctx) => {
|
|
78
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return;
|
|
79
|
-
const unrecognizedKeys = Object.keys(value).filter((key) => !declaredKeys.has(key));
|
|
80
|
-
if (unrecognizedKeys.length > 0) ctx.addIssue({
|
|
81
|
-
code: z.ZodIssueCode.unrecognized_keys,
|
|
82
|
-
keys: unrecognizedKeys,
|
|
83
|
-
message: `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`
|
|
84
|
-
});
|
|
33
|
+
const attachGuard = (schema, guard) => {
|
|
34
|
+
const wholeSchemaGuard = composeGuards(guard, schema._def.wholeSchemaGuard);
|
|
35
|
+
return new (guardedSchemaClass(schema.constructor))({
|
|
36
|
+
...schema._def,
|
|
37
|
+
wholeSchemaGuard
|
|
85
38
|
});
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
//#endregion
|
|
89
|
-
//#region src/parsers/parse-any-of.ts
|
|
90
|
-
const parseAnyOf = (jsonSchema, refs) => {
|
|
91
|
-
return jsonSchema.anyOf.length ? jsonSchema.anyOf.length === 1 ? parseSchema(jsonSchema.anyOf[0], {
|
|
92
|
-
...refs,
|
|
93
|
-
path: [
|
|
94
|
-
...refs.path,
|
|
95
|
-
"anyOf",
|
|
96
|
-
0
|
|
97
|
-
]
|
|
98
|
-
}) : z.union(jsonSchema.anyOf.map((schema, i) => parseSchema(schema, {
|
|
99
|
-
...refs,
|
|
100
|
-
path: [
|
|
101
|
-
...refs.path,
|
|
102
|
-
"anyOf",
|
|
103
|
-
i
|
|
104
|
-
]
|
|
105
|
-
}))) : z.any();
|
|
106
39
|
};
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
return zodSchema;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
//#endregion
|
|
120
|
-
//#region src/parsers/parse-array.ts
|
|
121
|
-
const parseArray = (jsonSchema, refs) => {
|
|
122
|
-
if (its.an.anyOf(jsonSchema)) {
|
|
123
|
-
const types = /* @__PURE__ */ new Set();
|
|
124
|
-
const itemsSchemas = [];
|
|
125
|
-
jsonSchema.anyOf.forEach((option) => {
|
|
126
|
-
if (typeof option === "object" && option.type) types.add(typeof option.type === "string" ? option.type : option.type[0]);
|
|
127
|
-
if (typeof option === "object" && option.items) {
|
|
128
|
-
const optionItems = option.items;
|
|
129
|
-
if (!Array.isArray(optionItems) && typeof optionItems === "object") itemsSchemas.push(optionItems);
|
|
130
|
-
}
|
|
40
|
+
/** Issues raised through the refinement context; Zod prefixes the context path itself. */
|
|
41
|
+
const sink = (ctx) => ({
|
|
42
|
+
custom(message, options) {
|
|
43
|
+
ctx.addIssue({
|
|
44
|
+
...withPath(options?.path),
|
|
45
|
+
code: z.ZodIssueCode.custom,
|
|
46
|
+
message,
|
|
47
|
+
...options?.params === void 0 ? {} : { params: options.params }
|
|
131
48
|
});
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
[
|
|
140
|
-
"default",
|
|
141
|
-
"description",
|
|
142
|
-
"examples",
|
|
143
|
-
"title"
|
|
144
|
-
].forEach((field) => {
|
|
145
|
-
const value = jsonSchema[field];
|
|
146
|
-
if (value !== void 0) newSchema[field] = value;
|
|
49
|
+
},
|
|
50
|
+
unrecognizedKeys(keys, message, options) {
|
|
51
|
+
ctx.addIssue({
|
|
52
|
+
...withPath(options?.path),
|
|
53
|
+
code: z.ZodIssueCode.unrecognized_keys,
|
|
54
|
+
keys: [...keys],
|
|
55
|
+
message
|
|
147
56
|
});
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
"items",
|
|
156
|
-
index
|
|
157
|
-
]
|
|
158
|
-
}));
|
|
159
|
-
const prefixSchemas = parsedItems.map((_, length) => z.tuple(parsedItems.slice(0, length)));
|
|
160
|
-
const fullTuple = z.tuple(parsedItems);
|
|
161
|
-
let fullLengthSchema;
|
|
162
|
-
if (jsonSchema.additionalItems === false) fullLengthSchema = fullTuple;
|
|
163
|
-
else if (jsonSchema.additionalItems && jsonSchema.additionalItems !== true) fullLengthSchema = fullTuple.rest(parseSchema(jsonSchema.additionalItems, {
|
|
164
|
-
...refs,
|
|
165
|
-
path: [...refs.path, "additionalItems"]
|
|
166
|
-
}));
|
|
167
|
-
else fullLengthSchema = fullTuple.rest(z.any());
|
|
168
|
-
const variants = [...prefixSchemas, fullLengthSchema];
|
|
169
|
-
let tupleSchema = variants.length === 1 ? variants[0] : z.union(variants);
|
|
170
|
-
if (typeof jsonSchema.minItems === "number") tupleSchema = tupleSchema.refine((value) => value.length >= jsonSchema.minItems, { message: `Array must contain at least ${jsonSchema.minItems} element(s)` });
|
|
171
|
-
if (typeof jsonSchema.maxItems === "number") tupleSchema = tupleSchema.refine((value) => value.length <= jsonSchema.maxItems, { message: `Array must contain at most ${jsonSchema.maxItems} element(s)` });
|
|
172
|
-
return tupleSchema;
|
|
173
|
-
}
|
|
174
|
-
let zodSchema = !jsonSchema.items ? z.array(z.any()) : z.array(parseSchema(jsonSchema.items, {
|
|
175
|
-
...refs,
|
|
176
|
-
path: [...refs.path, "items"]
|
|
177
|
-
}));
|
|
178
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
|
|
179
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
|
|
180
|
-
if (typeof jsonSchema.min === "number" && typeof jsonSchema.minItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
181
|
-
...jsonSchema,
|
|
182
|
-
minItems: jsonSchema.min
|
|
183
|
-
}, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
|
|
184
|
-
if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
185
|
-
...jsonSchema,
|
|
186
|
-
maxItems: jsonSchema.max
|
|
187
|
-
}, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
|
|
188
|
-
return zodSchema;
|
|
189
|
-
};
|
|
190
|
-
|
|
191
|
-
//#endregion
|
|
192
|
-
//#region src/parsers/parse-boolean.ts
|
|
193
|
-
const parseBoolean = (_jsonSchema) => {
|
|
194
|
-
return z.boolean();
|
|
195
|
-
};
|
|
196
|
-
|
|
197
|
-
//#endregion
|
|
198
|
-
//#region src/parsers/parse-literal-values.ts
|
|
199
|
-
const parseLiteralValues = (values) => {
|
|
200
|
-
if (values.length === 0) return z.never();
|
|
201
|
-
if (values.every((value) => value === null || typeof value !== "object")) {
|
|
202
|
-
if (values.length === 1) return z.literal(values[0]);
|
|
203
|
-
if (values.every((value) => typeof value === "string")) return z.enum(values);
|
|
204
|
-
return z.union(values.map((value) => z.literal(value)));
|
|
205
|
-
}
|
|
206
|
-
return z.custom((value) => values.some((candidate) => dequal(value, candidate)));
|
|
207
|
-
};
|
|
208
|
-
|
|
209
|
-
//#endregion
|
|
210
|
-
//#region src/parsers/parse-const.ts
|
|
211
|
-
const parseConst = (jsonSchema, refs) => {
|
|
212
|
-
const { const: value, ...baseSchema } = jsonSchema;
|
|
213
|
-
return parseSchema(baseSchema, {
|
|
214
|
-
...refs,
|
|
215
|
-
seen: new Map(refs.seen)
|
|
216
|
-
}, true).and(parseLiteralValues([value]));
|
|
217
|
-
};
|
|
218
|
-
|
|
219
|
-
//#endregion
|
|
220
|
-
//#region src/parsers/parse-default.ts
|
|
221
|
-
const parseDefault = (_jsonSchema) => {
|
|
222
|
-
return z.any();
|
|
223
|
-
};
|
|
224
|
-
|
|
225
|
-
//#endregion
|
|
226
|
-
//#region src/parsers/parse-enum.ts
|
|
227
|
-
const parseEnum = (jsonSchema, refs) => {
|
|
228
|
-
const { enum: values, ...baseSchema } = jsonSchema;
|
|
229
|
-
return parseSchema(baseSchema, {
|
|
230
|
-
...refs,
|
|
231
|
-
seen: new Map(refs.seen)
|
|
232
|
-
}, true).and(parseLiteralValues(values));
|
|
233
|
-
};
|
|
234
|
-
|
|
235
|
-
//#endregion
|
|
236
|
-
//#region src/parsers/parse-if-then-else.ts
|
|
237
|
-
const parseIfThenElse = (jsonSchema, refs) => {
|
|
238
|
-
const $if = parseSchema(jsonSchema.if, {
|
|
239
|
-
...refs,
|
|
240
|
-
path: [...refs.path, "if"]
|
|
241
|
-
});
|
|
242
|
-
const $then = parseSchema(jsonSchema.then, {
|
|
243
|
-
...refs,
|
|
244
|
-
path: [...refs.path, "then"]
|
|
245
|
-
});
|
|
246
|
-
const $else = parseSchema(jsonSchema.else, {
|
|
247
|
-
...refs,
|
|
248
|
-
path: [...refs.path, "else"]
|
|
249
|
-
});
|
|
250
|
-
return z.union([$then, $else]).superRefine((value, ctx) => {
|
|
251
|
-
const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
|
|
252
|
-
if (!result.success) result.error.errors.forEach((error) => ctx.addIssue(error));
|
|
253
|
-
});
|
|
254
|
-
};
|
|
255
|
-
|
|
256
|
-
//#endregion
|
|
257
|
-
//#region src/parsers/parse-multiple-type.ts
|
|
258
|
-
const parseMultipleType = (jsonSchema, refs) => {
|
|
259
|
-
return z.union(jsonSchema.type.map((type) => parseSchema({
|
|
260
|
-
...jsonSchema,
|
|
261
|
-
type
|
|
262
|
-
}, refs)));
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
//#endregion
|
|
266
|
-
//#region src/parsers/parse-not.ts
|
|
267
|
-
const parseNot = (jsonSchema, refs) => {
|
|
268
|
-
return z.any().refine((value) => !parseSchema(jsonSchema.not, {
|
|
269
|
-
...refs,
|
|
270
|
-
path: [...refs.path, "not"]
|
|
271
|
-
}).safeParse(value).success, "Invalid input: Should NOT be valid against schema");
|
|
272
|
-
};
|
|
273
|
-
|
|
274
|
-
//#endregion
|
|
275
|
-
//#region src/parsers/parse-null.ts
|
|
276
|
-
const parseNull = (_jsonSchema) => {
|
|
277
|
-
return z.null();
|
|
278
|
-
};
|
|
279
|
-
|
|
280
|
-
//#endregion
|
|
281
|
-
//#region src/utils/omit.ts
|
|
282
|
-
const omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
|
|
283
|
-
if (!keys.includes(key)) acc[key] = obj[key];
|
|
284
|
-
return acc;
|
|
285
|
-
}, {});
|
|
286
|
-
|
|
287
|
-
//#endregion
|
|
288
|
-
//#region src/parsers/parse-nullable.ts
|
|
289
|
-
/**
|
|
290
|
-
* For compatibility with open api 3.0 nullable
|
|
291
|
-
*/
|
|
292
|
-
const parseNullable = (jsonSchema, refs) => {
|
|
293
|
-
const hasNullDefault = jsonSchema.default === null;
|
|
294
|
-
const baseSchema = hasNullDefault ? omit(omit(jsonSchema, "nullable"), "default") : omit(jsonSchema, "nullable");
|
|
295
|
-
const zodSchema = parseSchema(baseSchema, refs, true).nullable();
|
|
296
|
-
return hasNullDefault ? zodSchema.default(null) : zodSchema;
|
|
297
|
-
};
|
|
298
|
-
|
|
299
|
-
//#endregion
|
|
300
|
-
//#region src/parsers/parse-number.ts
|
|
301
|
-
const toDecimalInteger = (value) => {
|
|
302
|
-
if (!Number.isFinite(value)) return void 0;
|
|
303
|
-
const negative = value < 0;
|
|
304
|
-
const [coefficient, exponentText] = Math.abs(value).toString().toLowerCase().split("e");
|
|
305
|
-
const exponent = exponentText === void 0 ? 0 : Number(exponentText);
|
|
306
|
-
const [whole, fraction = ""] = coefficient.split(".");
|
|
307
|
-
let digits = `${whole}${fraction}`.replace(/^0+(?=\d)/, "");
|
|
308
|
-
let scale = fraction.length - exponent;
|
|
309
|
-
if (scale < 0) {
|
|
310
|
-
digits += "0".repeat(-scale);
|
|
311
|
-
scale = 0;
|
|
312
|
-
}
|
|
313
|
-
return {
|
|
314
|
-
integer: BigInt(`${negative ? "-" : ""}${digits}`),
|
|
315
|
-
scale
|
|
316
|
-
};
|
|
317
|
-
};
|
|
318
|
-
const isJsonMultipleOf = (value, multiple) => {
|
|
319
|
-
const dividend = toDecimalInteger(value);
|
|
320
|
-
const divisor = toDecimalInteger(multiple);
|
|
321
|
-
if (!dividend || !divisor || divisor.integer === 0n) return false;
|
|
322
|
-
const scale = Math.max(dividend.scale, divisor.scale);
|
|
323
|
-
return dividend.integer * 10n ** BigInt(scale - dividend.scale) % (divisor.integer * 10n ** BigInt(scale - divisor.scale)) === 0n;
|
|
324
|
-
};
|
|
325
|
-
const parseNumber = (jsonSchema) => {
|
|
326
|
-
let zodSchema = z.number();
|
|
327
|
-
let isInteger = false;
|
|
328
|
-
if (jsonSchema.type === "integer") {
|
|
329
|
-
isInteger = true;
|
|
330
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "type", (zs, _, errorMsg) => zs.int(errorMsg));
|
|
331
|
-
} else if (jsonSchema.format === "int64") {
|
|
332
|
-
isInteger = true;
|
|
333
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, _, errorMsg) => zs.int(errorMsg));
|
|
334
|
-
}
|
|
335
|
-
if (typeof jsonSchema.minimum === "number") {
|
|
336
|
-
if (jsonSchema.exclusiveMinimum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg));
|
|
337
|
-
else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
|
|
338
|
-
}
|
|
339
|
-
if (typeof jsonSchema.exclusiveMinimum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMinimum", (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum, errorMsg));
|
|
340
|
-
if (typeof jsonSchema.maximum === "number") {
|
|
341
|
-
if (jsonSchema.exclusiveMaximum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg));
|
|
342
|
-
else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
343
|
-
}
|
|
344
|
-
if (typeof jsonSchema.exclusiveMaximum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMaximum", (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum, errorMsg));
|
|
345
|
-
if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
346
|
-
...jsonSchema,
|
|
347
|
-
minimum: jsonSchema.min
|
|
348
|
-
}, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
|
|
349
|
-
if (typeof jsonSchema.max === "number" && typeof jsonSchema.maximum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
350
|
-
...jsonSchema,
|
|
351
|
-
maximum: jsonSchema.max
|
|
352
|
-
}, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
353
|
-
if (typeof jsonSchema.multipleOf === "number") {
|
|
354
|
-
const errorMessage = jsonSchema.errorMessage?.multipleOf;
|
|
355
|
-
if (jsonSchema.multipleOf === 1) return isInteger ? zodSchema : zodSchema.int(errorMessage);
|
|
356
|
-
return zodSchema.refine((value) => isJsonMultipleOf(value, jsonSchema.multipleOf), { message: errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}` });
|
|
357
|
-
}
|
|
358
|
-
return zodSchema;
|
|
359
|
-
};
|
|
360
|
-
|
|
361
|
-
//#endregion
|
|
362
|
-
//#region src/parsers/parse-one-of.ts
|
|
363
|
-
const parseOneOf = (jsonSchema, refs) => {
|
|
364
|
-
if (!jsonSchema.oneOf.length) return z.any();
|
|
365
|
-
if (jsonSchema.oneOf.length === 1) return parseSchema(jsonSchema.oneOf[0], {
|
|
366
|
-
...refs,
|
|
367
|
-
path: [
|
|
368
|
-
...refs.path,
|
|
369
|
-
"oneOf",
|
|
370
|
-
0
|
|
371
|
-
]
|
|
372
|
-
});
|
|
373
|
-
return z.any().superRefine((x, ctx) => {
|
|
374
|
-
const schemas = jsonSchema.oneOf.map((schema, i) => parseSchema(schema, {
|
|
375
|
-
...refs,
|
|
376
|
-
path: [
|
|
377
|
-
...refs.path,
|
|
378
|
-
"oneOf",
|
|
379
|
-
i
|
|
380
|
-
]
|
|
381
|
-
}));
|
|
382
|
-
const unionErrors = schemas.reduce((errors, schema) => ((result) => result.error ? [...errors, result.error] : errors)(schema.safeParse(x)), []);
|
|
383
|
-
if (schemas.length - unionErrors.length !== 1) ctx.addIssue({
|
|
384
|
-
path: ctx.path,
|
|
385
|
-
code: "invalid_union",
|
|
386
|
-
unionErrors,
|
|
387
|
-
message: "Invalid input: Should pass single schema"
|
|
57
|
+
},
|
|
58
|
+
invalidUnion(message, failures, options) {
|
|
59
|
+
ctx.addIssue({
|
|
60
|
+
...withPath(options?.path),
|
|
61
|
+
code: z.ZodIssueCode.invalid_union,
|
|
62
|
+
unionErrors: failures,
|
|
63
|
+
message
|
|
388
64
|
});
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
* Raised at conversion time when a schema `pattern` cannot be turned into a
|
|
403
|
-
* `RegExp`. Conversion fails eagerly, in line with how this package and
|
|
404
|
-
* `@composio/json-schema-to-effect-schema` treat other schema defects: a broken
|
|
405
|
-
* schema is the tool author's bug, so it surfaces once at construction rather
|
|
406
|
-
* than on every validation as if the caller's input were wrong.
|
|
407
|
-
*/
|
|
408
|
-
var InvalidPatternError = class extends Error {
|
|
409
|
-
keyword;
|
|
410
|
-
pattern;
|
|
411
|
-
path;
|
|
412
|
-
reason;
|
|
413
|
-
name = "InvalidPatternError";
|
|
414
|
-
constructor(keyword, pattern, path, reason, detail, options) {
|
|
415
|
-
const location = path.length > 0 ? path.join(".") : "<root>";
|
|
416
|
-
super(`Invalid ${keyword} regular expression ${JSON.stringify(pattern)} at ${location}: ${detail}`, options);
|
|
417
|
-
this.keyword = keyword;
|
|
418
|
-
this.pattern = pattern;
|
|
419
|
-
this.path = path;
|
|
420
|
-
this.reason = reason;
|
|
421
|
-
}
|
|
422
|
-
};
|
|
423
|
-
/**
|
|
424
|
-
* Compile a schema pattern, rejecting anything that does not compile or that
|
|
425
|
-
* exceeds {@link MAX_PATTERN_LENGTH}.
|
|
426
|
-
*
|
|
427
|
-
* Both guards have no false positives: a pattern that fails here would never
|
|
428
|
-
* have worked. No backtracking (ReDoS) heuristic is applied on purpose — the
|
|
429
|
-
* syntactic checks that exist flag linear patterns such as `^(\d+\.)*\d+$`,
|
|
430
|
-
* and a wrong rejection fails the whole tool the schema belongs to. A hostile
|
|
431
|
-
* `pattern` that backtracks catastrophically remains a known limitation.
|
|
432
|
-
*
|
|
433
|
-
* No `u` flag is passed: existing tool schemas rely on identity escapes that
|
|
434
|
-
* Unicode mode refuses, and the goal here is to fail on defects, not to
|
|
435
|
-
* tighten which patterns are accepted.
|
|
436
|
-
*/
|
|
437
|
-
const compilePattern = (keyword, pattern, refs) => {
|
|
438
|
-
const path = keyword === "pattern" ? refs.path : [
|
|
439
|
-
...refs.path,
|
|
440
|
-
"patternProperties",
|
|
441
|
-
pattern
|
|
442
|
-
];
|
|
443
|
-
if (pattern.length > 1024) throw new InvalidPatternError(keyword, pattern, path, "too-long", `pattern exceeds ${MAX_PATTERN_LENGTH} characters`);
|
|
444
|
-
try {
|
|
445
|
-
return new RegExp(pattern);
|
|
446
|
-
} catch (cause) {
|
|
447
|
-
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
448
|
-
throw new InvalidPatternError(keyword, pattern, path, "syntax", detail, { cause });
|
|
449
|
-
}
|
|
450
|
-
};
|
|
451
|
-
|
|
452
|
-
//#endregion
|
|
453
|
-
//#region src/parsers/parse-object.ts
|
|
454
|
-
/**
|
|
455
|
-
* Build the static part of an object parser, or `undefined` when the schema
|
|
456
|
-
* declares no named properties.
|
|
457
|
-
*
|
|
458
|
-
* A property-less object (`properties` absent or `{}`) deliberately returns
|
|
459
|
-
* `undefined` so the caller can apply the open-object policy. This supersedes
|
|
460
|
-
* an earlier `z.object({})` fallback that was kept "or else this will break
|
|
461
|
-
* openai responses": collapsing `{ type: "object" }` to a strict empty object
|
|
462
|
-
* is the defect it was masking, and the OpenAI provider suite is part of this
|
|
463
|
-
* package's verification precisely so the claim stays checked.
|
|
464
|
-
*/
|
|
465
|
-
function parseObjectProperties(objectSchema, refs) {
|
|
466
|
-
if (!objectSchema.properties) return;
|
|
467
|
-
const propertyKeys = Object.keys(objectSchema.properties);
|
|
468
|
-
if (propertyKeys.length === 0) return;
|
|
469
|
-
const properties = {};
|
|
470
|
-
for (const key of propertyKeys) {
|
|
471
|
-
const propJsonSchema = objectSchema.properties[key];
|
|
472
|
-
const propZodSchema = parseSchema(propJsonSchema, {
|
|
473
|
-
...refs,
|
|
474
|
-
path: [
|
|
475
|
-
...refs.path,
|
|
476
|
-
"properties",
|
|
477
|
-
key
|
|
478
|
-
]
|
|
65
|
+
},
|
|
66
|
+
forward(failure) {
|
|
67
|
+
for (const issue of failure.issues) ctx.addIssue(issue);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
const stringFormat = (schema, format, message) => {
|
|
71
|
+
const string = schema;
|
|
72
|
+
switch (format) {
|
|
73
|
+
case "email": return string.email(message);
|
|
74
|
+
case "ip": return string.ip(message);
|
|
75
|
+
case "ipv4": return string.ip({
|
|
76
|
+
version: "v4",
|
|
77
|
+
message
|
|
479
78
|
});
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
484
|
-
const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
485
|
-
const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
|
|
486
|
-
if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) properties[key] = propZodSchema.optional().default(null);
|
|
487
|
-
else properties[key] = propZodSchema.nullable().optional().default(null);
|
|
488
|
-
} else properties[key] = propZodSchema.optional().default(propJsonSchema.default);
|
|
489
|
-
} else properties[key] = required ? propZodSchema : propZodSchema.optional();
|
|
490
|
-
}
|
|
491
|
-
return z$1.object(properties);
|
|
492
|
-
}
|
|
493
|
-
/**
|
|
494
|
-
* Object parser for schemas carrying `patternProperties`.
|
|
495
|
-
*
|
|
496
|
-
* Every key is routed to exactly the schemas that apply to it — each matching
|
|
497
|
-
* pattern, and `additionalProperties` only when no pattern and no named
|
|
498
|
-
* property claims the key. A catch-all union would instead let a key sneak past
|
|
499
|
-
* its own pattern by satisfying an unrelated one.
|
|
500
|
-
*/
|
|
501
|
-
function parseDynamicKeyObject(normalizedSchema, propertiesSchema, additionalProperties, refs) {
|
|
502
|
-
const patterns = Object.entries(normalizedSchema.patternProperties ?? {}).map(([pattern, schema]) => ({
|
|
503
|
-
regex: compilePattern("patternProperties", pattern, refs),
|
|
504
|
-
parser: parseSchema(schema, {
|
|
505
|
-
...refs,
|
|
506
|
-
path: [
|
|
507
|
-
...refs.path,
|
|
508
|
-
"patternProperties",
|
|
509
|
-
pattern
|
|
510
|
-
]
|
|
511
|
-
})
|
|
512
|
-
}));
|
|
513
|
-
const declaredKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
|
|
514
|
-
const rejectsUnmatched = additionalProperties instanceof z$1.ZodNever || additionalProperties === void 0 && declaredKeys.size > 0;
|
|
515
|
-
const validatesUnmatched = additionalProperties !== void 0 && !(additionalProperties instanceof z$1.ZodNever) && normalizedSchema.additionalProperties !== true;
|
|
516
|
-
return (propertiesSchema ?? z$1.object({})).passthrough().transform((value, ctx) => {
|
|
517
|
-
const result = { ...value };
|
|
518
|
-
const unrecognizedKeys = [];
|
|
519
|
-
for (const key of Object.keys(value)) {
|
|
520
|
-
const matching = patterns.filter(({ regex }) => regex.test(key));
|
|
521
|
-
for (const { parser } of matching) {
|
|
522
|
-
const parsed = parser.safeParse(value[key]);
|
|
523
|
-
if (!parsed.success) ctx.addIssue({
|
|
524
|
-
path: [...ctx.path, key],
|
|
525
|
-
code: "custom",
|
|
526
|
-
message: `Invalid input: key "${key}" must match its patternProperties schema`,
|
|
527
|
-
params: { issues: parsed.error.issues }
|
|
528
|
-
});
|
|
529
|
-
else if (!declaredKeys.has(key)) result[key] = parsed.data;
|
|
530
|
-
}
|
|
531
|
-
if (matching.length > 0 || declaredKeys.has(key)) continue;
|
|
532
|
-
if (rejectsUnmatched) unrecognizedKeys.push(key);
|
|
533
|
-
else if (validatesUnmatched) {
|
|
534
|
-
const parsed = additionalProperties.safeParse(value[key]);
|
|
535
|
-
if (!parsed.success) ctx.addIssue({
|
|
536
|
-
path: [...ctx.path, key],
|
|
537
|
-
code: "custom",
|
|
538
|
-
message: `Invalid input: key "${key}" must match the additionalProperties schema`,
|
|
539
|
-
params: { issues: parsed.error.issues }
|
|
540
|
-
});
|
|
541
|
-
else result[key] = parsed.data;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
if (unrecognizedKeys.length > 0) ctx.addIssue({
|
|
545
|
-
path: [...ctx.path],
|
|
546
|
-
code: "unrecognized_keys",
|
|
547
|
-
keys: unrecognizedKeys,
|
|
548
|
-
message: `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`
|
|
79
|
+
case "ipv6": return string.ip({
|
|
80
|
+
version: "v6",
|
|
81
|
+
message
|
|
549
82
|
});
|
|
550
|
-
return
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
const normalizedSchema = objectSchema.type === "object" ? objectSchema : {
|
|
556
|
-
...objectSchema,
|
|
557
|
-
type: "object"
|
|
558
|
-
};
|
|
559
|
-
const propertiesSchema = parseObjectProperties(normalizedSchema, refs);
|
|
560
|
-
const additionalProperties = normalizedSchema.additionalProperties !== void 0 ? parseSchema(normalizedSchema.additionalProperties, {
|
|
561
|
-
...refs,
|
|
562
|
-
path: [...refs.path, "additionalProperties"]
|
|
563
|
-
}) : void 0;
|
|
564
|
-
const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
|
|
565
|
-
let output;
|
|
566
|
-
if (hasPatternProperties) output = parseDynamicKeyObject(normalizedSchema, propertiesSchema, additionalProperties, refs);
|
|
567
|
-
else if (propertiesSchema) {
|
|
568
|
-
if (additionalProperties) {
|
|
569
|
-
if (additionalProperties instanceof z$1.ZodNever) output = propertiesSchema.strict();
|
|
570
|
-
else if (isAdditionalPropertiesTrue) output = propertiesSchema.passthrough();
|
|
571
|
-
else output = propertiesSchema.catchall(additionalProperties);
|
|
572
|
-
} else output = propertiesSchema.strict();
|
|
573
|
-
} else if (additionalProperties) {
|
|
574
|
-
if (additionalProperties instanceof z$1.ZodNever) output = z$1.object({}).strict();
|
|
575
|
-
else if (isAdditionalPropertiesTrue) output = z$1.object({}).passthrough();
|
|
576
|
-
else output = z$1.record(additionalProperties);
|
|
577
|
-
} else output = z$1.object({}).passthrough();
|
|
578
|
-
if (its.an.anyOf(objectSchema)) output = output.and(parseAnyOf({
|
|
579
|
-
...objectSchema,
|
|
580
|
-
anyOf: objectSchema.anyOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
581
|
-
...x,
|
|
582
|
-
type: "object"
|
|
583
|
-
} : x)
|
|
584
|
-
}, refs));
|
|
585
|
-
if (its.a.oneOf(objectSchema)) output = output.and(parseOneOf({
|
|
586
|
-
...objectSchema,
|
|
587
|
-
oneOf: objectSchema.oneOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
588
|
-
...x,
|
|
589
|
-
type: "object"
|
|
590
|
-
} : x)
|
|
591
|
-
}, refs));
|
|
592
|
-
if (its.an.allOf(objectSchema)) output = output.and(parseAllOf({
|
|
593
|
-
...objectSchema,
|
|
594
|
-
allOf: objectSchema.allOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
595
|
-
...x,
|
|
596
|
-
type: "object"
|
|
597
|
-
} : x)
|
|
598
|
-
}, refs));
|
|
599
|
-
return output;
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
//#endregion
|
|
603
|
-
//#region src/parsers/parse-string.ts
|
|
604
|
-
const parseString = (jsonSchema, refs) => {
|
|
605
|
-
let zodSchema = z.string();
|
|
606
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, format, errorMsg) => {
|
|
607
|
-
switch (format) {
|
|
608
|
-
case "email": return zs.email(errorMsg);
|
|
609
|
-
case "ip": return zs.ip(errorMsg);
|
|
610
|
-
case "ipv4": return zs.ip({
|
|
611
|
-
version: "v4",
|
|
612
|
-
message: errorMsg
|
|
613
|
-
});
|
|
614
|
-
case "ipv6": return zs.ip({
|
|
615
|
-
version: "v6",
|
|
616
|
-
message: errorMsg
|
|
617
|
-
});
|
|
618
|
-
case "uri": return zs.url(errorMsg);
|
|
619
|
-
case "uuid": return zs.uuid(errorMsg);
|
|
620
|
-
case "date-time": return zs.datetime({
|
|
621
|
-
offset: true,
|
|
622
|
-
message: errorMsg
|
|
623
|
-
});
|
|
624
|
-
case "time": return zs.time(errorMsg);
|
|
625
|
-
case "date": return zs.date(errorMsg);
|
|
626
|
-
case "binary": return zs.base64(errorMsg);
|
|
627
|
-
case "duration": return zs.duration(errorMsg);
|
|
628
|
-
default: return zs;
|
|
629
|
-
}
|
|
630
|
-
});
|
|
631
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "contentEncoding", (zs, _, errorMsg) => zs.base64(errorMsg));
|
|
632
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "pattern", (zs, pattern, errorMsg) => zs.regex(compilePattern("pattern", pattern, refs), errorMsg));
|
|
633
|
-
const errorMessages = jsonSchema.errorMessage;
|
|
634
|
-
const minLength = typeof jsonSchema.minLength === "number" ? jsonSchema.minLength : typeof jsonSchema.min === "number" ? jsonSchema.min : void 0;
|
|
635
|
-
const maxLength = typeof jsonSchema.maxLength === "number" ? jsonSchema.maxLength : typeof jsonSchema.max === "number" ? jsonSchema.max : void 0;
|
|
636
|
-
let result = zodSchema;
|
|
637
|
-
if (minLength !== void 0) result = result.refine((value) => codePointLength(value) >= minLength, { message: errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)` });
|
|
638
|
-
if (maxLength !== void 0) result = result.refine((value) => codePointLength(value) <= maxLength, { message: errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)` });
|
|
639
|
-
return result;
|
|
640
|
-
};
|
|
641
|
-
const codePointLength = (value) => [...value].length;
|
|
642
|
-
|
|
643
|
-
//#endregion
|
|
644
|
-
//#region src/parsers/parse-typeless-constraints.ts
|
|
645
|
-
const SCALAR_CONSTRAINT_KEYS = [
|
|
646
|
-
"minLength",
|
|
647
|
-
"maxLength",
|
|
648
|
-
"pattern",
|
|
649
|
-
"minimum",
|
|
650
|
-
"maximum",
|
|
651
|
-
"exclusiveMinimum",
|
|
652
|
-
"exclusiveMaximum",
|
|
653
|
-
"multipleOf"
|
|
654
|
-
];
|
|
655
|
-
const hasTypelessScalarConstraints = (schema) => schema.type === void 0 && SCALAR_CONSTRAINT_KEYS.some((key) => schema[key] !== void 0);
|
|
656
|
-
/**
|
|
657
|
-
* Draft 7 applies scalar constraints to matching instance types even when the
|
|
658
|
-
* schema declares no `type`: `{ "minLength": 2 }` restricts strings while
|
|
659
|
-
* leaving every non-string value untouched.
|
|
660
|
-
*/
|
|
661
|
-
const parseTypelessConstraints = (schema, refs) => {
|
|
662
|
-
const stringSchema = parseString({
|
|
663
|
-
...schema,
|
|
664
|
-
type: "string"
|
|
665
|
-
}, refs);
|
|
666
|
-
const numberSchema = parseNumber({
|
|
667
|
-
...schema,
|
|
668
|
-
type: "number"
|
|
669
|
-
});
|
|
670
|
-
return z.any().superRefine((value, ctx) => {
|
|
671
|
-
const applicable = typeof value === "string" ? stringSchema : typeof value === "number" ? numberSchema : void 0;
|
|
672
|
-
if (applicable === void 0) return;
|
|
673
|
-
const result = applicable.safeParse(value);
|
|
674
|
-
if (!result.success) for (const issue of result.error.issues) ctx.addIssue(issue);
|
|
675
|
-
});
|
|
676
|
-
};
|
|
677
|
-
|
|
678
|
-
//#endregion
|
|
679
|
-
//#region src/whole-schema-validation.ts
|
|
680
|
-
const REQUIRES_WHOLE_SCHEMA_VALIDATION = /* @__PURE__ */ new Set([
|
|
681
|
-
"$ref",
|
|
682
|
-
"additionalItems",
|
|
683
|
-
"allOf",
|
|
684
|
-
"anyOf",
|
|
685
|
-
"contains",
|
|
686
|
-
"dependencies",
|
|
687
|
-
"else",
|
|
688
|
-
"if",
|
|
689
|
-
"maxProperties",
|
|
690
|
-
"minProperties",
|
|
691
|
-
"not",
|
|
692
|
-
"oneOf",
|
|
693
|
-
"propertyNames",
|
|
694
|
-
"then",
|
|
695
|
-
"uniqueItems"
|
|
696
|
-
]);
|
|
697
|
-
const TYPELESS_TYPE_SCOPED_KEYWORDS = /* @__PURE__ */ new Set([
|
|
698
|
-
"properties",
|
|
699
|
-
"patternProperties",
|
|
700
|
-
"additionalProperties",
|
|
701
|
-
"propertyNames",
|
|
702
|
-
"required",
|
|
703
|
-
"dependencies",
|
|
704
|
-
"minProperties",
|
|
705
|
-
"maxProperties",
|
|
706
|
-
"items",
|
|
707
|
-
"additionalItems",
|
|
708
|
-
"contains",
|
|
709
|
-
"minItems",
|
|
710
|
-
"maxItems",
|
|
711
|
-
"uniqueItems"
|
|
712
|
-
]);
|
|
713
|
-
const SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
|
|
714
|
-
"$defs",
|
|
715
|
-
"definitions",
|
|
716
|
-
"dependencies",
|
|
717
|
-
"patternProperties",
|
|
718
|
-
"properties"
|
|
719
|
-
]);
|
|
720
|
-
const SCHEMA_ARRAY_KEYWORDS = /* @__PURE__ */ new Set([
|
|
721
|
-
"allOf",
|
|
722
|
-
"anyOf",
|
|
723
|
-
"oneOf"
|
|
724
|
-
]);
|
|
725
|
-
const SCHEMA_VALUE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
726
|
-
"additionalItems",
|
|
727
|
-
"additionalProperties",
|
|
728
|
-
"contains",
|
|
729
|
-
"else",
|
|
730
|
-
"if",
|
|
731
|
-
"items",
|
|
732
|
-
"not",
|
|
733
|
-
"propertyNames",
|
|
734
|
-
"then"
|
|
735
|
-
]);
|
|
736
|
-
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
737
|
-
const hasRequiredDefault = (schema) => {
|
|
738
|
-
if (!Array.isArray(schema.required) || !isObject(schema.properties)) return false;
|
|
739
|
-
return schema.required.some((name) => {
|
|
740
|
-
const property = schema.properties?.[name];
|
|
741
|
-
return isObject(property) && property.default !== void 0;
|
|
742
|
-
});
|
|
743
|
-
};
|
|
744
|
-
const hasUnparsedRequiredProperty = (schema) => {
|
|
745
|
-
if (!Array.isArray(schema.required)) return false;
|
|
746
|
-
const declared = new Set(Object.keys(schema.properties ?? {}));
|
|
747
|
-
return schema.required.some((name) => !declared.has(name));
|
|
748
|
-
};
|
|
749
|
-
/**
|
|
750
|
-
* The native parsers preserve useful Zod structure and materialize defaults,
|
|
751
|
-
* but some JSON Schema assertions cannot be represented by their first-match
|
|
752
|
-
* dispatch. Only those schemas receive an authoritative Draft 7 guard.
|
|
753
|
-
*/
|
|
754
|
-
const requiresWholeSchemaValidation = (schema, seen = /* @__PURE__ */ new WeakSet()) => {
|
|
755
|
-
if (!isObject(schema) || seen.has(schema)) return false;
|
|
756
|
-
seen.add(schema);
|
|
757
|
-
if (Object.keys(schema).some((key) => REQUIRES_WHOLE_SCHEMA_VALIDATION.has(key)) || schema.type === void 0 && Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || hasUnparsedRequiredProperty(schema) || hasRequiredDefault(schema)) return true;
|
|
758
|
-
for (const [key, child] of Object.entries(schema)) if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
|
|
759
|
-
if (Object.values(child).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
760
|
-
} else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
|
|
761
|
-
if (child.some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
762
|
-
} else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
|
|
763
|
-
if ((Array.isArray(child) ? child : [child]).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
764
|
-
}
|
|
765
|
-
return false;
|
|
766
|
-
};
|
|
767
|
-
/**
|
|
768
|
-
* Some schemas are valid for JSON instance types that the native parser does
|
|
769
|
-
* not materialize. Such a node is parsed as `z.any()` so the Draft 7 guard
|
|
770
|
-
* that every one of these keywords also activates (see
|
|
771
|
-
* `requiresWholeSchemaValidation`) stays the acceptance authority without
|
|
772
|
-
* piping into a narrower Zod schema. The check is deliberately local: a
|
|
773
|
-
* permissive descendant must not widen its enclosing parser, or sibling
|
|
774
|
-
* defaults would stop materializing.
|
|
775
|
-
*/
|
|
776
|
-
const requiresPermissiveMaterialization = (schema) => isObject(schema) && ("$ref" in schema || schema.type === void 0 && (Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || [
|
|
777
|
-
"if",
|
|
778
|
-
"then",
|
|
779
|
-
"else",
|
|
780
|
-
"not"
|
|
781
|
-
].some((key) => key in schema)));
|
|
782
|
-
/**
|
|
783
|
-
* The guard schema for a node nested at `path` inside `root`: the enclosing
|
|
784
|
-
* document pointed at that node, so local `$ref`s resolve exactly as they do
|
|
785
|
-
* for the document root. Draft 7 ignores the keywords next to `$ref`, which
|
|
786
|
-
* is what lets the root's own assertions be reused as the pointer carrier.
|
|
787
|
-
*/
|
|
788
|
-
const guardSchemaAt = (node, refs) => isObject(refs.root) && refs.path.length > 0 ? {
|
|
789
|
-
...refs.root,
|
|
790
|
-
$ref: `#/${refs.path.map((part) => encodePointer(String(part))).join("/")}`
|
|
791
|
-
} : node;
|
|
792
|
-
/**
|
|
793
|
-
* OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
|
|
794
|
-
* `minimum`/`maximum`. The Draft 7 interpreter ignores the flag, so the guard
|
|
795
|
-
* receives the numeric spelling the native number parser already honors.
|
|
796
|
-
*/
|
|
797
|
-
const normalizeExclusiveBounds = (value, seen) => {
|
|
798
|
-
if (!isObject(value) || seen.has(value)) return;
|
|
799
|
-
seen.add(value);
|
|
800
|
-
if (value.exclusiveMinimum === true && typeof value.minimum === "number") {
|
|
801
|
-
value.exclusiveMinimum = value.minimum;
|
|
802
|
-
delete value.minimum;
|
|
803
|
-
} else if (typeof value.exclusiveMinimum === "boolean") delete value.exclusiveMinimum;
|
|
804
|
-
if (value.exclusiveMaximum === true && typeof value.maximum === "number") {
|
|
805
|
-
value.exclusiveMaximum = value.maximum;
|
|
806
|
-
delete value.maximum;
|
|
807
|
-
} else if (typeof value.exclusiveMaximum === "boolean") delete value.exclusiveMaximum;
|
|
808
|
-
for (const [key, child] of Object.entries(value)) if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) Object.values(child).forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
809
|
-
else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) child.forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
810
|
-
else if (SCHEMA_VALUE_KEYWORDS.has(key)) (Array.isArray(child) ? child : [child]).forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
811
|
-
};
|
|
812
|
-
const withWholeSchemaValidation = (jsonSchema, parsedSchema) => {
|
|
813
|
-
const interpreterSchema = structuredClone(jsonSchema);
|
|
814
|
-
normalizeExclusiveBounds(interpreterSchema, /* @__PURE__ */ new WeakSet());
|
|
815
|
-
const validator = new Validator(interpreterSchema, "7", false);
|
|
816
|
-
const guardedSchema = z.any().superRefine((value, ctx) => {
|
|
817
|
-
let result;
|
|
818
|
-
try {
|
|
819
|
-
result = validator.validate(value);
|
|
820
|
-
} catch (cause) {
|
|
821
|
-
ctx.addIssue({
|
|
822
|
-
code: z.ZodIssueCode.custom,
|
|
823
|
-
message: `JSON Schema validation failed: ${String(cause)}`
|
|
824
|
-
});
|
|
825
|
-
return;
|
|
826
|
-
}
|
|
827
|
-
if (!result.valid) ctx.addIssue({
|
|
828
|
-
code: z.ZodIssueCode.custom,
|
|
829
|
-
message: result.errors[0]?.error ?? "Input does not satisfy the complete JSON Schema."
|
|
83
|
+
case "uri": return string.url(message);
|
|
84
|
+
case "uuid": return string.uuid(message);
|
|
85
|
+
case "date-time": return string.datetime({
|
|
86
|
+
offset: true,
|
|
87
|
+
message
|
|
830
88
|
});
|
|
831
|
-
|
|
832
|
-
|
|
89
|
+
case "time": return string.time(message);
|
|
90
|
+
case "date": return string.date(message);
|
|
91
|
+
case "duration": return string.duration(message);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/** Zod v3 output: descriptions on `_def`, refinements as `ZodEffects`, the guard as a subclass. */
|
|
95
|
+
const zodV3Backend = {
|
|
96
|
+
isSchema: (value) => value instanceof z.ZodType,
|
|
97
|
+
isNever: (schema) => schema instanceof z.ZodNever,
|
|
98
|
+
any: () => z.any(),
|
|
99
|
+
never: () => z.never(),
|
|
100
|
+
boolean: () => z.boolean(),
|
|
101
|
+
null: () => z.null(),
|
|
102
|
+
string: () => z.string(),
|
|
103
|
+
number: () => z.number(),
|
|
104
|
+
literal: (value) => z.literal(value),
|
|
105
|
+
enum: (values) => z.enum(values),
|
|
106
|
+
predicate: (test) => z.custom(test),
|
|
107
|
+
stringFormat,
|
|
108
|
+
base64: (schema, message) => schema.base64(message),
|
|
109
|
+
regex: (schema, pattern, message) => schema.regex(pattern, message),
|
|
110
|
+
integer: (schema, message) => schema.int(message),
|
|
111
|
+
bound: (schema, kind, value, message) => schema[kind](value, message),
|
|
112
|
+
array: (item) => z.array(item),
|
|
113
|
+
minItems: (schema, count, message) => schema.min(count, message),
|
|
114
|
+
maxItems: (schema, count, message) => schema.max(count, message),
|
|
115
|
+
tuple: (items, rest) => buildTuple(z.tuple(items), rest),
|
|
116
|
+
object: (shape, policy) => applyObjectPolicy(z.object(shape), policy),
|
|
117
|
+
record: (value) => z.record(value),
|
|
118
|
+
union: (options) => z.union(options),
|
|
119
|
+
intersection: (left, right) => z.intersection(left, right),
|
|
120
|
+
optional: (schema) => schema.optional(),
|
|
121
|
+
nullable: (schema) => schema.nullable(),
|
|
122
|
+
withDefault: (schema, value) => schema.default(value),
|
|
123
|
+
readonly: (schema) => schema.readonly(),
|
|
124
|
+
decorate: (schema, decorations) => decorations.description === void 0 ? schema : schema.describe(decorations.description),
|
|
125
|
+
refine: (schema, test, message) => schema.refine(test, { message }),
|
|
126
|
+
superRefine: (schema, check) => schema.superRefine((value, ctx) => check(value, sink(ctx))),
|
|
127
|
+
rewrite: (schema, fn) => schema.transform((value, ctx) => fn(value, sink(ctx))),
|
|
128
|
+
run,
|
|
129
|
+
attachGuard
|
|
833
130
|
};
|
|
834
131
|
|
|
835
|
-
//#endregion
|
|
836
|
-
//#region src/parsers/parse-schema.ts
|
|
837
|
-
const addDescribes = (jsonSchema, zodSchema) => {
|
|
838
|
-
let description = "";
|
|
839
|
-
if (jsonSchema.description) description = jsonSchema.description;
|
|
840
|
-
else if (jsonSchema.title) description = jsonSchema.title;
|
|
841
|
-
if (jsonSchema.example !== void 0) {
|
|
842
|
-
const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
|
|
843
|
-
description = description ? `${description}\n${exampleText}` : exampleText;
|
|
844
|
-
} else if (jsonSchema.examples !== void 0 && Array.isArray(jsonSchema.examples)) {
|
|
845
|
-
const examples = jsonSchema.examples;
|
|
846
|
-
if (examples.length > 0) {
|
|
847
|
-
const exampleText = examples.length === 1 ? `Example: ${JSON.stringify(examples[0])}` : `Examples:\n${examples.map((ex) => ` ${JSON.stringify(ex)}`).join("\n")}`;
|
|
848
|
-
description = description ? `${description}\n${exampleText}` : exampleText;
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
if (description) zodSchema = zodSchema.describe(description);
|
|
852
|
-
return zodSchema;
|
|
853
|
-
};
|
|
854
|
-
const addDefaults = (jsonSchema, zodSchema, refs) => {
|
|
855
|
-
if (jsonSchema.default !== void 0) {
|
|
856
|
-
if (jsonSchema.default === null) {
|
|
857
|
-
if (refs?.path.some((segment) => segment === "anyOf" || segment === "oneOf") && jsonSchema.type && jsonSchema.type !== "null" && !jsonSchema.nullable) return zodSchema;
|
|
858
|
-
}
|
|
859
|
-
zodSchema = zodSchema.default(jsonSchema.default);
|
|
860
|
-
}
|
|
861
|
-
return zodSchema;
|
|
862
|
-
};
|
|
863
|
-
const addAnnotations = (jsonSchema, zodSchema) => {
|
|
864
|
-
if (jsonSchema.readOnly) zodSchema = zodSchema.readonly();
|
|
865
|
-
return zodSchema;
|
|
866
|
-
};
|
|
867
|
-
const selectParser = (schema, refs) => {
|
|
868
|
-
if (requiresPermissiveMaterialization(schema)) return withWholeSchemaValidation(guardSchemaAt(schema, refs), z$1.any());
|
|
869
|
-
else if (its.a.nullable(schema)) return parseNullable(schema, refs);
|
|
870
|
-
else if (its.an.enum(schema)) return parseEnum(schema, refs);
|
|
871
|
-
else if (its.a.const(schema)) return parseConst(schema, refs);
|
|
872
|
-
else if (its.an.object(schema)) return parseObject(schema, refs);
|
|
873
|
-
else if (its.an.array(schema)) return parseArray(schema, refs);
|
|
874
|
-
else if (its.an.anyOf(schema)) return parseAnyOf(schema, refs);
|
|
875
|
-
else if (its.an.allOf(schema)) return parseAllOf(schema, refs);
|
|
876
|
-
else if (its.a.oneOf(schema)) return parseOneOf(schema, refs);
|
|
877
|
-
else if (its.a.not(schema)) return parseNot(schema, refs);
|
|
878
|
-
else if (hasTypelessScalarConstraints(schema)) return parseTypelessConstraints(schema, refs);
|
|
879
|
-
else if (its.a.multipleType(schema)) return parseMultipleType(schema, refs);
|
|
880
|
-
else if (its.a.primitive(schema, "string")) return parseString(schema, refs);
|
|
881
|
-
else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) return parseNumber(schema);
|
|
882
|
-
else if (its.a.primitive(schema, "boolean")) return parseBoolean(schema);
|
|
883
|
-
else if (its.a.primitive(schema, "null")) return parseNull(schema);
|
|
884
|
-
else if (its.a.conditional(schema)) return parseIfThenElse(schema, refs);
|
|
885
|
-
else return parseDefault(schema);
|
|
886
|
-
};
|
|
887
|
-
const parseSchema = (jsonSchema, refs = {
|
|
888
|
-
seen: /* @__PURE__ */ new Map(),
|
|
889
|
-
path: []
|
|
890
|
-
}, blockMeta) => {
|
|
891
|
-
if (typeof jsonSchema !== "object") return jsonSchema ? z$1.any() : z$1.never();
|
|
892
|
-
if (refs.parserOverride) {
|
|
893
|
-
const custom = refs.parserOverride(jsonSchema, refs);
|
|
894
|
-
if (custom instanceof z$1.ZodType) return custom;
|
|
895
|
-
}
|
|
896
|
-
let seen = refs.seen.get(jsonSchema);
|
|
897
|
-
if (seen) {
|
|
898
|
-
if (seen.r !== void 0) return seen.r;
|
|
899
|
-
if (refs.depth === void 0 || seen.n >= refs.depth) return z$1.any();
|
|
900
|
-
seen.n += 1;
|
|
901
|
-
} else {
|
|
902
|
-
seen = {
|
|
903
|
-
r: void 0,
|
|
904
|
-
n: 0
|
|
905
|
-
};
|
|
906
|
-
refs.seen.set(jsonSchema, seen);
|
|
907
|
-
}
|
|
908
|
-
let parsedZodSchema = selectParser(jsonSchema, refs);
|
|
909
|
-
if (!blockMeta) {
|
|
910
|
-
if (!refs.withoutDescribes) parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
|
|
911
|
-
if (!refs.withoutDefaults) parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, refs);
|
|
912
|
-
parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
|
|
913
|
-
}
|
|
914
|
-
seen.r = parsedZodSchema;
|
|
915
|
-
return parsedZodSchema;
|
|
916
|
-
};
|
|
917
|
-
|
|
918
|
-
//#endregion
|
|
919
|
-
//#region src/parsers/parse-object-shape.ts
|
|
920
|
-
/**
|
|
921
|
-
* Parses a JSON Schema object and returns the raw shape (property keys mapped to Zod types).
|
|
922
|
-
* This is useful when you need ZodRawShape instead of a complete ZodObject.
|
|
923
|
-
*
|
|
924
|
-
* @param objectSchema - The JSON Schema object to parse
|
|
925
|
-
* @param refs - Parser references for handling nested schemas
|
|
926
|
-
* @returns A Zod raw shape object
|
|
927
|
-
*/
|
|
928
|
-
function parseObjectShape(objectSchema, refs) {
|
|
929
|
-
if (!objectSchema.properties) return {};
|
|
930
|
-
const propertyKeys = Object.keys(objectSchema.properties);
|
|
931
|
-
if (propertyKeys.length === 0) return {};
|
|
932
|
-
const properties = {};
|
|
933
|
-
for (const key of propertyKeys) {
|
|
934
|
-
const propJsonSchema = objectSchema.properties[key];
|
|
935
|
-
const propRefs = {
|
|
936
|
-
...refs,
|
|
937
|
-
root: refs.root ?? objectSchema,
|
|
938
|
-
path: [
|
|
939
|
-
...refs.path,
|
|
940
|
-
"properties",
|
|
941
|
-
key
|
|
942
|
-
]
|
|
943
|
-
};
|
|
944
|
-
const parsedProperty = parseSchema(propJsonSchema, propRefs);
|
|
945
|
-
const propZodSchema = requiresWholeSchemaValidation(propJsonSchema) ? withWholeSchemaValidation(guardSchemaAt(propJsonSchema, propRefs), parsedProperty) : parsedProperty;
|
|
946
|
-
const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
|
|
947
|
-
if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) {
|
|
948
|
-
if (propJsonSchema.default === null) {
|
|
949
|
-
const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
950
|
-
const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
951
|
-
const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
|
|
952
|
-
if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) properties[key] = propZodSchema.optional().default(null);
|
|
953
|
-
else properties[key] = propZodSchema.nullable().optional().default(null);
|
|
954
|
-
} else properties[key] = propZodSchema.optional().default(propJsonSchema.default);
|
|
955
|
-
} else properties[key] = required ? propZodSchema : propZodSchema.optional();
|
|
956
|
-
}
|
|
957
|
-
return properties;
|
|
958
|
-
}
|
|
959
|
-
|
|
960
132
|
//#endregion
|
|
961
133
|
//#region src/json-schema-to-zod.ts
|
|
962
|
-
const
|
|
963
|
-
|
|
964
|
-
path: [],
|
|
965
|
-
seen: /* @__PURE__ */ new Map(),
|
|
966
|
-
root: schema,
|
|
967
|
-
...options
|
|
968
|
-
});
|
|
969
|
-
return requiresWholeSchemaValidation(schema) ? withWholeSchemaValidation(schema, parsedSchema) : parsedSchema;
|
|
970
|
-
};
|
|
134
|
+
const converter = createConverter(zodV3Backend);
|
|
135
|
+
const jsonSchemaToZod = (schema, options = {}) => converter.jsonSchemaToZod(schema, options);
|
|
971
136
|
/**
|
|
972
137
|
* Converts a JSON Schema object to a Zod raw shape.
|
|
973
138
|
* This is useful when you need the shape object (e.g., `{ name: z.string(), age: z.number() }`)
|
|
@@ -980,16 +145,7 @@ const jsonSchemaToZod = (schema, options = {}) => {
|
|
|
980
145
|
* @param options - Optional configuration for the conversion
|
|
981
146
|
* @returns A Zod raw shape object with property keys mapped to Zod types
|
|
982
147
|
*/
|
|
983
|
-
const jsonSchemaToZodShape = (schema, options = {}) =>
|
|
984
|
-
if (typeof schema !== "object" || schema === null) return {};
|
|
985
|
-
const objectSchema = schema;
|
|
986
|
-
return parseObjectShape(objectSchema, {
|
|
987
|
-
path: [],
|
|
988
|
-
seen: /* @__PURE__ */ new Map(),
|
|
989
|
-
root: objectSchema,
|
|
990
|
-
...options
|
|
991
|
-
});
|
|
992
|
-
};
|
|
148
|
+
const jsonSchemaToZodShape = (schema, options = {}) => converter.jsonSchemaToZodShape(schema, options);
|
|
993
149
|
|
|
994
150
|
//#endregion
|
|
995
151
|
export { InvalidPatternError, jsonSchemaToZod, jsonSchemaToZodShape };
|