@composio/json-schema-to-zod 0.3.4 → 0.4.1

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.
@@ -0,0 +1,1768 @@
1
+ import { dequal } from "dequal/lite";
2
+ import { RE2JS } from "re2js";
3
+ import { Validator, encodePointer, format, ignoredKeyword, schemaArrayKeyword, schemaMapKeyword } from "@cfworker/json-schema";
4
+
5
+ // src/backend/shared.ts
6
+ /** Spreads an optional relative issue path into an issue body. */
7
+ const withPath = (path) => path === void 0 ? {} : { path: [...path] };
8
+ /** Runs `guard` first and falls back to the guard already on the schema. */
9
+ const composeGuards = (guard, inner) => inner ? (value) => guard(value) ?? inner(value) : guard;
10
+ /** Runs the schema; the failure carries the backend's own error with its issues. */
11
+ const run = (schema, value) => {
12
+ const result = schema.safeParse(value);
13
+ const { success } = result;
14
+ return success ? {
15
+ success,
16
+ data: result.data
17
+ } : {
18
+ success,
19
+ failure: result.error
20
+ };
21
+ };
22
+ /** Applies one of the object policies the parsers use to a built object schema. */
23
+ const applyObjectPolicy = (base, policy) => {
24
+ switch (policy.kind) {
25
+ case "strict": return base.strict();
26
+ case "loose": return base.passthrough();
27
+ case "catchall": return base.catchall(policy.schema);
28
+ }
29
+ };
30
+ /** Attaches the rest schema to a tuple when the schema declares one. */
31
+ const buildTuple = (tuple, rest) => rest === void 0 ? tuple : tuple.rest(rest);
32
+
33
+ // src/utils/half.ts
34
+ const half = (arr) => {
35
+ return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
36
+ };
37
+
38
+ // src/utils/its.ts
39
+ const its = {
40
+ an: {
41
+ object: (x) => x.type === "object" || !x.type && (x.properties !== void 0 || x.additionalProperties !== void 0 || x.patternProperties !== void 0),
42
+ array: (x) => x.type === "array",
43
+ anyOf: (x) => x.anyOf !== void 0,
44
+ allOf: (x) => x.allOf !== void 0,
45
+ enum: (x) => x.enum !== void 0
46
+ },
47
+ a: {
48
+ nullable: (x) => x.nullable === true,
49
+ multipleType: (x) => Array.isArray(x.type),
50
+ not: (x) => x.not !== void 0,
51
+ const: (x) => x.const !== void 0,
52
+ primitive: (x, p) => x.type === p,
53
+ conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
54
+ oneOf: (x) => x.oneOf !== void 0
55
+ }
56
+ };
57
+
58
+ // src/parsers/parse-all-of.ts
59
+ const originalIndex = Symbol("Original index");
60
+ const ensureOriginalIndex = (arr) => {
61
+ const newArr = [];
62
+ for (let i = 0; i < arr.length; i++) {
63
+ const item = arr[i];
64
+ if (typeof item === "boolean") newArr.push(item ? { [originalIndex]: i } : {
65
+ [originalIndex]: i,
66
+ not: {}
67
+ });
68
+ else if (originalIndex in item) return arr;
69
+ else newArr.push({
70
+ ...item,
71
+ [originalIndex]: i
72
+ });
73
+ }
74
+ return newArr;
75
+ };
76
+ 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);
77
+ const intersect = (branches, ctx) => {
78
+ if (branches.length === 1) {
79
+ const item = branches[0];
80
+ return parseSchema(item, {
81
+ ...ctx,
82
+ path: [
83
+ ...ctx.path,
84
+ "allOf",
85
+ item[originalIndex]
86
+ ]
87
+ });
88
+ }
89
+ const [left, right] = half(branches);
90
+ return ctx.backend.intersection(intersect(left, ctx), intersect(right, ctx));
91
+ };
92
+ function parseAllOf(jsonSchema, ctx) {
93
+ if (jsonSchema.allOf.length === 0) return ctx.backend.never();
94
+ if (jsonSchema.allOf.length === 1) return intersect(ensureOriginalIndex(jsonSchema.allOf), ctx);
95
+ const opened = jsonSchema.allOf.map((branch) => isClosedObjectBranch(branch) ? {
96
+ ...branch,
97
+ additionalProperties: true
98
+ } : branch);
99
+ const parsed = intersect(ensureOriginalIndex(opened), ctx);
100
+ if (!jsonSchema.allOf.every(isClosedObjectBranch)) return parsed;
101
+ const declaredKeys = new Set(jsonSchema.allOf.flatMap((branch) => Object.keys(branch.properties ?? {})));
102
+ return ctx.backend.superRefine(parsed, (value, issues) => {
103
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
104
+ const unrecognizedKeys = Object.keys(value).filter((key) => !declaredKeys.has(key));
105
+ if (unrecognizedKeys.length > 0) issues.unrecognizedKeys(unrecognizedKeys, `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`);
106
+ });
107
+ }
108
+
109
+ // src/parsers/parse-any-of.ts
110
+ const parseAnyOf = (jsonSchema, ctx) => {
111
+ return jsonSchema.anyOf.length ? jsonSchema.anyOf.length === 1 ? parseSchema(jsonSchema.anyOf[0], {
112
+ ...ctx,
113
+ path: [
114
+ ...ctx.path,
115
+ "anyOf",
116
+ 0
117
+ ]
118
+ }) : ctx.backend.union(jsonSchema.anyOf.map((schema, i) => parseSchema(schema, {
119
+ ...ctx,
120
+ path: [
121
+ ...ctx.path,
122
+ "anyOf",
123
+ i
124
+ ]
125
+ }))) : ctx.backend.any();
126
+ };
127
+
128
+ // src/utils/extend-schema.ts
129
+ function extendSchemaWithMessage(zodSchema, jsonSchema, key, extend) {
130
+ const value = jsonSchema[key];
131
+ if (value !== void 0) {
132
+ const errorMessage = jsonSchema.errorMessage?.[key];
133
+ return extend(zodSchema, value, errorMessage);
134
+ }
135
+ return zodSchema;
136
+ }
137
+
138
+ // src/parsers/parse-array.ts
139
+ const parseArray = (jsonSchema, ctx) => {
140
+ const { backend } = ctx;
141
+ if (its.an.anyOf(jsonSchema)) {
142
+ const types = /* @__PURE__ */ new Set();
143
+ const itemsSchemas = [];
144
+ jsonSchema.anyOf.forEach((option) => {
145
+ if (typeof option === "object" && option.type) types.add(typeof option.type === "string" ? option.type : option.type[0]);
146
+ if (typeof option === "object" && option.items) {
147
+ const optionItems = option.items;
148
+ if (!Array.isArray(optionItems) && typeof optionItems === "object") itemsSchemas.push(optionItems);
149
+ }
150
+ });
151
+ let finalItems;
152
+ if (itemsSchemas.length === 1) finalItems = itemsSchemas[0];
153
+ else if (itemsSchemas.length > 1) finalItems = { anyOf: itemsSchemas };
154
+ const newSchema = {
155
+ ...types.size > 0 ? { type: Array.from(types) } : { type: "array" },
156
+ ...finalItems && { items: finalItems }
157
+ };
158
+ [
159
+ "default",
160
+ "description",
161
+ "examples",
162
+ "title"
163
+ ].forEach((field) => {
164
+ const value = jsonSchema[field];
165
+ if (value !== void 0) newSchema[field] = value;
166
+ });
167
+ return parseSchema(newSchema, ctx);
168
+ }
169
+ if (Array.isArray(jsonSchema.items)) {
170
+ const parsedItems = jsonSchema.items.map((item, index) => parseSchema(item, {
171
+ ...ctx,
172
+ path: [
173
+ ...ctx.path,
174
+ "items",
175
+ index
176
+ ]
177
+ }));
178
+ const prefixSchemas = parsedItems.map((_, length) => backend.tuple(parsedItems.slice(0, length), void 0));
179
+ let fullLengthSchema;
180
+ if (jsonSchema.additionalItems === false) fullLengthSchema = backend.tuple(parsedItems, void 0);
181
+ else if (jsonSchema.additionalItems && jsonSchema.additionalItems !== true) fullLengthSchema = backend.tuple(parsedItems, parseSchema(jsonSchema.additionalItems, {
182
+ ...ctx,
183
+ path: [...ctx.path, "additionalItems"]
184
+ }));
185
+ else fullLengthSchema = backend.tuple(parsedItems, backend.any());
186
+ const variants = [...prefixSchemas, fullLengthSchema];
187
+ let tupleSchema = variants.length === 1 ? variants[0] : backend.union(variants);
188
+ if (typeof jsonSchema.minItems === "number") tupleSchema = backend.refine(tupleSchema, (value) => value.length >= jsonSchema.minItems, `Array must contain at least ${jsonSchema.minItems} element(s)`);
189
+ if (typeof jsonSchema.maxItems === "number") tupleSchema = backend.refine(tupleSchema, (value) => value.length <= jsonSchema.maxItems, `Array must contain at most ${jsonSchema.maxItems} element(s)`);
190
+ return tupleSchema;
191
+ }
192
+ let zodSchema = !jsonSchema.items ? backend.array(backend.any()) : backend.array(parseSchema(jsonSchema.items, {
193
+ ...ctx,
194
+ path: [...ctx.path, "items"]
195
+ }));
196
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minItems", (zs, minItems, errorMessage) => backend.minItems(zs, minItems, errorMessage));
197
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maxItems", (zs, maxItems, errorMessage) => backend.maxItems(zs, maxItems, errorMessage));
198
+ if (typeof jsonSchema.min === "number" && typeof jsonSchema.minItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
199
+ ...jsonSchema,
200
+ minItems: jsonSchema.min
201
+ }, "minItems", (zs, minItems, errorMessage) => backend.minItems(zs, minItems, errorMessage));
202
+ if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
203
+ ...jsonSchema,
204
+ maxItems: jsonSchema.max
205
+ }, "maxItems", (zs, maxItems, errorMessage) => backend.maxItems(zs, maxItems, errorMessage));
206
+ return zodSchema;
207
+ };
208
+
209
+ // src/parsers/parse-boolean.ts
210
+ const parseBoolean = (_jsonSchema, ctx) => {
211
+ return ctx.backend.boolean();
212
+ };
213
+
214
+ // src/parsers/parse-literal-values.ts
215
+ const parseLiteralValues = (values, backend) => {
216
+ if (values.length === 0) return backend.never();
217
+ if (values.every((value) => value === null || typeof value !== "object")) {
218
+ const primitives = values;
219
+ if (primitives.length === 1) return backend.literal(primitives[0]);
220
+ if (primitives.every((value) => typeof value === "string")) return backend.enum(primitives);
221
+ return backend.union(primitives.map((value) => backend.literal(value)));
222
+ }
223
+ return backend.predicate((value) => values.some((candidate) => dequal(value, candidate)));
224
+ };
225
+
226
+ // src/parsers/parse-const.ts
227
+ const parseConst = (jsonSchema, ctx) => {
228
+ const { const: value, ...baseSchema } = jsonSchema;
229
+ return ctx.backend.intersection(parseSchema(baseSchema, {
230
+ ...ctx,
231
+ seen: new Map(ctx.seen)
232
+ }, true), parseLiteralValues([value], ctx.backend));
233
+ };
234
+
235
+ // src/parsers/parse-default.ts
236
+ const parseDefault = (_jsonSchema, ctx) => {
237
+ return ctx.backend.any();
238
+ };
239
+
240
+ // src/parsers/parse-enum.ts
241
+ const parseEnum = (jsonSchema, ctx) => {
242
+ const { enum: values, ...baseSchema } = jsonSchema;
243
+ return ctx.backend.intersection(parseSchema(baseSchema, {
244
+ ...ctx,
245
+ seen: new Map(ctx.seen)
246
+ }, true), parseLiteralValues(values, ctx.backend));
247
+ };
248
+
249
+ // src/parsers/parse-if-then-else.ts
250
+ const parseIfThenElse = (jsonSchema, ctx) => {
251
+ const { backend } = ctx;
252
+ const $if = parseSchema(jsonSchema.if, {
253
+ ...ctx,
254
+ path: [...ctx.path, "if"]
255
+ });
256
+ const $then = parseSchema(jsonSchema.then, {
257
+ ...ctx,
258
+ path: [...ctx.path, "then"]
259
+ });
260
+ const $else = parseSchema(jsonSchema.else, {
261
+ ...ctx,
262
+ path: [...ctx.path, "else"]
263
+ });
264
+ return backend.superRefine(backend.union([$then, $else]), (value, issues) => {
265
+ const result = backend.run($if, value).success ? backend.run($then, value) : backend.run($else, value);
266
+ if (!result.success) issues.forward(result.failure);
267
+ });
268
+ };
269
+
270
+ // src/parsers/parse-multiple-type.ts
271
+ const parseMultipleType = (jsonSchema, ctx) => {
272
+ return ctx.backend.union(jsonSchema.type.map((type) => parseSchema({
273
+ ...jsonSchema,
274
+ type
275
+ }, ctx)));
276
+ };
277
+
278
+ // src/parsers/parse-not.ts
279
+ const parseNot = (jsonSchema, ctx) => {
280
+ const { backend } = ctx;
281
+ return backend.refine(backend.any(), (value) => !backend.run(parseSchema(jsonSchema.not, {
282
+ ...ctx,
283
+ path: [...ctx.path, "not"]
284
+ }), value).success, "Invalid input: Should NOT be valid against schema");
285
+ };
286
+
287
+ // src/parsers/parse-null.ts
288
+ const parseNull = (_jsonSchema, ctx) => {
289
+ return ctx.backend.null();
290
+ };
291
+
292
+ // src/utils/omit.ts
293
+ const omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
294
+ if (!keys.includes(key)) acc[key] = obj[key];
295
+ return acc;
296
+ }, {});
297
+
298
+ // src/parsers/parse-nullable.ts
299
+ /**
300
+ * For compatibility with open api 3.0 nullable
301
+ */
302
+ const parseNullable = (jsonSchema, ctx) => {
303
+ const hasNullDefault = jsonSchema.default === null;
304
+ const baseSchema = hasNullDefault ? omit(omit(jsonSchema, "nullable"), "default") : omit(jsonSchema, "nullable");
305
+ const zodSchema = ctx.backend.nullable(parseSchema(baseSchema, ctx, true));
306
+ return hasNullDefault ? ctx.backend.withDefault(zodSchema, null) : zodSchema;
307
+ };
308
+
309
+ // src/parsers/parse-number.ts
310
+ const toDecimalInteger = (value) => {
311
+ if (!Number.isFinite(value)) return void 0;
312
+ const negative = value < 0;
313
+ const [coefficient, exponentText] = Math.abs(value).toString().toLowerCase().split("e");
314
+ const exponent = exponentText === void 0 ? 0 : Number(exponentText);
315
+ const [whole, fraction = ""] = coefficient.split(".");
316
+ let digits = `${whole}${fraction}`.replace(/^0+(?=\d)/, "");
317
+ let scale = fraction.length - exponent;
318
+ if (scale < 0) {
319
+ digits += "0".repeat(-scale);
320
+ scale = 0;
321
+ }
322
+ return {
323
+ integer: BigInt(`${negative ? "-" : ""}${digits}`),
324
+ scale
325
+ };
326
+ };
327
+ const isJsonMultipleOf = (value, multiple) => {
328
+ const dividend = toDecimalInteger(value);
329
+ const divisor = toDecimalInteger(multiple);
330
+ if (!dividend || !divisor || divisor.integer === 0n) return false;
331
+ const scale = Math.max(dividend.scale, divisor.scale);
332
+ return dividend.integer * 10n ** BigInt(scale - dividend.scale) % (divisor.integer * 10n ** BigInt(scale - divisor.scale)) === 0n;
333
+ };
334
+ const parseNumber = (jsonSchema, backend) => {
335
+ let zodSchema = backend.number();
336
+ let isInteger = false;
337
+ if (jsonSchema.type === "integer") {
338
+ isInteger = true;
339
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "type", (zs, _, errorMsg) => backend.integer(zs, errorMsg));
340
+ } else if (jsonSchema.format === "int64") {
341
+ isInteger = true;
342
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, _, errorMsg) => backend.integer(zs, errorMsg));
343
+ }
344
+ if (typeof jsonSchema.minimum === "number") {
345
+ if (jsonSchema.exclusiveMinimum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => backend.bound(zs, "gt", minimum, errorMsg));
346
+ else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => backend.bound(zs, "gte", minimum, errorMsg));
347
+ }
348
+ if (typeof jsonSchema.exclusiveMinimum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMinimum", (zs, exclusiveMinimum, errorMsg) => backend.bound(zs, "gt", exclusiveMinimum, errorMsg));
349
+ if (typeof jsonSchema.maximum === "number") {
350
+ if (jsonSchema.exclusiveMaximum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => backend.bound(zs, "lt", maximum, errorMsg));
351
+ else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => backend.bound(zs, "lte", maximum, errorMsg));
352
+ }
353
+ if (typeof jsonSchema.exclusiveMaximum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMaximum", (zs, exclusiveMaximum, errorMsg) => backend.bound(zs, "lt", exclusiveMaximum, errorMsg));
354
+ if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
355
+ ...jsonSchema,
356
+ minimum: jsonSchema.min
357
+ }, "minimum", (zs, minimum, errorMsg) => backend.bound(zs, "gte", minimum, errorMsg));
358
+ if (typeof jsonSchema.max === "number" && typeof jsonSchema.maximum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
359
+ ...jsonSchema,
360
+ maximum: jsonSchema.max
361
+ }, "maximum", (zs, maximum, errorMsg) => backend.bound(zs, "lte", maximum, errorMsg));
362
+ if (typeof jsonSchema.multipleOf === "number") {
363
+ const errorMessage = jsonSchema.errorMessage?.multipleOf;
364
+ if (jsonSchema.multipleOf === 1) return isInteger ? zodSchema : backend.integer(zodSchema, errorMessage);
365
+ return backend.refine(zodSchema, (value) => isJsonMultipleOf(value, jsonSchema.multipleOf), errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}`);
366
+ }
367
+ return zodSchema;
368
+ };
369
+
370
+ // src/parsers/parse-one-of.ts
371
+ const parseOneOf = (jsonSchema, ctx) => {
372
+ const { backend } = ctx;
373
+ if (!jsonSchema.oneOf.length) return backend.any();
374
+ if (jsonSchema.oneOf.length === 1) return parseSchema(jsonSchema.oneOf[0], {
375
+ ...ctx,
376
+ path: [
377
+ ...ctx.path,
378
+ "oneOf",
379
+ 0
380
+ ]
381
+ });
382
+ return backend.superRefine(backend.any(), (x, issues) => {
383
+ const schemas = jsonSchema.oneOf.map((schema, i) => parseSchema(schema, {
384
+ ...ctx,
385
+ path: [
386
+ ...ctx.path,
387
+ "oneOf",
388
+ i
389
+ ]
390
+ }));
391
+ const unionErrors = schemas.reduce((errors, schema) => {
392
+ const result = backend.run(schema, x);
393
+ return result.success ? errors : [...errors, result.failure];
394
+ }, []);
395
+ if (schemas.length - unionErrors.length !== 1) issues.invalidUnion("Invalid input: Should pass single schema", unionErrors);
396
+ });
397
+ };
398
+
399
+ // src/parsers/property-presence.ts
400
+ const admitsNull = (branches) => Array.isArray(branches) && branches.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
401
+ /**
402
+ * Wraps a parsed property for its place in an object: required properties
403
+ * stay as parsed, optional ones become optional, and an optional property
404
+ * with a `default` carries it. A `null` default makes the property nullable
405
+ * unless its schema already admits `null` through `anyOf`, `oneOf`, or
406
+ * `nullable`.
407
+ */
408
+ const applyPropertyPresence = (backend, propJsonSchema, parsed, required) => {
409
+ if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) {
410
+ if (propJsonSchema.default === null) {
411
+ const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
412
+ if (admitsNull(propJsonSchema.anyOf) || admitsNull(propJsonSchema.oneOf) || isNullable) return backend.withDefault(backend.optional(parsed), null);
413
+ return backend.withDefault(backend.optional(backend.nullable(parsed)), null);
414
+ }
415
+ return backend.withDefault(backend.optional(parsed), propJsonSchema.default);
416
+ }
417
+ return required ? parsed : backend.optional(parsed);
418
+ };
419
+
420
+ // src/utils/unicode-pattern.ts
421
+ const compilesAsUnicode = (pattern) => {
422
+ try {
423
+ new RegExp(pattern, "u");
424
+ return true;
425
+ } catch {
426
+ return false;
427
+ }
428
+ };
429
+ const REGEX_SYNTAX_CHARACTERS = /* @__PURE__ */ new Set("^$\\.*+?()[]{}|/");
430
+ const CHARACTER_CLASS_ESCAPES = /* @__PURE__ */ new Set("dDwWsS");
431
+ const CONTROL_ESCAPES$1 = /* @__PURE__ */ new Set("fnrtv");
432
+ const HEX_DIGIT = /^[0-9A-Fa-f]$/;
433
+ const QUANTIFIER = /^\{\d+(?:,\d*)?\}/;
434
+ const hexEscape = (code) => `\\x${code.toString(16).padStart(2, "0")}`;
435
+ /** Capturing group count and whether any is named, as the parser counts them. */
436
+ const scanGroups = (pattern) => {
437
+ let count = 0;
438
+ let named = false;
439
+ let inClass = false;
440
+ for (let index = 0; index < pattern.length; index++) {
441
+ const char = pattern[index];
442
+ if (char === "\\") index++;
443
+ else if (inClass) inClass = char !== "]";
444
+ else if (char === "[") inClass = true;
445
+ else if (char === "(") {
446
+ if (pattern[index + 1] !== "?") count++;
447
+ else if (pattern[index + 2] === "<" && !"=!".includes(pattern[index + 3] ?? "")) {
448
+ count++;
449
+ named = true;
450
+ }
451
+ }
452
+ }
453
+ return {
454
+ count,
455
+ named
456
+ };
457
+ };
458
+ /**
459
+ * A legacy octal escape (a `\` digit sequence that is not a backreference) as
460
+ * a hex escape. Returns the replacement and how many digits it consumed.
461
+ */
462
+ const legacyOctalEscape = (pattern, index) => {
463
+ const first = pattern[index];
464
+ if (first === "8" || first === "9") return [first, 1];
465
+ const maxDigits = first <= "3" ? 3 : 2;
466
+ let digits = first;
467
+ while (digits.length < maxDigits && /^[0-7]$/.test(pattern[index + digits.length] ?? "")) digits += pattern[index + digits.length];
468
+ return [hexEscape(parseInt(digits, 8)), digits.length];
469
+ };
470
+ /**
471
+ * The interpreter compiles every pattern with the `u` flag, while
472
+ * `compilePattern` and the native parsers deliberately do not. This spells a
473
+ * pattern written for the legacy (Annex B) grammar in the Unicode grammar with
474
+ * the same meaning: identity escapes such as `\_`, `\:` or `\k` become the
475
+ * literal character, incomplete `\x`, `\u` and `\c` escapes and legacy octal
476
+ * escapes are spelled out, lone `{`, `}` and `]` are escaped, and a hyphen
477
+ * next to a class escape (`[\w-.]`), which is a literal there, is escaped.
478
+ *
479
+ * Returns `undefined` for the few legacy constructs with no Unicode spelling,
480
+ * such as a quantified lookahead. Matching differs only for astral
481
+ * characters, which `.` and negated classes treat as one character, not two.
482
+ */
483
+ const toUnicodePattern = (pattern) => {
484
+ const { count: groupCount, named: hasNamedGroups } = scanGroups(pattern);
485
+ let rewritten = "";
486
+ let inClass = false;
487
+ let previousAtomWasClassEscape = false;
488
+ let index = 0;
489
+ while (index < pattern.length) {
490
+ const char = pattern[index];
491
+ if (char !== "\\" && inClass) {
492
+ if (char === "]") {
493
+ inClass = false;
494
+ rewritten += char;
495
+ } else if (char === "-" && (previousAtomWasClassEscape || pattern[index + 1] === "\\" && CHARACTER_CLASS_ESCAPES.has(pattern[index + 2] ?? ""))) rewritten += "\\-";
496
+ else rewritten += char;
497
+ previousAtomWasClassEscape = false;
498
+ index++;
499
+ continue;
500
+ }
501
+ if (char !== "\\") {
502
+ const quantifier = char === "{" ? QUANTIFIER.exec(pattern.slice(index)) : null;
503
+ if (char === "[") {
504
+ inClass = true;
505
+ const opening = pattern[index + 1] === "^" ? "[^" : "[";
506
+ rewritten += opening;
507
+ index += opening.length;
508
+ } else if (quantifier) {
509
+ rewritten += quantifier[0];
510
+ index += quantifier[0].length;
511
+ } else {
512
+ rewritten += char === "{" || char === "}" || char === "]" ? `\\${char}` : char;
513
+ index++;
514
+ }
515
+ continue;
516
+ }
517
+ const escaped = pattern[index + 1];
518
+ if (escaped === void 0) return;
519
+ previousAtomWasClassEscape = false;
520
+ if (CHARACTER_CLASS_ESCAPES.has(escaped)) {
521
+ previousAtomWasClassEscape = inClass;
522
+ rewritten += `\\${escaped}`;
523
+ index += 2;
524
+ } else if (CONTROL_ESCAPES$1.has(escaped) || REGEX_SYNTAX_CHARACTERS.has(escaped) || escaped === "b" || escaped === "B" && !inClass || escaped === "-" && inClass || escaped === "k" && hasNamedGroups && !inClass) {
525
+ rewritten += `\\${escaped}`;
526
+ index += 2;
527
+ } else if (escaped === "c") {
528
+ const letter = pattern[index + 2] ?? "";
529
+ if (/^[A-Za-z]$/.test(letter)) {
530
+ rewritten += `\\c${letter}`;
531
+ index += 3;
532
+ } else if (inClass && /^[0-9_]$/.test(letter)) {
533
+ rewritten += hexEscape(letter.charCodeAt(0) % 32);
534
+ index += 3;
535
+ } else {
536
+ rewritten += "\\\\";
537
+ index++;
538
+ }
539
+ } else if (escaped === "x" || escaped === "u") {
540
+ const length = escaped === "x" ? 2 : 4;
541
+ const digits = pattern.slice(index + 2, index + 2 + length);
542
+ if (digits.length === length && [...digits].every((digit) => HEX_DIGIT.test(digit))) {
543
+ rewritten += `\\${escaped}${digits}`;
544
+ index += 2 + length;
545
+ } else {
546
+ rewritten += escaped;
547
+ index += 2;
548
+ }
549
+ } else if (/^[0-9]$/.test(escaped)) {
550
+ const decimal = /^\d+/.exec(pattern.slice(index + 1))?.[0] ?? escaped;
551
+ if (escaped === "0" && !/^[0-9]$/.test(pattern[index + 2] ?? "")) {
552
+ rewritten += "\\0";
553
+ index += 2;
554
+ } else if (!inClass && escaped !== "0" && Number(decimal) <= groupCount) {
555
+ rewritten += `\\${decimal}`;
556
+ index += 1 + decimal.length;
557
+ } else {
558
+ const [replacement, consumed] = legacyOctalEscape(pattern, index + 1);
559
+ rewritten += replacement;
560
+ index += 1 + consumed;
561
+ }
562
+ } else {
563
+ rewritten += escaped;
564
+ index += 2;
565
+ }
566
+ }
567
+ return compilesAsUnicode(rewritten) ? rewritten : void 0;
568
+ };
569
+
570
+ // src/utils/linear-pattern.ts
571
+ /**
572
+ * ECMAScript `\s`: the characters it matches, spelled for an RE2 class body.
573
+ * RE2's own `\s` is ASCII-only, so both `\s` and `\S` are spelled out.
574
+ */
575
+ const WHITESPACE = "\\t\\n\\x{B}\\f\\r\\x{20}\\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{2028}\\x{2029}\\x{202F}\\x{205F}\\x{3000}\\x{FEFF}";
576
+ /** The complement of {@link WHITESPACE}, usable inside another class. */
577
+ const NON_WHITESPACE = "\\x{0}-\\x{8}\\x{E}-\\x{1F}\\x{21}-\\x{9F}\\x{A1}-\\x{167F}\\x{1681}-\\x{1FFF}\\x{200B}-\\x{2027}\\x{202A}-\\x{202E}\\x{2030}-\\x{205E}\\x{2060}-\\x{2FFF}\\x{3001}-\\x{FEFE}\\x{FF00}-\\x{10FFFF}";
578
+ const ANY_CHARACTER = "\\x{0}-\\x{10FFFF}";
579
+ /** ECMAScript `.` without the `s` flag excludes every line terminator, not just `\n`. */
580
+ const DOT = "[^\\n\\r\\x{2028}\\x{2029}]";
581
+ const SYNTAX_CHARACTERS = /* @__PURE__ */ new Set("^$\\.*+?()[]{}|/-");
582
+ const CONTROL_ESCAPES = /* @__PURE__ */ new Set("fnrtv");
583
+ const PASSTHROUGH_CLASS_ESCAPES = /* @__PURE__ */ new Set("dDwW");
584
+ const codePoint = (code) => `\\x{${code.toString(16).toUpperCase()}}`;
585
+ /** Thrown inside the translator for constructs RE2 cannot express. */
586
+ var Unsupported = class extends Error {};
587
+ /**
588
+ * Reads one escape at `pattern[index] === '\\'` that is valid in both a class
589
+ * and the top level, returning its RE2 spelling and the index after it.
590
+ */
591
+ const readEscape = (pattern, index, inClass) => {
592
+ const escaped = pattern[index + 1] ?? "";
593
+ if (PASSTHROUGH_CLASS_ESCAPES.has(escaped) || CONTROL_ESCAPES.has(escaped)) return [`\\${escaped}`, index + 2];
594
+ if (escaped === "s") return [inClass ? WHITESPACE : `[${WHITESPACE}]`, index + 2];
595
+ if (escaped === "S") return [inClass ? NON_WHITESPACE : `[^${WHITESPACE}]`, index + 2];
596
+ if (escaped === "b" || escaped === "B") return [inClass ? codePoint(8) : `\\${escaped}`, index + 2];
597
+ if (escaped === "0") return [codePoint(0), index + 2];
598
+ if (escaped === "c") return [codePoint(pattern.charCodeAt(index + 2) % 32), index + 3];
599
+ if (escaped === "x") return [codePoint(parseInt(pattern.slice(index + 2, index + 4), 16)), index + 4];
600
+ if (escaped === "u") {
601
+ if (pattern[index + 2] === "{") {
602
+ const end = pattern.indexOf("}", index + 3);
603
+ return [codePoint(parseInt(pattern.slice(index + 3, end), 16)), end + 1];
604
+ }
605
+ const unit = parseInt(pattern.slice(index + 2, index + 6), 16);
606
+ const low = /^\\u([Dd][C-Fc-f][0-9A-Fa-f]{2})/.exec(pattern.slice(index + 6));
607
+ if (unit >= 55296 && unit <= 56319 && low) {
608
+ const combined = (unit - 55296) * 1024 + (parseInt(low[1], 16) - 56320) + 65536;
609
+ return [codePoint(combined), index + 12];
610
+ }
611
+ return [codePoint(unit), index + 6];
612
+ }
613
+ if (SYNTAX_CHARACTERS.has(escaped)) return [`\\${escaped}`, index + 2];
614
+ throw new Unsupported();
615
+ };
616
+ /** Translates a class starting at `pattern[index] === '['`. */
617
+ const readClass = (pattern, index) => {
618
+ let cursor = index + 1;
619
+ const negated = pattern[cursor] === "^";
620
+ if (negated) cursor++;
621
+ if (pattern[cursor] === "]") return [negated ? `[${ANY_CHARACTER}]` : `[^${ANY_CHARACTER}]`, cursor + 1];
622
+ let body = "";
623
+ while (pattern[cursor] !== "]") {
624
+ const char = pattern[cursor];
625
+ if (char === "\\") {
626
+ const [spelled, next] = readEscape(pattern, cursor, true);
627
+ body += spelled;
628
+ cursor = next;
629
+ } else {
630
+ body += char === "[" || char === "^" ? `\\${char}` : char;
631
+ cursor += char.length;
632
+ }
633
+ }
634
+ return [`[${negated ? "^" : ""}${body}]`, cursor + 1];
635
+ };
636
+ /**
637
+ * Translates a pattern written in the ECMAScript Unicode (`u` flag) grammar
638
+ * into RE2 syntax with the same meaning. The input must already compile with
639
+ * the `u` flag. Returns `undefined` for constructs that need a backtracking
640
+ * engine (lookaround, backreferences) or that RE2 spells differently.
641
+ */
642
+ const unicodePatternToRe2 = (pattern) => {
643
+ let result = "";
644
+ let index = 0;
645
+ try {
646
+ while (index < pattern.length) {
647
+ const char = pattern[index];
648
+ if (char === "\\") {
649
+ const [spelled, next] = readEscape(pattern, index, false);
650
+ result += spelled;
651
+ index = next;
652
+ } else if (char === "[") {
653
+ const [spelled, next] = readClass(pattern, index);
654
+ result += spelled;
655
+ index = next;
656
+ } else if (char === ".") {
657
+ result += DOT;
658
+ index++;
659
+ } else if (char === "(" && pattern[index + 1] === "?") {
660
+ if (pattern[index + 2] === ":") {
661
+ result += "(?:";
662
+ index += 3;
663
+ } else if (pattern[index + 2] === "<" && !"=!".includes(pattern[index + 3] ?? "")) {
664
+ result += "(";
665
+ index = pattern.indexOf(">", index) + 1;
666
+ } else throw new Unsupported();
667
+ } else {
668
+ result += char;
669
+ index++;
670
+ }
671
+ }
672
+ } catch (error) {
673
+ if (error instanceof Unsupported) return;
674
+ throw error;
675
+ }
676
+ return result;
677
+ };
678
+ /**
679
+ * Compiles a Unicode-grammar pattern for RE2JS, whose matching time is linear
680
+ * in the input for every pattern. Returns `undefined` when RE2 cannot express
681
+ * the pattern.
682
+ */
683
+ const compileLinearPattern = (unicodePattern) => {
684
+ const re2 = unicodePatternToRe2(unicodePattern);
685
+ if (re2 === void 0) return;
686
+ try {
687
+ return RE2JS.compile(re2);
688
+ } catch {
689
+ return;
690
+ }
691
+ };
692
+ /** A quantifier whose range (maximum minus minimum) exceeds this counts as unbounded. */
693
+ const LARGE_QUANTIFIER_RANGE = 16;
694
+ /** Bound on the product of the ranges of all small variable quantifiers. */
695
+ const MAX_SMALL_QUANTIFIER_PRODUCT = 64;
696
+ /** Absolute explicit repeat bounds, including repetitions of zero-width assertions. */
697
+ const MAX_FALLBACK_REPEAT_COUNT = 64;
698
+ /** Bound on the polynomial degree of the backtracking search in the input length. */
699
+ const MAX_BACKTRACKING_DEGREE = 2;
700
+ const BRACE_QUANTIFIER = /^\{(\d+)(,(\d*))?\}/;
701
+ /**
702
+ * Whether a pattern that RE2 cannot run (it needs lookaround or a
703
+ * backreference) is still safe for the native backtracking engine on short
704
+ * input. Deliberately conservative, since only such patterns reach it:
705
+ *
706
+ * - no backreferences;
707
+ * - no quantified group that contains a quantifier or an alternation, the
708
+ * shapes behind exponential backtracking (`(a+)+`, `(a|a)*`);
709
+ * - no lookaround nested in another lookaround;
710
+ * - explicit repetition bounds are capped, including fixed assertions;
711
+ * - the search is at most quadratic: one degree for an unanchored start, plus
712
+ * the number of unbounded quantifiers at the top level, plus the largest
713
+ * number inside a single lookaround (lookarounds are atomic, so they add
714
+ * rather than multiply);
715
+ * - small variable quantifiers (`?`, `{1,3}`) and alternations multiply the
716
+ * work by a bounded constant (`(?:a|aa)(?:a|aa)...b` is exponential without
717
+ * any quantifier).
718
+ * A leading anchor removes search work only without a top-level alternative.
719
+ *
720
+ * Callers still bound the input length, which keeps the quadratic case cheap.
721
+ */
722
+ const isSafeForBacktracking = (pattern) => {
723
+ const hasNamedGroup = /\(\?<(?![=!])/.test(pattern);
724
+ const newGroup = (lookaround) => ({
725
+ lookaround,
726
+ quantified: false,
727
+ alternation: false,
728
+ branches: 1
729
+ });
730
+ const stack = [newGroup(false)];
731
+ let topLevelLarge = 0;
732
+ let lookaroundLarge = 0;
733
+ let maxLookaroundLarge = 0;
734
+ let smallProduct = 1;
735
+ let lastAtomGroup;
736
+ let index = 0;
737
+ const insideLookaround = () => stack.some((group) => group.lookaround);
738
+ const multiply = (factor) => {
739
+ smallProduct *= factor;
740
+ return smallProduct <= MAX_SMALL_QUANTIFIER_PRODUCT;
741
+ };
742
+ while (index < pattern.length) {
743
+ const char = pattern[index];
744
+ const current = stack[stack.length - 1];
745
+ let quantifierLength = 0;
746
+ let range = 0;
747
+ if (char === "*" || char === "+") {
748
+ quantifierLength = 1;
749
+ range = Infinity;
750
+ } else if (char === "?") {
751
+ quantifierLength = 1;
752
+ range = 1;
753
+ } else if (char === "{") {
754
+ const brace = BRACE_QUANTIFIER.exec(pattern.slice(index));
755
+ if (brace) {
756
+ quantifierLength = brace[0].length;
757
+ const minimum = Number(brace[1]);
758
+ const maximum = brace[2] === void 0 ? minimum : Number(brace[3]);
759
+ if (minimum > MAX_FALLBACK_REPEAT_COUNT || brace[3] !== "" && maximum > MAX_FALLBACK_REPEAT_COUNT) return false;
760
+ if (brace[2] !== void 0) range = brace[3] === "" ? Infinity : Number(brace[3]) - Number(brace[1]);
761
+ }
762
+ }
763
+ if (quantifierLength > 0) {
764
+ if (lastAtomGroup && (lastAtomGroup.quantified || lastAtomGroup.alternation)) return false;
765
+ if (range > LARGE_QUANTIFIER_RANGE) {
766
+ if (insideLookaround()) maxLookaroundLarge = Math.max(maxLookaroundLarge, ++lookaroundLarge);
767
+ else topLevelLarge++;
768
+ } else if (range > 0 && !multiply(range + 1)) return false;
769
+ current.quantified = true;
770
+ index += quantifierLength;
771
+ if (pattern[index] === "?") index++;
772
+ lastAtomGroup = void 0;
773
+ continue;
774
+ }
775
+ lastAtomGroup = void 0;
776
+ if (char === "\\") {
777
+ const escaped = pattern[index + 1] ?? "";
778
+ if (/^[1-9]$/.test(escaped) || escaped === "k" && hasNamedGroup) return false;
779
+ index += 2;
780
+ } else if (char === "[") {
781
+ index++;
782
+ while (index < pattern.length && pattern[index] !== "]") index += pattern[index] === "\\" ? 2 : 1;
783
+ index++;
784
+ } else if (char === "(") {
785
+ const lookaround = pattern[index + 1] === "?" && ("=!".includes(pattern[index + 2] ?? "") || pattern[index + 2] === "<" && "=!".includes(pattern[index + 3] ?? ""));
786
+ if (lookaround) {
787
+ if (insideLookaround()) return false;
788
+ lookaroundLarge = 0;
789
+ }
790
+ stack.push(newGroup(lookaround));
791
+ index++;
792
+ if (pattern[index] === "?") index += lookaround && pattern[index + 1] === "<" ? 3 : 2;
793
+ } else if (char === ")") {
794
+ const closed = stack.length > 1 ? stack.pop() : current;
795
+ if (!multiply(closed.branches)) return false;
796
+ const parent = stack[stack.length - 1];
797
+ parent.quantified ||= closed.quantified;
798
+ parent.alternation ||= closed.alternation;
799
+ lastAtomGroup = closed;
800
+ index++;
801
+ } else {
802
+ if (char === "|") {
803
+ current.alternation = true;
804
+ current.branches++;
805
+ }
806
+ index++;
807
+ }
808
+ }
809
+ if (!multiply(stack[0].branches)) return false;
810
+ return (pattern.startsWith("^") && stack[0].branches === 1 ? 0 : 1) + topLevelLarge + maxLookaroundLarge <= MAX_BACKTRACKING_DEGREE;
811
+ };
812
+ /**
813
+ * Longest input the backtracking fallback runs on. Longer input is treated as
814
+ * matching: skipping a constraint only widens what the schema accepts, which
815
+ * a hostile schema could do anyway by omitting the pattern.
816
+ */
817
+ const MAX_BACKTRACKING_INPUT_LENGTH = 1e3;
818
+ /**
819
+ * Builds the matcher for a schema pattern in the legacy (no `u` flag) grammar
820
+ * the rest of this package accepts. `pattern` must already compile as a
821
+ * `RegExp`.
822
+ */
823
+ const createPatternMatcher = (pattern) => {
824
+ const unicodePattern = toUnicodePattern(pattern);
825
+ const linear = unicodePattern === void 0 ? void 0 : compileLinearPattern(unicodePattern);
826
+ if (linear !== void 0) return {
827
+ kind: "linear",
828
+ regex: linear
829
+ };
830
+ if (isSafeForBacktracking(pattern)) return {
831
+ kind: "backtracking",
832
+ regex: new RegExp(pattern)
833
+ };
834
+ return { kind: "unenforced" };
835
+ };
836
+ /** Whether `input` satisfies the pattern behind `matcher`. */
837
+ const patternMatches = (matcher, input) => {
838
+ switch (matcher.kind) {
839
+ case "linear": return matcher.regex.test(input);
840
+ case "backtracking":
841
+ if (input.length > 1e3) return true;
842
+ matcher.regex.lastIndex = 0;
843
+ return matcher.regex.test(input);
844
+ case "unenforced": return true;
845
+ }
846
+ };
847
+
848
+ // src/utils/compile-pattern.ts
849
+ /**
850
+ * Longest `pattern` / `patternProperties` key this package compiles. Tool
851
+ * schemas come from third-party toolkit definitions; anything past this is
852
+ * far outside what a format constraint needs and is rejected before it can
853
+ * cost anything at validation time.
854
+ */
855
+ const MAX_PATTERN_LENGTH = 1024;
856
+ /**
857
+ * Raised at conversion time when a schema `pattern` cannot be turned into a
858
+ * `RegExp`. Conversion fails eagerly, in line with how this package and
859
+ * `@composio/json-schema-to-effect-schema` treat other schema defects: a broken
860
+ * schema is the tool author's bug, so it surfaces once at construction rather
861
+ * than on every validation as if the caller's input were wrong.
862
+ */
863
+ var InvalidPatternError = class extends Error {
864
+ keyword;
865
+ pattern;
866
+ path;
867
+ reason;
868
+ name = "InvalidPatternError";
869
+ constructor(keyword, pattern, path, reason, detail, options) {
870
+ const location = path.length > 0 ? path.join(".") : "<root>";
871
+ super(`Invalid ${keyword} regular expression ${JSON.stringify(pattern)} at ${location}: ${detail}`, options);
872
+ this.keyword = keyword;
873
+ this.pattern = pattern;
874
+ this.path = path;
875
+ this.reason = reason;
876
+ }
877
+ };
878
+ /**
879
+ * A schema pattern as a `RegExp` whose matching cannot be made to backtrack
880
+ * catastrophically. The native `source` stays intact, so JSON Schema emitted
881
+ * from the Zod schema still carries the original pattern for the model, while
882
+ * `test` and `exec` go through a {@link PatternMatcher}: RE2 where it can run
883
+ * the pattern, otherwise a statically vetted, length-bounded native match, or
884
+ * no check at all.
885
+ */
886
+ var SchemaPatternRegExp = class extends RegExp {
887
+ matcher;
888
+ constructor(pattern, matcher = createPatternMatcher(pattern)) {
889
+ super(pattern);
890
+ this.matcher = matcher;
891
+ }
892
+ test(input) {
893
+ return patternMatches(this.matcher, String(input));
894
+ }
895
+ exec(input) {
896
+ const string = String(input);
897
+ switch (this.matcher.kind) {
898
+ case "linear": return this.matcher.regex.exec(string);
899
+ case "backtracking": return patternMatches(this.matcher, string) ? this.matcher.regex.exec(string) : null;
900
+ case "unenforced": return null;
901
+ }
902
+ }
903
+ static get [Symbol.species]() {
904
+ return RegExp;
905
+ }
906
+ };
907
+ /**
908
+ * Compile a schema pattern, rejecting anything that does not compile or that
909
+ * exceeds {@link MAX_PATTERN_LENGTH}.
910
+ *
911
+ * Matching is protected against catastrophic backtracking (ReDoS): tool
912
+ * arguments come from a model that may be steered by untrusted content, and
913
+ * object keys are as attacker-influenced as values. Patterns run on RE2,
914
+ * which is linear-time. A `pattern` RE2 cannot express (lookaround) falls back
915
+ * to the native engine only when it passes a conservative static check, and
916
+ * only on bounded input; otherwise it is left unenforced, which widens the
917
+ * schema no further than omitting the pattern would. A `patternProperties`
918
+ * key decides which schema applies to a property, so it is never silently
919
+ * skipped: one RE2 cannot express is rejected at conversion.
920
+ *
921
+ * No `u` flag is passed: existing tool schemas rely on identity escapes that
922
+ * Unicode mode refuses, and the goal here is to fail on defects, not to
923
+ * tighten which patterns are accepted.
924
+ */
925
+ const compilePattern = (keyword, pattern, refs) => {
926
+ const path = keyword === "pattern" ? refs.path : [
927
+ ...refs.path,
928
+ "patternProperties",
929
+ pattern
930
+ ];
931
+ if (pattern.length > 1024) throw new InvalidPatternError(keyword, pattern, path, "too-long", `pattern exceeds ${MAX_PATTERN_LENGTH} characters`);
932
+ try {
933
+ new RegExp(pattern);
934
+ } catch (cause) {
935
+ const detail = cause instanceof Error ? cause.message : String(cause);
936
+ throw new InvalidPatternError(keyword, pattern, path, "syntax", detail, { cause });
937
+ }
938
+ const matcher = createPatternMatcher(pattern);
939
+ if (keyword === "patternProperties" && matcher.kind !== "linear") throw new InvalidPatternError(keyword, pattern, path, "unsupported", "patternProperties keys must not use lookaround or backreferences");
940
+ return new SchemaPatternRegExp(pattern, matcher);
941
+ };
942
+
943
+ // src/parsers/parse-object.ts
944
+ /**
945
+ * Build the static part of an object parser, or `undefined` when the schema
946
+ * declares no named properties.
947
+ *
948
+ * A property-less object (`properties` absent or `{}`) deliberately returns
949
+ * `undefined` so the caller can apply the open-object policy. This supersedes
950
+ * an earlier `z.object({})` fallback that was kept "or else this will break
951
+ * openai responses": collapsing `{ type: "object" }` to a strict empty object
952
+ * is the defect it was masking, and the OpenAI provider suite is part of this
953
+ * package's verification precisely so the claim stays checked.
954
+ */
955
+ function parseObjectProperties(objectSchema, ctx) {
956
+ if (!objectSchema.properties) return;
957
+ const propertyKeys = Object.keys(objectSchema.properties);
958
+ if (propertyKeys.length === 0) return;
959
+ const { backend } = ctx;
960
+ const properties = {};
961
+ for (const key of propertyKeys) {
962
+ const propJsonSchema = objectSchema.properties[key];
963
+ const propZodSchema = parseSchema(propJsonSchema, {
964
+ ...ctx,
965
+ path: [
966
+ ...ctx.path,
967
+ "properties",
968
+ key
969
+ ]
970
+ });
971
+ const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
972
+ properties[key] = applyPropertyPresence(backend, propJsonSchema, propZodSchema, required);
973
+ }
974
+ return properties;
975
+ }
976
+ /**
977
+ * Object parser for schemas carrying `patternProperties`.
978
+ *
979
+ * Every key is routed to exactly the schemas that apply to it — each matching
980
+ * pattern, and `additionalProperties` only when no pattern and no named
981
+ * property claims the key. A catch-all union would instead let a key sneak past
982
+ * its own pattern by satisfying an unrelated one.
983
+ */
984
+ function parseDynamicKeyObject(normalizedSchema, shape, additionalProperties, ctx) {
985
+ const { backend } = ctx;
986
+ const patterns = Object.entries(normalizedSchema.patternProperties ?? {}).map(([pattern, schema]) => ({
987
+ regex: compilePattern("patternProperties", pattern, ctx),
988
+ parser: parseSchema(schema, {
989
+ ...ctx,
990
+ path: [
991
+ ...ctx.path,
992
+ "patternProperties",
993
+ pattern
994
+ ]
995
+ })
996
+ }));
997
+ const declaredKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
998
+ const rejectsUnmatched = additionalProperties !== void 0 && backend.isNever(additionalProperties) || additionalProperties === void 0 && declaredKeys.size > 0;
999
+ const validatesUnmatched = additionalProperties !== void 0 && !backend.isNever(additionalProperties) && normalizedSchema.additionalProperties !== true;
1000
+ const base = backend.object(shape ?? {}, { kind: "loose" });
1001
+ return backend.rewrite(base, (value, issues) => {
1002
+ const result = { ...value };
1003
+ const unrecognizedKeys = [];
1004
+ for (const key of Object.keys(value)) {
1005
+ const matching = patterns.filter(({ regex }) => regex.test(key));
1006
+ for (const { parser } of matching) {
1007
+ const parsed = backend.run(parser, value[key]);
1008
+ if (!parsed.success) issues.custom(`Invalid input: key "${key}" must match its patternProperties schema`, {
1009
+ path: [key],
1010
+ params: { issues: parsed.failure.issues }
1011
+ });
1012
+ else if (!declaredKeys.has(key)) result[key] = parsed.data;
1013
+ }
1014
+ if (matching.length > 0 || declaredKeys.has(key)) continue;
1015
+ if (rejectsUnmatched) unrecognizedKeys.push(key);
1016
+ else if (validatesUnmatched) {
1017
+ const parsed = backend.run(additionalProperties, value[key]);
1018
+ if (!parsed.success) issues.custom(`Invalid input: key "${key}" must match the additionalProperties schema`, {
1019
+ path: [key],
1020
+ params: { issues: parsed.failure.issues }
1021
+ });
1022
+ else result[key] = parsed.data;
1023
+ }
1024
+ }
1025
+ if (unrecognizedKeys.length > 0) issues.unrecognizedKeys(unrecognizedKeys, `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`);
1026
+ return result;
1027
+ });
1028
+ }
1029
+ function parseObject(objectSchema, ctx) {
1030
+ const { backend } = ctx;
1031
+ const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
1032
+ const normalizedSchema = objectSchema.type === "object" ? objectSchema : {
1033
+ ...objectSchema,
1034
+ type: "object"
1035
+ };
1036
+ const shape = parseObjectProperties(normalizedSchema, ctx);
1037
+ const additionalProperties = normalizedSchema.additionalProperties !== void 0 ? parseSchema(normalizedSchema.additionalProperties, {
1038
+ ...ctx,
1039
+ path: [...ctx.path, "additionalProperties"]
1040
+ }) : void 0;
1041
+ const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
1042
+ let output;
1043
+ if (hasPatternProperties) output = parseDynamicKeyObject(normalizedSchema, shape, additionalProperties, ctx);
1044
+ else if (shape) {
1045
+ if (additionalProperties) {
1046
+ if (backend.isNever(additionalProperties)) output = backend.object(shape, { kind: "strict" });
1047
+ else if (isAdditionalPropertiesTrue) output = backend.object(shape, { kind: "loose" });
1048
+ else output = backend.object(shape, {
1049
+ kind: "catchall",
1050
+ schema: additionalProperties
1051
+ });
1052
+ } else output = backend.object(shape, { kind: "strict" });
1053
+ } else if (additionalProperties) {
1054
+ if (backend.isNever(additionalProperties)) output = backend.object({}, { kind: "strict" });
1055
+ else if (isAdditionalPropertiesTrue) output = backend.object({}, { kind: "loose" });
1056
+ else output = backend.record(additionalProperties);
1057
+ } else output = backend.object({}, { kind: "loose" });
1058
+ if (its.an.anyOf(objectSchema)) output = backend.intersection(output, parseAnyOf({
1059
+ ...objectSchema,
1060
+ anyOf: objectSchema.anyOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
1061
+ ...x,
1062
+ type: "object"
1063
+ } : x)
1064
+ }, ctx));
1065
+ if (its.a.oneOf(objectSchema)) output = backend.intersection(output, parseOneOf({
1066
+ ...objectSchema,
1067
+ oneOf: objectSchema.oneOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
1068
+ ...x,
1069
+ type: "object"
1070
+ } : x)
1071
+ }, ctx));
1072
+ if (its.an.allOf(objectSchema)) output = backend.intersection(output, parseAllOf({
1073
+ ...objectSchema,
1074
+ allOf: objectSchema.allOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
1075
+ ...x,
1076
+ type: "object"
1077
+ } : x)
1078
+ }, ctx));
1079
+ return output;
1080
+ }
1081
+
1082
+ // src/backend/types.ts
1083
+ /** String formats the string parser asserts; every other `format` is an annotation. */
1084
+ const ASSERTED_STRING_FORMATS = [
1085
+ "email",
1086
+ "ip",
1087
+ "ipv4",
1088
+ "ipv6",
1089
+ "uri",
1090
+ "uuid",
1091
+ "date-time",
1092
+ "time",
1093
+ "date",
1094
+ "duration"
1095
+ ];
1096
+
1097
+ // src/annotations.ts
1098
+ const ASSERTED_FORMAT_SET = new Set(ASSERTED_STRING_FORMATS);
1099
+ const isAssertedStringFormat = (format) => typeof format === "string" && ASSERTED_FORMAT_SET.has(format);
1100
+ /**
1101
+ * The description text a node carries: its `description`, else its `title`,
1102
+ * followed by the `example` or `examples` it declares. `undefined` when there
1103
+ * is nothing to say.
1104
+ */
1105
+ const describeText = (jsonSchema) => {
1106
+ let description = "";
1107
+ if (jsonSchema.description) description = jsonSchema.description;
1108
+ else if (jsonSchema.title) description = jsonSchema.title;
1109
+ if (jsonSchema.example !== void 0) {
1110
+ const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
1111
+ description = description ? `${description}\n${exampleText}` : exampleText;
1112
+ } else if (jsonSchema.examples !== void 0 && Array.isArray(jsonSchema.examples)) {
1113
+ const examples = jsonSchema.examples;
1114
+ if (examples.length > 0) {
1115
+ const exampleText = examples.length === 1 ? `Example: ${JSON.stringify(examples[0])}` : `Examples:\n${examples.map((ex) => ` ${JSON.stringify(ex)}`).join("\n")}`;
1116
+ description = description ? `${description}\n${exampleText}` : exampleText;
1117
+ }
1118
+ }
1119
+ return description || void 0;
1120
+ };
1121
+ /** Whether the number parser applies its integer check to this node. */
1122
+ const isIntegerNumber = (jsonSchema) => its.a.primitive(jsonSchema, "integer") || its.a.primitive(jsonSchema, "number") && (jsonSchema.format === "int64" || jsonSchema.multipleOf === 1);
1123
+ /**
1124
+ * The JSON Schema annotations a node carries beyond what its checks imply:
1125
+ * `format`, `contentEncoding`, and `contentMediaType` verbatim, and
1126
+ * `type: "integer"` wherever the integer check applies, since that check is
1127
+ * a refinement a serializer cannot see. Everything else the serializer
1128
+ * derives from the checks themselves, or is deliberately left out.
1129
+ */
1130
+ const collectAnnotations = (jsonSchema) => {
1131
+ if ("$ref" in jsonSchema) return;
1132
+ const annotations = {};
1133
+ if (typeof jsonSchema.format === "string") annotations.format = jsonSchema.format;
1134
+ if (typeof jsonSchema.contentEncoding === "string") annotations.contentEncoding = jsonSchema.contentEncoding;
1135
+ if (typeof jsonSchema.contentMediaType === "string") annotations.contentMediaType = jsonSchema.contentMediaType;
1136
+ if (isIntegerNumber(jsonSchema)) annotations.type = "integer";
1137
+ return Object.keys(annotations).length > 0 ? annotations : void 0;
1138
+ };
1139
+
1140
+ // src/parsers/parse-string.ts
1141
+ const parseString = (jsonSchema, ctx) => {
1142
+ const { backend } = ctx;
1143
+ let zodSchema = backend.string();
1144
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, format, errorMsg) => isAssertedStringFormat(format) ? backend.stringFormat(zs, format, errorMsg) : zs);
1145
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "contentEncoding", (zs, encoding, errorMsg) => isBase64Encoding(encoding) ? backend.base64(zs, errorMsg) : zs);
1146
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "pattern", (zs, pattern, errorMsg) => backend.regex(zs, compilePattern("pattern", pattern, ctx), errorMsg));
1147
+ const errorMessages = jsonSchema.errorMessage;
1148
+ const minLength = typeof jsonSchema.minLength === "number" ? jsonSchema.minLength : typeof jsonSchema.min === "number" ? jsonSchema.min : void 0;
1149
+ const maxLength = typeof jsonSchema.maxLength === "number" ? jsonSchema.maxLength : typeof jsonSchema.max === "number" ? jsonSchema.max : void 0;
1150
+ let result = zodSchema;
1151
+ if (minLength !== void 0) result = backend.refine(result, (value) => codePointLength(value) >= minLength, errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)`);
1152
+ if (maxLength !== void 0) result = backend.refine(result, (value) => codePointLength(value) <= maxLength, errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)`);
1153
+ return result;
1154
+ };
1155
+ const codePointLength = (value) => [...value].length;
1156
+ const isBase64Encoding = (encoding) => typeof encoding === "string" && encoding.toLowerCase() === "base64";
1157
+
1158
+ // src/parsers/parse-typeless-constraints.ts
1159
+ const SCALAR_CONSTRAINT_KEYS = [
1160
+ "minLength",
1161
+ "maxLength",
1162
+ "pattern",
1163
+ "minimum",
1164
+ "maximum",
1165
+ "exclusiveMinimum",
1166
+ "exclusiveMaximum",
1167
+ "multipleOf"
1168
+ ];
1169
+ const hasTypelessScalarConstraints = (schema) => schema.type === void 0 && SCALAR_CONSTRAINT_KEYS.some((key) => schema[key] !== void 0);
1170
+ /**
1171
+ * Draft 7 applies scalar constraints to matching instance types even when the
1172
+ * schema declares no `type`: `{ "minLength": 2 }` restricts strings while
1173
+ * leaving every non-string value untouched.
1174
+ */
1175
+ const parseTypelessConstraints = (schema, ctx) => {
1176
+ const { backend } = ctx;
1177
+ const stringSchema = parseString({
1178
+ ...schema,
1179
+ type: "string"
1180
+ }, ctx);
1181
+ const numberSchema = parseNumber({
1182
+ ...schema,
1183
+ type: "number"
1184
+ }, backend);
1185
+ return backend.superRefine(backend.any(), (value, issues) => {
1186
+ const applicable = typeof value === "string" ? stringSchema : typeof value === "number" ? numberSchema : void 0;
1187
+ if (applicable === void 0) return;
1188
+ const result = backend.run(applicable, value);
1189
+ if (!result.success) issues.forward(result.failure);
1190
+ });
1191
+ };
1192
+
1193
+ // src/whole-schema-validation.ts
1194
+ const REQUIRES_WHOLE_SCHEMA_VALIDATION = /* @__PURE__ */ new Set([
1195
+ "$ref",
1196
+ "additionalItems",
1197
+ "allOf",
1198
+ "anyOf",
1199
+ "contains",
1200
+ "dependencies",
1201
+ "else",
1202
+ "if",
1203
+ "maxProperties",
1204
+ "minProperties",
1205
+ "not",
1206
+ "oneOf",
1207
+ "propertyNames",
1208
+ "then",
1209
+ "uniqueItems"
1210
+ ]);
1211
+ const TYPELESS_TYPE_SCOPED_KEYWORDS = /* @__PURE__ */ new Set([
1212
+ "properties",
1213
+ "patternProperties",
1214
+ "additionalProperties",
1215
+ "propertyNames",
1216
+ "required",
1217
+ "dependencies",
1218
+ "minProperties",
1219
+ "maxProperties",
1220
+ "items",
1221
+ "additionalItems",
1222
+ "contains",
1223
+ "minItems",
1224
+ "maxItems",
1225
+ "uniqueItems"
1226
+ ]);
1227
+ const SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
1228
+ "$defs",
1229
+ "definitions",
1230
+ "dependencies",
1231
+ "patternProperties",
1232
+ "properties"
1233
+ ]);
1234
+ const SCHEMA_ARRAY_KEYWORDS = /* @__PURE__ */ new Set([
1235
+ "allOf",
1236
+ "anyOf",
1237
+ "oneOf"
1238
+ ]);
1239
+ const SCHEMA_VALUE_KEYWORDS = /* @__PURE__ */ new Set([
1240
+ "additionalItems",
1241
+ "additionalProperties",
1242
+ "contains",
1243
+ "else",
1244
+ "if",
1245
+ "items",
1246
+ "not",
1247
+ "propertyNames",
1248
+ "then"
1249
+ ]);
1250
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1251
+ /**
1252
+ * Every object the interpreter registers as a schema, found with its own walk
1253
+ * (`dereference`): each key it does not ignore, extension locations included.
1254
+ * A `$ref` resolves only through that registry, whether it is a JSON Pointer,
1255
+ * an `$id` or an `$anchor`, so these are all the schemas the interpreter can
1256
+ * ever validate against.
1257
+ */
1258
+ function* interpreterSchemaNodes(value, path = [], seen = /* @__PURE__ */ new WeakSet()) {
1259
+ if (!isObject(value) || seen.has(value)) return;
1260
+ seen.add(value);
1261
+ yield {
1262
+ value,
1263
+ path
1264
+ };
1265
+ for (const [key, child] of Object.entries(value)) {
1266
+ if (ignoredKeyword[key]) continue;
1267
+ if (Array.isArray(child)) {
1268
+ if (schemaArrayKeyword[key]) for (const [index, nested] of child.entries()) yield* interpreterSchemaNodes(nested, [
1269
+ ...path,
1270
+ key,
1271
+ index
1272
+ ], seen);
1273
+ } else if (schemaMapKeyword[key]) {
1274
+ if (isObject(child)) for (const [name, nested] of Object.entries(child)) yield* interpreterSchemaNodes(nested, [
1275
+ ...path,
1276
+ key,
1277
+ name
1278
+ ], seen);
1279
+ } else yield* interpreterSchemaNodes(child, [...path, key], seen);
1280
+ }
1281
+ }
1282
+ const hasRequiredDefault = (schema) => {
1283
+ if (!Array.isArray(schema.required) || !isObject(schema.properties)) return false;
1284
+ return schema.required.some((name) => {
1285
+ const property = schema.properties?.[name];
1286
+ return isObject(property) && property.default !== void 0;
1287
+ });
1288
+ };
1289
+ const hasUnparsedRequiredProperty = (schema) => {
1290
+ if (!Array.isArray(schema.required)) return false;
1291
+ const declared = new Set(Object.keys(schema.properties ?? {}));
1292
+ return schema.required.some((name) => !declared.has(name));
1293
+ };
1294
+ /**
1295
+ * The native parsers preserve useful Zod structure and materialize defaults,
1296
+ * but some JSON Schema assertions cannot be represented by their first-match
1297
+ * dispatch. Only those schemas receive an authoritative Draft 7 guard.
1298
+ */
1299
+ const requiresWholeSchemaValidation = (schema, seen = /* @__PURE__ */ new WeakSet()) => {
1300
+ if (!isObject(schema) || seen.has(schema)) return false;
1301
+ seen.add(schema);
1302
+ 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;
1303
+ for (const [key, child] of Object.entries(schema)) if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
1304
+ if (Object.values(child).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
1305
+ } else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
1306
+ if (child.some((value) => requiresWholeSchemaValidation(value, seen))) return true;
1307
+ } else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
1308
+ if ((Array.isArray(child) ? child : [child]).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
1309
+ }
1310
+ return false;
1311
+ };
1312
+ /**
1313
+ * Some schemas are valid for JSON instance types that the native parser does
1314
+ * not materialize. Such a node is parsed as `z.any()` so the Draft 7 guard
1315
+ * that every one of these keywords also activates (see
1316
+ * `requiresWholeSchemaValidation`) stays the acceptance authority without
1317
+ * piping into a narrower Zod schema. The check is deliberately local: a
1318
+ * permissive descendant must not widen its enclosing parser, or sibling
1319
+ * defaults would stop materializing.
1320
+ */
1321
+ const requiresPermissiveMaterialization = (schema) => isObject(schema) && ("$ref" in schema || schema.type === void 0 && (Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || [
1322
+ "if",
1323
+ "then",
1324
+ "else",
1325
+ "not"
1326
+ ].some((key) => key in schema)));
1327
+ /**
1328
+ * The guard schema for a node nested at `path` inside `root`: the enclosing
1329
+ * document pointed at that node, so local `$ref`s resolve exactly as they do
1330
+ * for the document root. Draft 7 ignores the keywords next to `$ref`, which
1331
+ * is what lets the root's own assertions be reused as the pointer carrier.
1332
+ */
1333
+ const guardSchemaAt = (node, refs) => isObject(refs.root) && refs.path.length > 0 ? {
1334
+ ...refs.root,
1335
+ $ref: `#/${refs.path.map((part) => encodePointer(String(part))).join("/")}`
1336
+ } : node;
1337
+ /**
1338
+ * Spells each key of a `patternProperties` object with `spell`. Two keys that
1339
+ * spell the same way (`^a\_b$` and `^a_b$`) stay separate entries: the later
1340
+ * one is wrapped in a non-capturing group, which matches the same names, so
1341
+ * neither value schema is dropped. `renamed` collects every spelling that
1342
+ * differs from its key.
1343
+ */
1344
+ const patternKeyRenamer = (spell, renamed = /* @__PURE__ */ new Map()) => {
1345
+ const cache = /* @__PURE__ */ new WeakMap();
1346
+ return (patternProperties) => {
1347
+ const cached = cache.get(patternProperties);
1348
+ if (cached) return cached;
1349
+ const renames = /* @__PURE__ */ new Map();
1350
+ const used = /* @__PURE__ */ new Set();
1351
+ for (const key of Object.keys(patternProperties)) {
1352
+ let spelling = spell(key);
1353
+ while (used.has(spelling)) spelling = `(?:${spelling})`;
1354
+ used.add(spelling);
1355
+ renames.set(key, spelling);
1356
+ if (spelling !== key) renamed.set(spelling, key);
1357
+ }
1358
+ cache.set(patternProperties, renames);
1359
+ return renames;
1360
+ };
1361
+ };
1362
+ /**
1363
+ * The interpreter matches `patternProperties` keys itself, with a native
1364
+ * backtracking `RegExp`, against object keys that come from the caller. So a
1365
+ * key never reaches it as written. Instead, each validation spells it as the
1366
+ * literal set of instance keys it matches under RE2 (an anchored trie, which
1367
+ * cannot backtrack beyond the key length). Interpreter matching then agrees
1368
+ * with RE2 on every key it can see.
1369
+ *
1370
+ * Returns the RE2 matcher of each key, or `undefined` for a key that does not
1371
+ * compile in the Unicode grammar: the interpreter throws on it when reached,
1372
+ * which fails the guard closed, as it always has. A key that compiles but
1373
+ * needs a backtracking engine is rejected at conversion, as the native object
1374
+ * parser does.
1375
+ */
1376
+ const collectPatternKeyMatchers = (nodes) => {
1377
+ const matchers = /* @__PURE__ */ new Map();
1378
+ for (const { value, path } of nodes) {
1379
+ if (!isObject(value.patternProperties)) continue;
1380
+ for (const key of Object.keys(value.patternProperties)) {
1381
+ if (matchers.has(key)) continue;
1382
+ let matcher;
1383
+ try {
1384
+ matcher = createPatternMatcher(key);
1385
+ } catch {
1386
+ matcher = void 0;
1387
+ }
1388
+ if (matcher !== void 0 && matcher.kind !== "linear") {
1389
+ if (unicodeSpellingCompiles(key)) throw new InvalidPatternError("patternProperties", key, [
1390
+ ...path,
1391
+ "patternProperties",
1392
+ key
1393
+ ], "unsupported", "patternProperties keys must not use lookaround or backreferences");
1394
+ matcher = void 0;
1395
+ }
1396
+ matchers.set(key, matcher);
1397
+ }
1398
+ }
1399
+ return matchers;
1400
+ };
1401
+ /** The Unicode spelling of a key that cannot be matched with RE2. */
1402
+ const fallbackKeySpelling = (pattern) => toUnicodePattern(pattern) ?? pattern;
1403
+ const unicodeSpellingCompiles = (pattern) => {
1404
+ try {
1405
+ new RegExp(fallbackKeySpelling(pattern), "u");
1406
+ return true;
1407
+ } catch {
1408
+ return false;
1409
+ }
1410
+ };
1411
+ /** Every object key anywhere in `value`. */
1412
+ const collectInstanceKeys = (value, keys = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new WeakSet()) => {
1413
+ if (typeof value !== "object" || value === null || seen.has(value)) return keys;
1414
+ seen.add(value);
1415
+ if (Array.isArray(value)) value.forEach((item) => collectInstanceKeys(item, keys, seen));
1416
+ else for (const [key, child] of Object.entries(value)) {
1417
+ keys.add(key);
1418
+ collectInstanceKeys(child, keys, seen);
1419
+ }
1420
+ return keys;
1421
+ };
1422
+ const UNICODE_SYNTAX_CHARACTER = /[$()*+./?[\\\]^{|}]/g;
1423
+ /** Spells a trie node as a Unicode-grammar pattern over its code points. */
1424
+ const spellKeyTrie = (node) => {
1425
+ const branches = [...node.children].map(([char, child]) => {
1426
+ let spelling = char.replace(UNICODE_SYNTAX_CHARACTER, "\\$&");
1427
+ let next = child;
1428
+ while (!next.end && next.children.size === 1) {
1429
+ const [[nextChar, grandchild]] = next.children;
1430
+ spelling += nextChar.replace(UNICODE_SYNTAX_CHARACTER, "\\$&");
1431
+ next = grandchild;
1432
+ }
1433
+ return spelling + spellKeyTrie(next);
1434
+ });
1435
+ if (branches.length === 0) return "";
1436
+ if (branches.length === 1 && !node.end) return branches[0];
1437
+ return `(?:${branches.join("|")}${node.end ? "|" : ""})`;
1438
+ };
1439
+ /**
1440
+ * An anchored Unicode-grammar pattern that matches exactly `keys`. Branches of
1441
+ * a trie start with distinct characters, so matching never backtracks further
1442
+ * than the key being tested. No keys gives `[]`, which matches nothing.
1443
+ */
1444
+ const literalKeysPattern = (keys) => {
1445
+ if (keys.length === 0) return "[]";
1446
+ const root = {
1447
+ end: false,
1448
+ children: /* @__PURE__ */ new Map()
1449
+ };
1450
+ for (const key of keys) {
1451
+ let node = root;
1452
+ for (const char of key) {
1453
+ let child = node.children.get(char);
1454
+ if (!child) {
1455
+ child = {
1456
+ end: false,
1457
+ children: /* @__PURE__ */ new Map()
1458
+ };
1459
+ node.children.set(char, child);
1460
+ }
1461
+ node = child;
1462
+ }
1463
+ node.end = true;
1464
+ }
1465
+ return `^${spellKeyTrie(root)}$`;
1466
+ };
1467
+ const decodePointerSegment = (segment) => {
1468
+ try {
1469
+ return decodeURI(segment).replace(/~1/g, "/").replace(/~0/g, "~");
1470
+ } catch {
1471
+ return segment;
1472
+ }
1473
+ };
1474
+ const positionAfter = (position, key, child) => {
1475
+ if (position !== "keyword") return position === "other" ? "other" : "keyword";
1476
+ if (key === "patternProperties") return "patternKey";
1477
+ if (SCHEMA_MAP_KEYWORDS.has(key)) return "name";
1478
+ if (SCHEMA_ARRAY_KEYWORDS.has(key) || SCHEMA_VALUE_KEYWORDS.has(key) && Array.isArray(child)) return "index";
1479
+ return SCHEMA_VALUE_KEYWORDS.has(key) ? "keyword" : "other";
1480
+ };
1481
+ /**
1482
+ * A local `$ref` rewritten to address the renamed `patternProperties` keys of
1483
+ * the interpreter copy. `root` is the unrenamed document it points into. Only
1484
+ * a segment in keyword position is a keyword, so a definition that happens to
1485
+ * be named `patternProperties` is not mistaken for one.
1486
+ */
1487
+ const renameRefThroughPatternKeys = (ref, root, renamePatternKeys, schemaObjects) => {
1488
+ if (!ref.startsWith("#/")) return ref;
1489
+ let node = root;
1490
+ let position = "keyword";
1491
+ let changed = false;
1492
+ const renamed = ref.slice(2).split("/").map((segment) => {
1493
+ if (position === "other" && isObject(node) && schemaObjects.has(node)) position = "keyword";
1494
+ const key = decodePointerSegment(segment);
1495
+ let result = segment;
1496
+ if (position === "patternKey" && isObject(node)) {
1497
+ const renamedKey = renamePatternKeys(node).get(key);
1498
+ if (renamedKey !== void 0 && renamedKey !== key) {
1499
+ result = encodePointer(renamedKey);
1500
+ changed = true;
1501
+ }
1502
+ }
1503
+ const child = isObject(node) || Array.isArray(node) ? node[key] : void 0;
1504
+ position = positionAfter(position, key, child);
1505
+ node = child;
1506
+ return result;
1507
+ });
1508
+ return changed ? `#/${renamed.join("/")}` : ref;
1509
+ };
1510
+ const PATTERN_FORMAT_PREFIX = "composio-pattern:";
1511
+ /**
1512
+ * Adds `pattern` to `formats` as an interpreter format that tests it as the
1513
+ * native string parser does (legacy grammar, RE2 with a bounded fallback; see
1514
+ * `compilePattern`), and returns the format name. Returns `undefined` for a
1515
+ * pattern that does not compile at all, which the interpreter then reports as
1516
+ * it always has. `matchers` caches compiled patterns across validations.
1517
+ */
1518
+ const patternFormat = (pattern, formats, matchers) => {
1519
+ const name = `${PATTERN_FORMAT_PREFIX}${pattern}`;
1520
+ if (!formats.has(name)) {
1521
+ let matcher = matchers.get(pattern);
1522
+ if (matcher === void 0) {
1523
+ try {
1524
+ new RegExp(pattern);
1525
+ } catch {
1526
+ return;
1527
+ }
1528
+ matcher = createPatternMatcher(pattern);
1529
+ matchers.set(pattern, matcher);
1530
+ }
1531
+ const compiled = matcher;
1532
+ formats.set(name, (value) => patternMatches(compiled, value));
1533
+ }
1534
+ return name;
1535
+ };
1536
+ /**
1537
+ * Rewrites the guard's private copy of a schema into what the Draft 7
1538
+ * interpreter understands the way the native parsers do:
1539
+ *
1540
+ * - OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
1541
+ * `minimum`/`maximum`. The interpreter ignores the flag, so it receives the
1542
+ * numeric spelling the native number parser already honors.
1543
+ * - The interpreter compiles patterns natively with the `u` flag, which
1544
+ * refuses legacy syntax tool schemas use, such as `\_`, and backtracks. A
1545
+ * `pattern` becomes a format that tests it exactly like the native string
1546
+ * parser. A `patternProperties` key cannot leave the interpreter, so it is
1547
+ * respelled by `renamePatternKeys`, and local `$ref`s through a renamed key
1548
+ * follow the rename. `root` is the unmodified document those refs address.
1549
+ * `formats` collects the pattern formats.
1550
+ */
1551
+ const prepareInterpreterSchema = (value, root, formats, patternMatchers, renamePatternKeys, schemaObjects) => {
1552
+ if (value.exclusiveMinimum === true && typeof value.minimum === "number") {
1553
+ value.exclusiveMinimum = value.minimum;
1554
+ delete value.minimum;
1555
+ } else if (typeof value.exclusiveMinimum === "boolean") delete value.exclusiveMinimum;
1556
+ if (value.exclusiveMaximum === true && typeof value.maximum === "number") {
1557
+ value.exclusiveMaximum = value.maximum;
1558
+ delete value.maximum;
1559
+ } else if (typeof value.exclusiveMaximum === "boolean") delete value.exclusiveMaximum;
1560
+ if (typeof value.$ref === "string") value.$ref = renameRefThroughPatternKeys(value.$ref, root, renamePatternKeys, schemaObjects);
1561
+ const patternFormatName = typeof value.pattern === "string" ? patternFormat(value.pattern, formats, patternMatchers) : void 0;
1562
+ if (patternFormatName !== void 0) {
1563
+ delete value.pattern;
1564
+ if (value.format === void 0) value.format = patternFormatName;
1565
+ else value.allOf = [...Array.isArray(value.allOf) ? value.allOf : [], { format: patternFormatName }];
1566
+ }
1567
+ if (isObject(value.patternProperties)) {
1568
+ const renames = renamePatternKeys(value.patternProperties);
1569
+ value.patternProperties = Object.fromEntries(Object.entries(value.patternProperties).map(([pattern, schema]) => [renames.get(pattern) ?? pattern, schema]));
1570
+ }
1571
+ };
1572
+ /**
1573
+ * The Draft 7 guard for `jsonSchema`: validates a source value against the
1574
+ * complete schema with the interpreter, with patterns spelled as the native
1575
+ * parsers match them. The backend attaches it to the parsed schema so it runs
1576
+ * before defaults and other transforms.
1577
+ */
1578
+ const createWholeSchemaGuard = (jsonSchema) => {
1579
+ const patternMatchers = /* @__PURE__ */ new Map();
1580
+ const originalNodes = [...interpreterSchemaNodes(jsonSchema)];
1581
+ const schemaObjects = new WeakSet(originalNodes.map((node) => node.value));
1582
+ const keyMatchers = collectPatternKeyMatchers(originalNodes);
1583
+ const prepare = (spell) => {
1584
+ const interpreterSchema = structuredClone(jsonSchema);
1585
+ const formats = /* @__PURE__ */ new Map();
1586
+ const renamed = /* @__PURE__ */ new Map();
1587
+ const renamePatternKeys = patternKeyRenamer(spell, renamed);
1588
+ const nodes = [...interpreterSchemaNodes(interpreterSchema)];
1589
+ for (const { value } of nodes) prepareInterpreterSchema(value, jsonSchema, formats, patternMatchers, renamePatternKeys, schemaObjects);
1590
+ return {
1591
+ validator: new Validator(interpreterSchema, "7", false),
1592
+ formats,
1593
+ renamed
1594
+ };
1595
+ };
1596
+ const shared = keyMatchers.size === 0 ? prepare(fallbackKeySpelling) : void 0;
1597
+ const prepareFor = (value) => {
1598
+ if (shared) return shared;
1599
+ const instanceKeys = [...collectInstanceKeys(value)];
1600
+ const spellings = /* @__PURE__ */ new Map();
1601
+ return prepare((pattern) => {
1602
+ const cached = spellings.get(pattern);
1603
+ if (cached !== void 0) return cached;
1604
+ const matcher = keyMatchers.get(pattern);
1605
+ const spelling = matcher === void 0 ? fallbackKeySpelling(pattern) : literalKeysPattern(instanceKeys.filter((key) => patternMatches(matcher, key)));
1606
+ spellings.set(pattern, spelling);
1607
+ return spelling;
1608
+ });
1609
+ };
1610
+ return (value) => {
1611
+ let result;
1612
+ let prepared;
1613
+ try {
1614
+ prepared = prepareFor(value);
1615
+ prepared.formats.forEach((test, name) => {
1616
+ format[name] = test;
1617
+ });
1618
+ result = prepared.validator.validate(value);
1619
+ } catch (cause) {
1620
+ return `JSON Schema validation failed: ${String(cause)}`;
1621
+ } finally {
1622
+ prepared?.formats.forEach((_, name) => {
1623
+ delete format[name];
1624
+ });
1625
+ }
1626
+ if (!result.valid) {
1627
+ let error = result.errors[0]?.error ?? "Input does not satisfy the complete JSON Schema.";
1628
+ prepared.renamed.forEach((key, spelling) => {
1629
+ error = error.split(`"${spelling}"`).join(`"${key}"`);
1630
+ });
1631
+ return error;
1632
+ }
1633
+ };
1634
+ };
1635
+
1636
+ // src/parsers/parse-schema.ts
1637
+ const addDecorations = (jsonSchema, zodSchema, ctx) => {
1638
+ const description = ctx.withoutDescribes ? void 0 : describeText(jsonSchema);
1639
+ const annotations = ctx.withoutAnnotations ? void 0 : collectAnnotations(jsonSchema);
1640
+ if (description === void 0 && annotations === void 0) return zodSchema;
1641
+ return ctx.backend.decorate(zodSchema, {
1642
+ description,
1643
+ annotations
1644
+ });
1645
+ };
1646
+ const addDefaults = (jsonSchema, zodSchema, ctx) => {
1647
+ if (jsonSchema.default !== void 0) {
1648
+ if (jsonSchema.default === null) {
1649
+ if (ctx.path.some((segment) => segment === "anyOf" || segment === "oneOf") && jsonSchema.type && jsonSchema.type !== "null" && !jsonSchema.nullable) return zodSchema;
1650
+ }
1651
+ return ctx.backend.withDefault(zodSchema, jsonSchema.default);
1652
+ }
1653
+ return zodSchema;
1654
+ };
1655
+ const addAnnotations = (jsonSchema, zodSchema, ctx) => {
1656
+ if (jsonSchema.readOnly) return ctx.backend.readonly(zodSchema);
1657
+ return zodSchema;
1658
+ };
1659
+ const selectParser = (schema, ctx) => {
1660
+ if (requiresPermissiveMaterialization(schema)) return ctx.backend.attachGuard(ctx.backend.any(), createWholeSchemaGuard(guardSchemaAt(schema, ctx)));
1661
+ else if (its.a.nullable(schema)) return parseNullable(schema, ctx);
1662
+ else if (its.an.enum(schema)) return parseEnum(schema, ctx);
1663
+ else if (its.a.const(schema)) return parseConst(schema, ctx);
1664
+ else if (its.an.object(schema)) return parseObject(schema, ctx);
1665
+ else if (its.an.array(schema)) return parseArray(schema, ctx);
1666
+ else if (its.an.anyOf(schema)) return parseAnyOf(schema, ctx);
1667
+ else if (its.an.allOf(schema)) return parseAllOf(schema, ctx);
1668
+ else if (its.a.oneOf(schema)) return parseOneOf(schema, ctx);
1669
+ else if (its.a.not(schema)) return parseNot(schema, ctx);
1670
+ else if (hasTypelessScalarConstraints(schema)) return parseTypelessConstraints(schema, ctx);
1671
+ else if (its.a.multipleType(schema)) return parseMultipleType(schema, ctx);
1672
+ else if (its.a.primitive(schema, "string")) return parseString(schema, ctx);
1673
+ else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) return parseNumber(schema, ctx.backend);
1674
+ else if (its.a.primitive(schema, "boolean")) return parseBoolean(schema, ctx);
1675
+ else if (its.a.primitive(schema, "null")) return parseNull(schema, ctx);
1676
+ else if (its.a.conditional(schema)) return parseIfThenElse(schema, ctx);
1677
+ else return parseDefault(schema, ctx);
1678
+ };
1679
+ const parseSchema = (jsonSchema, ctx, blockMeta) => {
1680
+ const { backend } = ctx;
1681
+ if (typeof jsonSchema !== "object") return jsonSchema ? backend.any() : backend.never();
1682
+ if (ctx.parserOverride) {
1683
+ const custom = ctx.parserOverride(jsonSchema, ctx);
1684
+ if (backend.isSchema(custom)) return custom;
1685
+ }
1686
+ let seen = ctx.seen.get(jsonSchema);
1687
+ if (seen) {
1688
+ if (seen.r !== void 0) return seen.r;
1689
+ if (ctx.depth === void 0 || seen.n >= ctx.depth) return backend.any();
1690
+ seen.n += 1;
1691
+ } else {
1692
+ seen = {
1693
+ r: void 0,
1694
+ n: 0
1695
+ };
1696
+ ctx.seen.set(jsonSchema, seen);
1697
+ }
1698
+ let parsedZodSchema = selectParser(jsonSchema, ctx);
1699
+ if (!blockMeta) {
1700
+ parsedZodSchema = addDecorations(jsonSchema, parsedZodSchema, ctx);
1701
+ if (!ctx.withoutDefaults) parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, ctx);
1702
+ parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema, ctx);
1703
+ }
1704
+ seen.r = parsedZodSchema;
1705
+ return parsedZodSchema;
1706
+ };
1707
+
1708
+ // src/parsers/parse-object-shape.ts
1709
+ /**
1710
+ * Parses a JSON Schema object and returns the raw shape (property keys mapped to Zod types).
1711
+ * This is useful when you need ZodRawShape instead of a complete ZodObject.
1712
+ *
1713
+ * @param objectSchema - The JSON Schema object to parse
1714
+ * @param ctx - Parser context for handling nested schemas
1715
+ * @returns A Zod raw shape object
1716
+ */
1717
+ function parseObjectShape(objectSchema, ctx) {
1718
+ if (!objectSchema.properties) return {};
1719
+ const propertyKeys = Object.keys(objectSchema.properties);
1720
+ if (propertyKeys.length === 0) return {};
1721
+ const { backend } = ctx;
1722
+ const properties = {};
1723
+ for (const key of propertyKeys) {
1724
+ const propJsonSchema = objectSchema.properties[key];
1725
+ const propCtx = {
1726
+ ...ctx,
1727
+ root: ctx.root ?? objectSchema,
1728
+ path: [
1729
+ ...ctx.path,
1730
+ "properties",
1731
+ key
1732
+ ]
1733
+ };
1734
+ const parsedProperty = parseSchema(propJsonSchema, propCtx);
1735
+ const carriesGuard = ctx.parserOverride === void 0 && requiresPermissiveMaterialization(propJsonSchema);
1736
+ const propZodSchema = requiresWholeSchemaValidation(propJsonSchema) && !carriesGuard ? backend.attachGuard(parsedProperty, createWholeSchemaGuard(guardSchemaAt(propJsonSchema, propCtx))) : parsedProperty;
1737
+ const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
1738
+ properties[key] = applyPropertyPresence(backend, propJsonSchema, propZodSchema, required);
1739
+ }
1740
+ return properties;
1741
+ }
1742
+
1743
+ // src/convert.ts
1744
+ /** The two conversion entry points, bound to one backend. */
1745
+ const createConverter = (backend) => {
1746
+ const contextFor = (root, options) => ({
1747
+ path: [],
1748
+ seen: /* @__PURE__ */ new Map(),
1749
+ root,
1750
+ ...options,
1751
+ backend
1752
+ });
1753
+ const jsonSchemaToZod = (schema, options = {}) => {
1754
+ const parsedSchema = parseSchema(schema, contextFor(schema, options));
1755
+ return requiresWholeSchemaValidation(schema) ? backend.attachGuard(parsedSchema, createWholeSchemaGuard(schema)) : parsedSchema;
1756
+ };
1757
+ const jsonSchemaToZodShape = (schema, options = {}) => {
1758
+ if (typeof schema !== "object" || schema === null) return {};
1759
+ const objectSchema = schema;
1760
+ return parseObjectShape(objectSchema, contextFor(objectSchema, options));
1761
+ };
1762
+ return {
1763
+ jsonSchemaToZod,
1764
+ jsonSchemaToZodShape
1765
+ };
1766
+ };
1767
+
1768
+ export { composeGuards as a, buildTuple as i, InvalidPatternError as n, run as o, applyObjectPolicy as r, withPath as s, createConverter as t };