@composio/json-schema-to-zod 0.3.3-beta.0 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +812 -30
- package/package.json +6 -5
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ZodTypeAny, z } from "zod/v3";
|
|
2
|
+
import { RE2JS } from "re2js";
|
|
2
3
|
//#region ../../../node_modules/.pnpm/@types+json-schema@7.0.15/node_modules/@types/json-schema/index.d.ts
|
|
3
4
|
// ==================================================================================================
|
|
4
5
|
// JSON Schema Draft 07
|
|
@@ -206,7 +207,7 @@ type SimpleZodRawShape = Record<string, ZodTypeAny>;
|
|
|
206
207
|
export declare const jsonSchemaToZodShape: (schema: JsonSchema, options?: JsonSchemaToZodOptions) => SimpleZodRawShape;
|
|
207
208
|
//#endregion
|
|
208
209
|
//#region src/utils/compile-pattern.d.ts
|
|
209
|
-
type InvalidPatternReason = 'syntax' | 'too-long';
|
|
210
|
+
type InvalidPatternReason = 'syntax' | 'too-long' | 'unsupported';
|
|
210
211
|
/**
|
|
211
212
|
* Raised at conversion time when a schema `pattern` cannot be turned into a
|
|
212
213
|
* `RegExp`. Conversion fails eagerly, in line with how this package and
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import * as z$1 from "zod/v3";
|
|
2
2
|
import { z } from "zod/v3";
|
|
3
3
|
import { dequal } from "dequal/lite";
|
|
4
|
-
import {
|
|
4
|
+
import { RE2JS } from "re2js";
|
|
5
|
+
import { Validator, encodePointer, format, ignoredKeyword, schemaArrayKeyword, schemaMapKeyword } from "@cfworker/json-schema";
|
|
5
6
|
|
|
6
7
|
//#region src/utils/half.ts
|
|
7
8
|
const half = (arr) => {
|
|
@@ -389,6 +390,436 @@ const parseOneOf = (jsonSchema, refs) => {
|
|
|
389
390
|
});
|
|
390
391
|
};
|
|
391
392
|
|
|
393
|
+
//#endregion
|
|
394
|
+
//#region src/utils/unicode-pattern.ts
|
|
395
|
+
const compilesAsUnicode = (pattern) => {
|
|
396
|
+
try {
|
|
397
|
+
new RegExp(pattern, "u");
|
|
398
|
+
return true;
|
|
399
|
+
} catch {
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const REGEX_SYNTAX_CHARACTERS = /* @__PURE__ */ new Set("^$\\.*+?()[]{}|/");
|
|
404
|
+
const CHARACTER_CLASS_ESCAPES = /* @__PURE__ */ new Set("dDwWsS");
|
|
405
|
+
const CONTROL_ESCAPES$1 = /* @__PURE__ */ new Set("fnrtv");
|
|
406
|
+
const HEX_DIGIT = /^[0-9A-Fa-f]$/;
|
|
407
|
+
const QUANTIFIER = /^\{\d+(?:,\d*)?\}/;
|
|
408
|
+
const hexEscape = (code) => `\\x${code.toString(16).padStart(2, "0")}`;
|
|
409
|
+
/** Capturing group count and whether any is named, as the parser counts them. */
|
|
410
|
+
const scanGroups = (pattern) => {
|
|
411
|
+
let count = 0;
|
|
412
|
+
let named = false;
|
|
413
|
+
let inClass = false;
|
|
414
|
+
for (let index = 0; index < pattern.length; index++) {
|
|
415
|
+
const char = pattern[index];
|
|
416
|
+
if (char === "\\") index++;
|
|
417
|
+
else if (inClass) inClass = char !== "]";
|
|
418
|
+
else if (char === "[") inClass = true;
|
|
419
|
+
else if (char === "(") {
|
|
420
|
+
if (pattern[index + 1] !== "?") count++;
|
|
421
|
+
else if (pattern[index + 2] === "<" && !"=!".includes(pattern[index + 3] ?? "")) {
|
|
422
|
+
count++;
|
|
423
|
+
named = true;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
count,
|
|
429
|
+
named
|
|
430
|
+
};
|
|
431
|
+
};
|
|
432
|
+
/**
|
|
433
|
+
* A legacy octal escape (a `\` digit sequence that is not a backreference) as
|
|
434
|
+
* a hex escape. Returns the replacement and how many digits it consumed.
|
|
435
|
+
*/
|
|
436
|
+
const legacyOctalEscape = (pattern, index) => {
|
|
437
|
+
const first = pattern[index];
|
|
438
|
+
if (first === "8" || first === "9") return [first, 1];
|
|
439
|
+
const maxDigits = first <= "3" ? 3 : 2;
|
|
440
|
+
let digits = first;
|
|
441
|
+
while (digits.length < maxDigits && /^[0-7]$/.test(pattern[index + digits.length] ?? "")) digits += pattern[index + digits.length];
|
|
442
|
+
return [hexEscape(parseInt(digits, 8)), digits.length];
|
|
443
|
+
};
|
|
444
|
+
/**
|
|
445
|
+
* The interpreter compiles every pattern with the `u` flag, while
|
|
446
|
+
* `compilePattern` and the native parsers deliberately do not. This spells a
|
|
447
|
+
* pattern written for the legacy (Annex B) grammar in the Unicode grammar with
|
|
448
|
+
* the same meaning: identity escapes such as `\_`, `\:` or `\k` become the
|
|
449
|
+
* literal character, incomplete `\x`, `\u` and `\c` escapes and legacy octal
|
|
450
|
+
* escapes are spelled out, lone `{`, `}` and `]` are escaped, and a hyphen
|
|
451
|
+
* next to a class escape (`[\w-.]`), which is a literal there, is escaped.
|
|
452
|
+
*
|
|
453
|
+
* Returns `undefined` for the few legacy constructs with no Unicode spelling,
|
|
454
|
+
* such as a quantified lookahead. Matching differs only for astral
|
|
455
|
+
* characters, which `.` and negated classes treat as one character, not two.
|
|
456
|
+
*/
|
|
457
|
+
const toUnicodePattern = (pattern) => {
|
|
458
|
+
const { count: groupCount, named: hasNamedGroups } = scanGroups(pattern);
|
|
459
|
+
let rewritten = "";
|
|
460
|
+
let inClass = false;
|
|
461
|
+
let previousAtomWasClassEscape = false;
|
|
462
|
+
let index = 0;
|
|
463
|
+
while (index < pattern.length) {
|
|
464
|
+
const char = pattern[index];
|
|
465
|
+
if (char !== "\\" && inClass) {
|
|
466
|
+
if (char === "]") {
|
|
467
|
+
inClass = false;
|
|
468
|
+
rewritten += char;
|
|
469
|
+
} else if (char === "-" && (previousAtomWasClassEscape || pattern[index + 1] === "\\" && CHARACTER_CLASS_ESCAPES.has(pattern[index + 2] ?? ""))) rewritten += "\\-";
|
|
470
|
+
else rewritten += char;
|
|
471
|
+
previousAtomWasClassEscape = false;
|
|
472
|
+
index++;
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
if (char !== "\\") {
|
|
476
|
+
const quantifier = char === "{" ? QUANTIFIER.exec(pattern.slice(index)) : null;
|
|
477
|
+
if (char === "[") {
|
|
478
|
+
inClass = true;
|
|
479
|
+
const opening = pattern[index + 1] === "^" ? "[^" : "[";
|
|
480
|
+
rewritten += opening;
|
|
481
|
+
index += opening.length;
|
|
482
|
+
} else if (quantifier) {
|
|
483
|
+
rewritten += quantifier[0];
|
|
484
|
+
index += quantifier[0].length;
|
|
485
|
+
} else {
|
|
486
|
+
rewritten += char === "{" || char === "}" || char === "]" ? `\\${char}` : char;
|
|
487
|
+
index++;
|
|
488
|
+
}
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
const escaped = pattern[index + 1];
|
|
492
|
+
if (escaped === void 0) return;
|
|
493
|
+
previousAtomWasClassEscape = false;
|
|
494
|
+
if (CHARACTER_CLASS_ESCAPES.has(escaped)) {
|
|
495
|
+
previousAtomWasClassEscape = inClass;
|
|
496
|
+
rewritten += `\\${escaped}`;
|
|
497
|
+
index += 2;
|
|
498
|
+
} else if (CONTROL_ESCAPES$1.has(escaped) || REGEX_SYNTAX_CHARACTERS.has(escaped) || escaped === "b" || escaped === "B" && !inClass || escaped === "-" && inClass || escaped === "k" && hasNamedGroups && !inClass) {
|
|
499
|
+
rewritten += `\\${escaped}`;
|
|
500
|
+
index += 2;
|
|
501
|
+
} else if (escaped === "c") {
|
|
502
|
+
const letter = pattern[index + 2] ?? "";
|
|
503
|
+
if (/^[A-Za-z]$/.test(letter)) {
|
|
504
|
+
rewritten += `\\c${letter}`;
|
|
505
|
+
index += 3;
|
|
506
|
+
} else if (inClass && /^[0-9_]$/.test(letter)) {
|
|
507
|
+
rewritten += hexEscape(letter.charCodeAt(0) % 32);
|
|
508
|
+
index += 3;
|
|
509
|
+
} else {
|
|
510
|
+
rewritten += "\\\\";
|
|
511
|
+
index++;
|
|
512
|
+
}
|
|
513
|
+
} else if (escaped === "x" || escaped === "u") {
|
|
514
|
+
const length = escaped === "x" ? 2 : 4;
|
|
515
|
+
const digits = pattern.slice(index + 2, index + 2 + length);
|
|
516
|
+
if (digits.length === length && [...digits].every((digit) => HEX_DIGIT.test(digit))) {
|
|
517
|
+
rewritten += `\\${escaped}${digits}`;
|
|
518
|
+
index += 2 + length;
|
|
519
|
+
} else {
|
|
520
|
+
rewritten += escaped;
|
|
521
|
+
index += 2;
|
|
522
|
+
}
|
|
523
|
+
} else if (/^[0-9]$/.test(escaped)) {
|
|
524
|
+
const decimal = /^\d+/.exec(pattern.slice(index + 1))?.[0] ?? escaped;
|
|
525
|
+
if (escaped === "0" && !/^[0-9]$/.test(pattern[index + 2] ?? "")) {
|
|
526
|
+
rewritten += "\\0";
|
|
527
|
+
index += 2;
|
|
528
|
+
} else if (!inClass && escaped !== "0" && Number(decimal) <= groupCount) {
|
|
529
|
+
rewritten += `\\${decimal}`;
|
|
530
|
+
index += 1 + decimal.length;
|
|
531
|
+
} else {
|
|
532
|
+
const [replacement, consumed] = legacyOctalEscape(pattern, index + 1);
|
|
533
|
+
rewritten += replacement;
|
|
534
|
+
index += 1 + consumed;
|
|
535
|
+
}
|
|
536
|
+
} else {
|
|
537
|
+
rewritten += escaped;
|
|
538
|
+
index += 2;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return compilesAsUnicode(rewritten) ? rewritten : void 0;
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
//#endregion
|
|
545
|
+
//#region src/utils/linear-pattern.ts
|
|
546
|
+
/**
|
|
547
|
+
* ECMAScript `\s`: the characters it matches, spelled for an RE2 class body.
|
|
548
|
+
* RE2's own `\s` is ASCII-only, so both `\s` and `\S` are spelled out.
|
|
549
|
+
*/
|
|
550
|
+
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}";
|
|
551
|
+
/** The complement of {@link WHITESPACE}, usable inside another class. */
|
|
552
|
+
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}";
|
|
553
|
+
const ANY_CHARACTER = "\\x{0}-\\x{10FFFF}";
|
|
554
|
+
/** ECMAScript `.` without the `s` flag excludes every line terminator, not just `\n`. */
|
|
555
|
+
const DOT = "[^\\n\\r\\x{2028}\\x{2029}]";
|
|
556
|
+
const SYNTAX_CHARACTERS = /* @__PURE__ */ new Set("^$\\.*+?()[]{}|/-");
|
|
557
|
+
const CONTROL_ESCAPES = /* @__PURE__ */ new Set("fnrtv");
|
|
558
|
+
const PASSTHROUGH_CLASS_ESCAPES = /* @__PURE__ */ new Set("dDwW");
|
|
559
|
+
const codePoint = (code) => `\\x{${code.toString(16).toUpperCase()}}`;
|
|
560
|
+
/** Thrown inside the translator for constructs RE2 cannot express. */
|
|
561
|
+
var Unsupported = class extends Error {};
|
|
562
|
+
/**
|
|
563
|
+
* Reads one escape at `pattern[index] === '\\'` that is valid in both a class
|
|
564
|
+
* and the top level, returning its RE2 spelling and the index after it.
|
|
565
|
+
*/
|
|
566
|
+
const readEscape = (pattern, index, inClass) => {
|
|
567
|
+
const escaped = pattern[index + 1] ?? "";
|
|
568
|
+
if (PASSTHROUGH_CLASS_ESCAPES.has(escaped) || CONTROL_ESCAPES.has(escaped)) return [`\\${escaped}`, index + 2];
|
|
569
|
+
if (escaped === "s") return [inClass ? WHITESPACE : `[${WHITESPACE}]`, index + 2];
|
|
570
|
+
if (escaped === "S") return [inClass ? NON_WHITESPACE : `[^${WHITESPACE}]`, index + 2];
|
|
571
|
+
if (escaped === "b" || escaped === "B") return [inClass ? codePoint(8) : `\\${escaped}`, index + 2];
|
|
572
|
+
if (escaped === "0") return [codePoint(0), index + 2];
|
|
573
|
+
if (escaped === "c") return [codePoint(pattern.charCodeAt(index + 2) % 32), index + 3];
|
|
574
|
+
if (escaped === "x") return [codePoint(parseInt(pattern.slice(index + 2, index + 4), 16)), index + 4];
|
|
575
|
+
if (escaped === "u") {
|
|
576
|
+
if (pattern[index + 2] === "{") {
|
|
577
|
+
const end = pattern.indexOf("}", index + 3);
|
|
578
|
+
return [codePoint(parseInt(pattern.slice(index + 3, end), 16)), end + 1];
|
|
579
|
+
}
|
|
580
|
+
const unit = parseInt(pattern.slice(index + 2, index + 6), 16);
|
|
581
|
+
const low = /^\\u([Dd][C-Fc-f][0-9A-Fa-f]{2})/.exec(pattern.slice(index + 6));
|
|
582
|
+
if (unit >= 55296 && unit <= 56319 && low) {
|
|
583
|
+
const combined = (unit - 55296) * 1024 + (parseInt(low[1], 16) - 56320) + 65536;
|
|
584
|
+
return [codePoint(combined), index + 12];
|
|
585
|
+
}
|
|
586
|
+
return [codePoint(unit), index + 6];
|
|
587
|
+
}
|
|
588
|
+
if (SYNTAX_CHARACTERS.has(escaped)) return [`\\${escaped}`, index + 2];
|
|
589
|
+
throw new Unsupported();
|
|
590
|
+
};
|
|
591
|
+
/** Translates a class starting at `pattern[index] === '['`. */
|
|
592
|
+
const readClass = (pattern, index) => {
|
|
593
|
+
let cursor = index + 1;
|
|
594
|
+
const negated = pattern[cursor] === "^";
|
|
595
|
+
if (negated) cursor++;
|
|
596
|
+
if (pattern[cursor] === "]") return [negated ? `[${ANY_CHARACTER}]` : `[^${ANY_CHARACTER}]`, cursor + 1];
|
|
597
|
+
let body = "";
|
|
598
|
+
while (pattern[cursor] !== "]") {
|
|
599
|
+
const char = pattern[cursor];
|
|
600
|
+
if (char === "\\") {
|
|
601
|
+
const [spelled, next] = readEscape(pattern, cursor, true);
|
|
602
|
+
body += spelled;
|
|
603
|
+
cursor = next;
|
|
604
|
+
} else {
|
|
605
|
+
body += char === "[" || char === "^" ? `\\${char}` : char;
|
|
606
|
+
cursor += char.length;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
return [`[${negated ? "^" : ""}${body}]`, cursor + 1];
|
|
610
|
+
};
|
|
611
|
+
/**
|
|
612
|
+
* Translates a pattern written in the ECMAScript Unicode (`u` flag) grammar
|
|
613
|
+
* into RE2 syntax with the same meaning. The input must already compile with
|
|
614
|
+
* the `u` flag. Returns `undefined` for constructs that need a backtracking
|
|
615
|
+
* engine (lookaround, backreferences) or that RE2 spells differently.
|
|
616
|
+
*/
|
|
617
|
+
const unicodePatternToRe2 = (pattern) => {
|
|
618
|
+
let result = "";
|
|
619
|
+
let index = 0;
|
|
620
|
+
try {
|
|
621
|
+
while (index < pattern.length) {
|
|
622
|
+
const char = pattern[index];
|
|
623
|
+
if (char === "\\") {
|
|
624
|
+
const [spelled, next] = readEscape(pattern, index, false);
|
|
625
|
+
result += spelled;
|
|
626
|
+
index = next;
|
|
627
|
+
} else if (char === "[") {
|
|
628
|
+
const [spelled, next] = readClass(pattern, index);
|
|
629
|
+
result += spelled;
|
|
630
|
+
index = next;
|
|
631
|
+
} else if (char === ".") {
|
|
632
|
+
result += DOT;
|
|
633
|
+
index++;
|
|
634
|
+
} else if (char === "(" && pattern[index + 1] === "?") {
|
|
635
|
+
if (pattern[index + 2] === ":") {
|
|
636
|
+
result += "(?:";
|
|
637
|
+
index += 3;
|
|
638
|
+
} else if (pattern[index + 2] === "<" && !"=!".includes(pattern[index + 3] ?? "")) {
|
|
639
|
+
result += "(";
|
|
640
|
+
index = pattern.indexOf(">", index) + 1;
|
|
641
|
+
} else throw new Unsupported();
|
|
642
|
+
} else {
|
|
643
|
+
result += char;
|
|
644
|
+
index++;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
} catch (error) {
|
|
648
|
+
if (error instanceof Unsupported) return;
|
|
649
|
+
throw error;
|
|
650
|
+
}
|
|
651
|
+
return result;
|
|
652
|
+
};
|
|
653
|
+
/**
|
|
654
|
+
* Compiles a Unicode-grammar pattern for RE2JS, whose matching time is linear
|
|
655
|
+
* in the input for every pattern. Returns `undefined` when RE2 cannot express
|
|
656
|
+
* the pattern.
|
|
657
|
+
*/
|
|
658
|
+
const compileLinearPattern = (unicodePattern) => {
|
|
659
|
+
const re2 = unicodePatternToRe2(unicodePattern);
|
|
660
|
+
if (re2 === void 0) return;
|
|
661
|
+
try {
|
|
662
|
+
return RE2JS.compile(re2);
|
|
663
|
+
} catch {
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
};
|
|
667
|
+
/** A quantifier whose range (maximum minus minimum) exceeds this counts as unbounded. */
|
|
668
|
+
const LARGE_QUANTIFIER_RANGE = 16;
|
|
669
|
+
/** Bound on the product of the ranges of all small variable quantifiers. */
|
|
670
|
+
const MAX_SMALL_QUANTIFIER_PRODUCT = 64;
|
|
671
|
+
/** Absolute explicit repeat bounds, including repetitions of zero-width assertions. */
|
|
672
|
+
const MAX_FALLBACK_REPEAT_COUNT = 64;
|
|
673
|
+
/** Bound on the polynomial degree of the backtracking search in the input length. */
|
|
674
|
+
const MAX_BACKTRACKING_DEGREE = 2;
|
|
675
|
+
const BRACE_QUANTIFIER = /^\{(\d+)(,(\d*))?\}/;
|
|
676
|
+
/**
|
|
677
|
+
* Whether a pattern that RE2 cannot run (it needs lookaround or a
|
|
678
|
+
* backreference) is still safe for the native backtracking engine on short
|
|
679
|
+
* input. Deliberately conservative, since only such patterns reach it:
|
|
680
|
+
*
|
|
681
|
+
* - no backreferences;
|
|
682
|
+
* - no quantified group that contains a quantifier or an alternation, the
|
|
683
|
+
* shapes behind exponential backtracking (`(a+)+`, `(a|a)*`);
|
|
684
|
+
* - no lookaround nested in another lookaround;
|
|
685
|
+
* - explicit repetition bounds are capped, including fixed assertions;
|
|
686
|
+
* - the search is at most quadratic: one degree for an unanchored start, plus
|
|
687
|
+
* the number of unbounded quantifiers at the top level, plus the largest
|
|
688
|
+
* number inside a single lookaround (lookarounds are atomic, so they add
|
|
689
|
+
* rather than multiply);
|
|
690
|
+
* - small variable quantifiers (`?`, `{1,3}`) and alternations multiply the
|
|
691
|
+
* work by a bounded constant (`(?:a|aa)(?:a|aa)...b` is exponential without
|
|
692
|
+
* any quantifier).
|
|
693
|
+
* A leading anchor removes search work only without a top-level alternative.
|
|
694
|
+
*
|
|
695
|
+
* Callers still bound the input length, which keeps the quadratic case cheap.
|
|
696
|
+
*/
|
|
697
|
+
const isSafeForBacktracking = (pattern) => {
|
|
698
|
+
const hasNamedGroup = /\(\?<(?![=!])/.test(pattern);
|
|
699
|
+
const newGroup = (lookaround) => ({
|
|
700
|
+
lookaround,
|
|
701
|
+
quantified: false,
|
|
702
|
+
alternation: false,
|
|
703
|
+
branches: 1
|
|
704
|
+
});
|
|
705
|
+
const stack = [newGroup(false)];
|
|
706
|
+
let topLevelLarge = 0;
|
|
707
|
+
let lookaroundLarge = 0;
|
|
708
|
+
let maxLookaroundLarge = 0;
|
|
709
|
+
let smallProduct = 1;
|
|
710
|
+
let lastAtomGroup;
|
|
711
|
+
let index = 0;
|
|
712
|
+
const insideLookaround = () => stack.some((group) => group.lookaround);
|
|
713
|
+
const multiply = (factor) => {
|
|
714
|
+
smallProduct *= factor;
|
|
715
|
+
return smallProduct <= MAX_SMALL_QUANTIFIER_PRODUCT;
|
|
716
|
+
};
|
|
717
|
+
while (index < pattern.length) {
|
|
718
|
+
const char = pattern[index];
|
|
719
|
+
const current = stack[stack.length - 1];
|
|
720
|
+
let quantifierLength = 0;
|
|
721
|
+
let range = 0;
|
|
722
|
+
if (char === "*" || char === "+") {
|
|
723
|
+
quantifierLength = 1;
|
|
724
|
+
range = Infinity;
|
|
725
|
+
} else if (char === "?") {
|
|
726
|
+
quantifierLength = 1;
|
|
727
|
+
range = 1;
|
|
728
|
+
} else if (char === "{") {
|
|
729
|
+
const brace = BRACE_QUANTIFIER.exec(pattern.slice(index));
|
|
730
|
+
if (brace) {
|
|
731
|
+
quantifierLength = brace[0].length;
|
|
732
|
+
const minimum = Number(brace[1]);
|
|
733
|
+
const maximum = brace[2] === void 0 ? minimum : Number(brace[3]);
|
|
734
|
+
if (minimum > MAX_FALLBACK_REPEAT_COUNT || brace[3] !== "" && maximum > MAX_FALLBACK_REPEAT_COUNT) return false;
|
|
735
|
+
if (brace[2] !== void 0) range = brace[3] === "" ? Infinity : Number(brace[3]) - Number(brace[1]);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (quantifierLength > 0) {
|
|
739
|
+
if (lastAtomGroup && (lastAtomGroup.quantified || lastAtomGroup.alternation)) return false;
|
|
740
|
+
if (range > LARGE_QUANTIFIER_RANGE) {
|
|
741
|
+
if (insideLookaround()) maxLookaroundLarge = Math.max(maxLookaroundLarge, ++lookaroundLarge);
|
|
742
|
+
else topLevelLarge++;
|
|
743
|
+
} else if (range > 0 && !multiply(range + 1)) return false;
|
|
744
|
+
current.quantified = true;
|
|
745
|
+
index += quantifierLength;
|
|
746
|
+
if (pattern[index] === "?") index++;
|
|
747
|
+
lastAtomGroup = void 0;
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
lastAtomGroup = void 0;
|
|
751
|
+
if (char === "\\") {
|
|
752
|
+
const escaped = pattern[index + 1] ?? "";
|
|
753
|
+
if (/^[1-9]$/.test(escaped) || escaped === "k" && hasNamedGroup) return false;
|
|
754
|
+
index += 2;
|
|
755
|
+
} else if (char === "[") {
|
|
756
|
+
index++;
|
|
757
|
+
while (index < pattern.length && pattern[index] !== "]") index += pattern[index] === "\\" ? 2 : 1;
|
|
758
|
+
index++;
|
|
759
|
+
} else if (char === "(") {
|
|
760
|
+
const lookaround = pattern[index + 1] === "?" && ("=!".includes(pattern[index + 2] ?? "") || pattern[index + 2] === "<" && "=!".includes(pattern[index + 3] ?? ""));
|
|
761
|
+
if (lookaround) {
|
|
762
|
+
if (insideLookaround()) return false;
|
|
763
|
+
lookaroundLarge = 0;
|
|
764
|
+
}
|
|
765
|
+
stack.push(newGroup(lookaround));
|
|
766
|
+
index++;
|
|
767
|
+
if (pattern[index] === "?") index += lookaround && pattern[index + 1] === "<" ? 3 : 2;
|
|
768
|
+
} else if (char === ")") {
|
|
769
|
+
const closed = stack.length > 1 ? stack.pop() : current;
|
|
770
|
+
if (!multiply(closed.branches)) return false;
|
|
771
|
+
const parent = stack[stack.length - 1];
|
|
772
|
+
parent.quantified ||= closed.quantified;
|
|
773
|
+
parent.alternation ||= closed.alternation;
|
|
774
|
+
lastAtomGroup = closed;
|
|
775
|
+
index++;
|
|
776
|
+
} else {
|
|
777
|
+
if (char === "|") {
|
|
778
|
+
current.alternation = true;
|
|
779
|
+
current.branches++;
|
|
780
|
+
}
|
|
781
|
+
index++;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
if (!multiply(stack[0].branches)) return false;
|
|
785
|
+
return (pattern.startsWith("^") && stack[0].branches === 1 ? 0 : 1) + topLevelLarge + maxLookaroundLarge <= MAX_BACKTRACKING_DEGREE;
|
|
786
|
+
};
|
|
787
|
+
/**
|
|
788
|
+
* Longest input the backtracking fallback runs on. Longer input is treated as
|
|
789
|
+
* matching: skipping a constraint only widens what the schema accepts, which
|
|
790
|
+
* a hostile schema could do anyway by omitting the pattern.
|
|
791
|
+
*/
|
|
792
|
+
const MAX_BACKTRACKING_INPUT_LENGTH = 1e3;
|
|
793
|
+
/**
|
|
794
|
+
* Builds the matcher for a schema pattern in the legacy (no `u` flag) grammar
|
|
795
|
+
* the rest of this package accepts. `pattern` must already compile as a
|
|
796
|
+
* `RegExp`.
|
|
797
|
+
*/
|
|
798
|
+
const createPatternMatcher = (pattern) => {
|
|
799
|
+
const unicodePattern = toUnicodePattern(pattern);
|
|
800
|
+
const linear = unicodePattern === void 0 ? void 0 : compileLinearPattern(unicodePattern);
|
|
801
|
+
if (linear !== void 0) return {
|
|
802
|
+
kind: "linear",
|
|
803
|
+
regex: linear
|
|
804
|
+
};
|
|
805
|
+
if (isSafeForBacktracking(pattern)) return {
|
|
806
|
+
kind: "backtracking",
|
|
807
|
+
regex: new RegExp(pattern)
|
|
808
|
+
};
|
|
809
|
+
return { kind: "unenforced" };
|
|
810
|
+
};
|
|
811
|
+
/** Whether `input` satisfies the pattern behind `matcher`. */
|
|
812
|
+
const patternMatches = (matcher, input) => {
|
|
813
|
+
switch (matcher.kind) {
|
|
814
|
+
case "linear": return matcher.regex.test(input);
|
|
815
|
+
case "backtracking":
|
|
816
|
+
if (input.length > 1e3) return true;
|
|
817
|
+
matcher.regex.lastIndex = 0;
|
|
818
|
+
return matcher.regex.test(input);
|
|
819
|
+
case "unenforced": return true;
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
|
|
392
823
|
//#endregion
|
|
393
824
|
//#region src/utils/compile-pattern.ts
|
|
394
825
|
/**
|
|
@@ -421,14 +852,47 @@ var InvalidPatternError = class extends Error {
|
|
|
421
852
|
}
|
|
422
853
|
};
|
|
423
854
|
/**
|
|
855
|
+
* A schema pattern as a `RegExp` whose matching cannot be made to backtrack
|
|
856
|
+
* catastrophically. The native `source` stays intact, so JSON Schema emitted
|
|
857
|
+
* from the Zod schema still carries the original pattern for the model, while
|
|
858
|
+
* `test` and `exec` go through a {@link PatternMatcher}: RE2 where it can run
|
|
859
|
+
* the pattern, otherwise a statically vetted, length-bounded native match, or
|
|
860
|
+
* no check at all.
|
|
861
|
+
*/
|
|
862
|
+
var SchemaPatternRegExp = class extends RegExp {
|
|
863
|
+
matcher;
|
|
864
|
+
constructor(pattern, matcher = createPatternMatcher(pattern)) {
|
|
865
|
+
super(pattern);
|
|
866
|
+
this.matcher = matcher;
|
|
867
|
+
}
|
|
868
|
+
test(input) {
|
|
869
|
+
return patternMatches(this.matcher, String(input));
|
|
870
|
+
}
|
|
871
|
+
exec(input) {
|
|
872
|
+
const string = String(input);
|
|
873
|
+
switch (this.matcher.kind) {
|
|
874
|
+
case "linear": return this.matcher.regex.exec(string);
|
|
875
|
+
case "backtracking": return patternMatches(this.matcher, string) ? this.matcher.regex.exec(string) : null;
|
|
876
|
+
case "unenforced": return null;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
static get [Symbol.species]() {
|
|
880
|
+
return RegExp;
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
/**
|
|
424
884
|
* Compile a schema pattern, rejecting anything that does not compile or that
|
|
425
885
|
* exceeds {@link MAX_PATTERN_LENGTH}.
|
|
426
886
|
*
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
887
|
+
* Matching is protected against catastrophic backtracking (ReDoS): tool
|
|
888
|
+
* arguments come from a model that may be steered by untrusted content, and
|
|
889
|
+
* object keys are as attacker-influenced as values. Patterns run on RE2,
|
|
890
|
+
* which is linear-time. A `pattern` RE2 cannot express (lookaround) falls back
|
|
891
|
+
* to the native engine only when it passes a conservative static check, and
|
|
892
|
+
* only on bounded input; otherwise it is left unenforced, which widens the
|
|
893
|
+
* schema no further than omitting the pattern would. A `patternProperties`
|
|
894
|
+
* key decides which schema applies to a property, so it is never silently
|
|
895
|
+
* skipped: one RE2 cannot express is rejected at conversion.
|
|
432
896
|
*
|
|
433
897
|
* No `u` flag is passed: existing tool schemas rely on identity escapes that
|
|
434
898
|
* Unicode mode refuses, and the goal here is to fail on defects, not to
|
|
@@ -442,11 +906,14 @@ const compilePattern = (keyword, pattern, refs) => {
|
|
|
442
906
|
];
|
|
443
907
|
if (pattern.length > 1024) throw new InvalidPatternError(keyword, pattern, path, "too-long", `pattern exceeds ${MAX_PATTERN_LENGTH} characters`);
|
|
444
908
|
try {
|
|
445
|
-
|
|
909
|
+
new RegExp(pattern);
|
|
446
910
|
} catch (cause) {
|
|
447
911
|
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
448
912
|
throw new InvalidPatternError(keyword, pattern, path, "syntax", detail, { cause });
|
|
449
913
|
}
|
|
914
|
+
const matcher = createPatternMatcher(pattern);
|
|
915
|
+
if (keyword === "patternProperties" && matcher.kind !== "linear") throw new InvalidPatternError(keyword, pattern, path, "unsupported", "patternProperties keys must not use lookaround or backreferences");
|
|
916
|
+
return new SchemaPatternRegExp(pattern, matcher);
|
|
450
917
|
};
|
|
451
918
|
|
|
452
919
|
//#endregion
|
|
@@ -734,6 +1201,37 @@ const SCHEMA_VALUE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
|
734
1201
|
"then"
|
|
735
1202
|
]);
|
|
736
1203
|
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1204
|
+
/**
|
|
1205
|
+
* Every object the interpreter registers as a schema, found with its own walk
|
|
1206
|
+
* (`dereference`): each key it does not ignore, extension locations included.
|
|
1207
|
+
* A `$ref` resolves only through that registry, whether it is a JSON Pointer,
|
|
1208
|
+
* an `$id` or an `$anchor`, so these are all the schemas the interpreter can
|
|
1209
|
+
* ever validate against.
|
|
1210
|
+
*/
|
|
1211
|
+
function* interpreterSchemaNodes(value, path = [], seen = /* @__PURE__ */ new WeakSet()) {
|
|
1212
|
+
if (!isObject(value) || seen.has(value)) return;
|
|
1213
|
+
seen.add(value);
|
|
1214
|
+
yield {
|
|
1215
|
+
value,
|
|
1216
|
+
path
|
|
1217
|
+
};
|
|
1218
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1219
|
+
if (ignoredKeyword[key]) continue;
|
|
1220
|
+
if (Array.isArray(child)) {
|
|
1221
|
+
if (schemaArrayKeyword[key]) for (const [index, nested] of child.entries()) yield* interpreterSchemaNodes(nested, [
|
|
1222
|
+
...path,
|
|
1223
|
+
key,
|
|
1224
|
+
index
|
|
1225
|
+
], seen);
|
|
1226
|
+
} else if (schemaMapKeyword[key]) {
|
|
1227
|
+
if (isObject(child)) for (const [name, nested] of Object.entries(child)) yield* interpreterSchemaNodes(nested, [
|
|
1228
|
+
...path,
|
|
1229
|
+
key,
|
|
1230
|
+
name
|
|
1231
|
+
], seen);
|
|
1232
|
+
} else yield* interpreterSchemaNodes(child, [...path, key], seen);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
737
1235
|
const hasRequiredDefault = (schema) => {
|
|
738
1236
|
if (!Array.isArray(schema.required) || !isObject(schema.properties)) return false;
|
|
739
1237
|
return schema.required.some((name) => {
|
|
@@ -790,13 +1288,220 @@ const guardSchemaAt = (node, refs) => isObject(refs.root) && refs.path.length >
|
|
|
790
1288
|
$ref: `#/${refs.path.map((part) => encodePointer(String(part))).join("/")}`
|
|
791
1289
|
} : node;
|
|
792
1290
|
/**
|
|
793
|
-
*
|
|
794
|
-
*
|
|
795
|
-
*
|
|
1291
|
+
* Spells each key of a `patternProperties` object with `spell`. Two keys that
|
|
1292
|
+
* spell the same way (`^a\_b$` and `^a_b$`) stay separate entries: the later
|
|
1293
|
+
* one is wrapped in a non-capturing group, which matches the same names, so
|
|
1294
|
+
* neither value schema is dropped. `renamed` collects every spelling that
|
|
1295
|
+
* differs from its key.
|
|
796
1296
|
*/
|
|
797
|
-
const
|
|
798
|
-
|
|
1297
|
+
const patternKeyRenamer = (spell, renamed = /* @__PURE__ */ new Map()) => {
|
|
1298
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
1299
|
+
return (patternProperties) => {
|
|
1300
|
+
const cached = cache.get(patternProperties);
|
|
1301
|
+
if (cached) return cached;
|
|
1302
|
+
const renames = /* @__PURE__ */ new Map();
|
|
1303
|
+
const used = /* @__PURE__ */ new Set();
|
|
1304
|
+
for (const key of Object.keys(patternProperties)) {
|
|
1305
|
+
let spelling = spell(key);
|
|
1306
|
+
while (used.has(spelling)) spelling = `(?:${spelling})`;
|
|
1307
|
+
used.add(spelling);
|
|
1308
|
+
renames.set(key, spelling);
|
|
1309
|
+
if (spelling !== key) renamed.set(spelling, key);
|
|
1310
|
+
}
|
|
1311
|
+
cache.set(patternProperties, renames);
|
|
1312
|
+
return renames;
|
|
1313
|
+
};
|
|
1314
|
+
};
|
|
1315
|
+
/**
|
|
1316
|
+
* The interpreter matches `patternProperties` keys itself, with a native
|
|
1317
|
+
* backtracking `RegExp`, against object keys that come from the caller. So a
|
|
1318
|
+
* key never reaches it as written. Instead, each validation spells it as the
|
|
1319
|
+
* literal set of instance keys it matches under RE2 (an anchored trie, which
|
|
1320
|
+
* cannot backtrack beyond the key length). Interpreter matching then agrees
|
|
1321
|
+
* with RE2 on every key it can see.
|
|
1322
|
+
*
|
|
1323
|
+
* Returns the RE2 matcher of each key, or `undefined` for a key that does not
|
|
1324
|
+
* compile in the Unicode grammar: the interpreter throws on it when reached,
|
|
1325
|
+
* which fails the guard closed, as it always has. A key that compiles but
|
|
1326
|
+
* needs a backtracking engine is rejected at conversion, as the native object
|
|
1327
|
+
* parser does.
|
|
1328
|
+
*/
|
|
1329
|
+
const collectPatternKeyMatchers = (nodes) => {
|
|
1330
|
+
const matchers = /* @__PURE__ */ new Map();
|
|
1331
|
+
for (const { value, path } of nodes) {
|
|
1332
|
+
if (!isObject(value.patternProperties)) continue;
|
|
1333
|
+
for (const key of Object.keys(value.patternProperties)) {
|
|
1334
|
+
if (matchers.has(key)) continue;
|
|
1335
|
+
let matcher;
|
|
1336
|
+
try {
|
|
1337
|
+
matcher = createPatternMatcher(key);
|
|
1338
|
+
} catch {
|
|
1339
|
+
matcher = void 0;
|
|
1340
|
+
}
|
|
1341
|
+
if (matcher !== void 0 && matcher.kind !== "linear") {
|
|
1342
|
+
if (unicodeSpellingCompiles(key)) throw new InvalidPatternError("patternProperties", key, [
|
|
1343
|
+
...path,
|
|
1344
|
+
"patternProperties",
|
|
1345
|
+
key
|
|
1346
|
+
], "unsupported", "patternProperties keys must not use lookaround or backreferences");
|
|
1347
|
+
matcher = void 0;
|
|
1348
|
+
}
|
|
1349
|
+
matchers.set(key, matcher);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return matchers;
|
|
1353
|
+
};
|
|
1354
|
+
/** The Unicode spelling of a key that cannot be matched with RE2. */
|
|
1355
|
+
const fallbackKeySpelling = (pattern) => toUnicodePattern(pattern) ?? pattern;
|
|
1356
|
+
const unicodeSpellingCompiles = (pattern) => {
|
|
1357
|
+
try {
|
|
1358
|
+
new RegExp(fallbackKeySpelling(pattern), "u");
|
|
1359
|
+
return true;
|
|
1360
|
+
} catch {
|
|
1361
|
+
return false;
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
/** Every object key anywhere in `value`. */
|
|
1365
|
+
const collectInstanceKeys = (value, keys = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new WeakSet()) => {
|
|
1366
|
+
if (typeof value !== "object" || value === null || seen.has(value)) return keys;
|
|
799
1367
|
seen.add(value);
|
|
1368
|
+
if (Array.isArray(value)) value.forEach((item) => collectInstanceKeys(item, keys, seen));
|
|
1369
|
+
else for (const [key, child] of Object.entries(value)) {
|
|
1370
|
+
keys.add(key);
|
|
1371
|
+
collectInstanceKeys(child, keys, seen);
|
|
1372
|
+
}
|
|
1373
|
+
return keys;
|
|
1374
|
+
};
|
|
1375
|
+
const UNICODE_SYNTAX_CHARACTER = /[$()*+./?[\\\]^{|}]/g;
|
|
1376
|
+
/** Spells a trie node as a Unicode-grammar pattern over its code points. */
|
|
1377
|
+
const spellKeyTrie = (node) => {
|
|
1378
|
+
const branches = [...node.children].map(([char, child]) => {
|
|
1379
|
+
let spelling = char.replace(UNICODE_SYNTAX_CHARACTER, "\\$&");
|
|
1380
|
+
let next = child;
|
|
1381
|
+
while (!next.end && next.children.size === 1) {
|
|
1382
|
+
const [[nextChar, grandchild]] = next.children;
|
|
1383
|
+
spelling += nextChar.replace(UNICODE_SYNTAX_CHARACTER, "\\$&");
|
|
1384
|
+
next = grandchild;
|
|
1385
|
+
}
|
|
1386
|
+
return spelling + spellKeyTrie(next);
|
|
1387
|
+
});
|
|
1388
|
+
if (branches.length === 0) return "";
|
|
1389
|
+
if (branches.length === 1 && !node.end) return branches[0];
|
|
1390
|
+
return `(?:${branches.join("|")}${node.end ? "|" : ""})`;
|
|
1391
|
+
};
|
|
1392
|
+
/**
|
|
1393
|
+
* An anchored Unicode-grammar pattern that matches exactly `keys`. Branches of
|
|
1394
|
+
* a trie start with distinct characters, so matching never backtracks further
|
|
1395
|
+
* than the key being tested. No keys gives `[]`, which matches nothing.
|
|
1396
|
+
*/
|
|
1397
|
+
const literalKeysPattern = (keys) => {
|
|
1398
|
+
if (keys.length === 0) return "[]";
|
|
1399
|
+
const root = {
|
|
1400
|
+
end: false,
|
|
1401
|
+
children: /* @__PURE__ */ new Map()
|
|
1402
|
+
};
|
|
1403
|
+
for (const key of keys) {
|
|
1404
|
+
let node = root;
|
|
1405
|
+
for (const char of key) {
|
|
1406
|
+
let child = node.children.get(char);
|
|
1407
|
+
if (!child) {
|
|
1408
|
+
child = {
|
|
1409
|
+
end: false,
|
|
1410
|
+
children: /* @__PURE__ */ new Map()
|
|
1411
|
+
};
|
|
1412
|
+
node.children.set(char, child);
|
|
1413
|
+
}
|
|
1414
|
+
node = child;
|
|
1415
|
+
}
|
|
1416
|
+
node.end = true;
|
|
1417
|
+
}
|
|
1418
|
+
return `^${spellKeyTrie(root)}$`;
|
|
1419
|
+
};
|
|
1420
|
+
const decodePointerSegment = (segment) => {
|
|
1421
|
+
try {
|
|
1422
|
+
return decodeURI(segment).replace(/~1/g, "/").replace(/~0/g, "~");
|
|
1423
|
+
} catch {
|
|
1424
|
+
return segment;
|
|
1425
|
+
}
|
|
1426
|
+
};
|
|
1427
|
+
const positionAfter = (position, key, child) => {
|
|
1428
|
+
if (position !== "keyword") return position === "other" ? "other" : "keyword";
|
|
1429
|
+
if (key === "patternProperties") return "patternKey";
|
|
1430
|
+
if (SCHEMA_MAP_KEYWORDS.has(key)) return "name";
|
|
1431
|
+
if (SCHEMA_ARRAY_KEYWORDS.has(key) || SCHEMA_VALUE_KEYWORDS.has(key) && Array.isArray(child)) return "index";
|
|
1432
|
+
return SCHEMA_VALUE_KEYWORDS.has(key) ? "keyword" : "other";
|
|
1433
|
+
};
|
|
1434
|
+
/**
|
|
1435
|
+
* A local `$ref` rewritten to address the renamed `patternProperties` keys of
|
|
1436
|
+
* the interpreter copy. `root` is the unrenamed document it points into. Only
|
|
1437
|
+
* a segment in keyword position is a keyword, so a definition that happens to
|
|
1438
|
+
* be named `patternProperties` is not mistaken for one.
|
|
1439
|
+
*/
|
|
1440
|
+
const renameRefThroughPatternKeys = (ref, root, renamePatternKeys, schemaObjects) => {
|
|
1441
|
+
if (!ref.startsWith("#/")) return ref;
|
|
1442
|
+
let node = root;
|
|
1443
|
+
let position = "keyword";
|
|
1444
|
+
let changed = false;
|
|
1445
|
+
const renamed = ref.slice(2).split("/").map((segment) => {
|
|
1446
|
+
if (position === "other" && isObject(node) && schemaObjects.has(node)) position = "keyword";
|
|
1447
|
+
const key = decodePointerSegment(segment);
|
|
1448
|
+
let result = segment;
|
|
1449
|
+
if (position === "patternKey" && isObject(node)) {
|
|
1450
|
+
const renamedKey = renamePatternKeys(node).get(key);
|
|
1451
|
+
if (renamedKey !== void 0 && renamedKey !== key) {
|
|
1452
|
+
result = encodePointer(renamedKey);
|
|
1453
|
+
changed = true;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
const child = isObject(node) || Array.isArray(node) ? node[key] : void 0;
|
|
1457
|
+
position = positionAfter(position, key, child);
|
|
1458
|
+
node = child;
|
|
1459
|
+
return result;
|
|
1460
|
+
});
|
|
1461
|
+
return changed ? `#/${renamed.join("/")}` : ref;
|
|
1462
|
+
};
|
|
1463
|
+
const PATTERN_FORMAT_PREFIX = "composio-pattern:";
|
|
1464
|
+
/**
|
|
1465
|
+
* Adds `pattern` to `formats` as an interpreter format that tests it as the
|
|
1466
|
+
* native string parser does (legacy grammar, RE2 with a bounded fallback; see
|
|
1467
|
+
* `compilePattern`), and returns the format name. Returns `undefined` for a
|
|
1468
|
+
* pattern that does not compile at all, which the interpreter then reports as
|
|
1469
|
+
* it always has. `matchers` caches compiled patterns across validations.
|
|
1470
|
+
*/
|
|
1471
|
+
const patternFormat = (pattern, formats, matchers) => {
|
|
1472
|
+
const name = `${PATTERN_FORMAT_PREFIX}${pattern}`;
|
|
1473
|
+
if (!formats.has(name)) {
|
|
1474
|
+
let matcher = matchers.get(pattern);
|
|
1475
|
+
if (matcher === void 0) {
|
|
1476
|
+
try {
|
|
1477
|
+
new RegExp(pattern);
|
|
1478
|
+
} catch {
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
matcher = createPatternMatcher(pattern);
|
|
1482
|
+
matchers.set(pattern, matcher);
|
|
1483
|
+
}
|
|
1484
|
+
const compiled = matcher;
|
|
1485
|
+
formats.set(name, (value) => patternMatches(compiled, value));
|
|
1486
|
+
}
|
|
1487
|
+
return name;
|
|
1488
|
+
};
|
|
1489
|
+
/**
|
|
1490
|
+
* Rewrites the guard's private copy of a schema into what the Draft 7
|
|
1491
|
+
* interpreter understands the way the native parsers do:
|
|
1492
|
+
*
|
|
1493
|
+
* - OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
|
|
1494
|
+
* `minimum`/`maximum`. The interpreter ignores the flag, so it receives the
|
|
1495
|
+
* numeric spelling the native number parser already honors.
|
|
1496
|
+
* - The interpreter compiles patterns natively with the `u` flag, which
|
|
1497
|
+
* refuses legacy syntax tool schemas use, such as `\_`, and backtracks. A
|
|
1498
|
+
* `pattern` becomes a format that tests it exactly like the native string
|
|
1499
|
+
* parser. A `patternProperties` key cannot leave the interpreter, so it is
|
|
1500
|
+
* respelled by `renamePatternKeys`, and local `$ref`s through a renamed key
|
|
1501
|
+
* follow the rename. `root` is the unmodified document those refs address.
|
|
1502
|
+
* `formats` collects the pattern formats.
|
|
1503
|
+
*/
|
|
1504
|
+
const prepareInterpreterSchema = (value, root, formats, patternMatchers, renamePatternKeys, schemaObjects) => {
|
|
800
1505
|
if (value.exclusiveMinimum === true && typeof value.minimum === "number") {
|
|
801
1506
|
value.exclusiveMinimum = value.minimum;
|
|
802
1507
|
delete value.minimum;
|
|
@@ -805,31 +1510,108 @@ const normalizeExclusiveBounds = (value, seen) => {
|
|
|
805
1510
|
value.exclusiveMaximum = value.maximum;
|
|
806
1511
|
delete value.maximum;
|
|
807
1512
|
} else if (typeof value.exclusiveMaximum === "boolean") delete value.exclusiveMaximum;
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
1513
|
+
if (typeof value.$ref === "string") value.$ref = renameRefThroughPatternKeys(value.$ref, root, renamePatternKeys, schemaObjects);
|
|
1514
|
+
const patternFormatName = typeof value.pattern === "string" ? patternFormat(value.pattern, formats, patternMatchers) : void 0;
|
|
1515
|
+
if (patternFormatName !== void 0) {
|
|
1516
|
+
delete value.pattern;
|
|
1517
|
+
if (value.format === void 0) value.format = patternFormatName;
|
|
1518
|
+
else value.allOf = [...Array.isArray(value.allOf) ? value.allOf : [], { format: patternFormatName }];
|
|
1519
|
+
}
|
|
1520
|
+
if (isObject(value.patternProperties)) {
|
|
1521
|
+
const renames = renamePatternKeys(value.patternProperties);
|
|
1522
|
+
value.patternProperties = Object.fromEntries(Object.entries(value.patternProperties).map(([pattern, schema]) => [renames.get(pattern) ?? pattern, schema]));
|
|
1523
|
+
}
|
|
1524
|
+
};
|
|
1525
|
+
const guardedSchemaClasses = /* @__PURE__ */ new WeakMap();
|
|
1526
|
+
/**
|
|
1527
|
+
* A subclass of the parsed schema's own class that checks the source value
|
|
1528
|
+
* against the guard before parsing it. Keeping the class, rather than wrapping
|
|
1529
|
+
* it in a pipeline, keeps the schema's kind: a guarded object is still a
|
|
1530
|
+
* `ZodObject` with a `shape`, which is what zod-to-json-schema and the MCP SDK
|
|
1531
|
+
* need to emit a root `type: "object"` for LLM tool parameters. The guard lives
|
|
1532
|
+
* on `_def`, so copies such as `.describe()` keep it.
|
|
1533
|
+
*/
|
|
1534
|
+
const guardedSchemaClass = (Base) => {
|
|
1535
|
+
const cached = guardedSchemaClasses.get(Base);
|
|
1536
|
+
if (cached) return cached;
|
|
1537
|
+
const parseAsBase = Base.prototype._parse;
|
|
1538
|
+
class Guarded extends Base {
|
|
1539
|
+
_parse(input) {
|
|
1540
|
+
const failure = this._def.wholeSchemaGuard?.(input.data);
|
|
1541
|
+
if (failure === void 0) return parseAsBase.call(this, input);
|
|
1542
|
+
z.addIssueToContext(this._getOrReturnCtx(input), {
|
|
1543
|
+
code: z.ZodIssueCode.custom,
|
|
1544
|
+
message: failure
|
|
1545
|
+
});
|
|
1546
|
+
return z.DIRTY(input.data);
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
guardedSchemaClasses.set(Base, Guarded);
|
|
1550
|
+
guardedSchemaClasses.set(Guarded, Guarded);
|
|
1551
|
+
return Guarded;
|
|
811
1552
|
};
|
|
812
1553
|
const withWholeSchemaValidation = (jsonSchema, parsedSchema) => {
|
|
813
|
-
const
|
|
814
|
-
|
|
815
|
-
const
|
|
816
|
-
const
|
|
1554
|
+
const patternMatchers = /* @__PURE__ */ new Map();
|
|
1555
|
+
const originalNodes = [...interpreterSchemaNodes(jsonSchema)];
|
|
1556
|
+
const schemaObjects = new WeakSet(originalNodes.map((node) => node.value));
|
|
1557
|
+
const keyMatchers = collectPatternKeyMatchers(originalNodes);
|
|
1558
|
+
const prepare = (spell) => {
|
|
1559
|
+
const interpreterSchema = structuredClone(jsonSchema);
|
|
1560
|
+
const formats = /* @__PURE__ */ new Map();
|
|
1561
|
+
const renamed = /* @__PURE__ */ new Map();
|
|
1562
|
+
const renamePatternKeys = patternKeyRenamer(spell, renamed);
|
|
1563
|
+
const nodes = [...interpreterSchemaNodes(interpreterSchema)];
|
|
1564
|
+
for (const { value } of nodes) prepareInterpreterSchema(value, jsonSchema, formats, patternMatchers, renamePatternKeys, schemaObjects);
|
|
1565
|
+
return {
|
|
1566
|
+
validator: new Validator(interpreterSchema, "7", false),
|
|
1567
|
+
formats,
|
|
1568
|
+
renamed
|
|
1569
|
+
};
|
|
1570
|
+
};
|
|
1571
|
+
const shared = keyMatchers.size === 0 ? prepare(fallbackKeySpelling) : void 0;
|
|
1572
|
+
const prepareFor = (value) => {
|
|
1573
|
+
if (shared) return shared;
|
|
1574
|
+
const instanceKeys = [...collectInstanceKeys(value)];
|
|
1575
|
+
const spellings = /* @__PURE__ */ new Map();
|
|
1576
|
+
return prepare((pattern) => {
|
|
1577
|
+
const cached = spellings.get(pattern);
|
|
1578
|
+
if (cached !== void 0) return cached;
|
|
1579
|
+
const matcher = keyMatchers.get(pattern);
|
|
1580
|
+
const spelling = matcher === void 0 ? fallbackKeySpelling(pattern) : literalKeysPattern(instanceKeys.filter((key) => patternMatches(matcher, key)));
|
|
1581
|
+
spellings.set(pattern, spelling);
|
|
1582
|
+
return spelling;
|
|
1583
|
+
});
|
|
1584
|
+
};
|
|
1585
|
+
const innerGuard = parsedSchema._def.wholeSchemaGuard;
|
|
1586
|
+
const wholeSchemaGuard = (value) => {
|
|
817
1587
|
let result;
|
|
1588
|
+
let prepared;
|
|
818
1589
|
try {
|
|
819
|
-
|
|
1590
|
+
prepared = prepareFor(value);
|
|
1591
|
+
prepared.formats.forEach((test, name) => {
|
|
1592
|
+
format[name] = test;
|
|
1593
|
+
});
|
|
1594
|
+
result = prepared.validator.validate(value);
|
|
820
1595
|
} catch (cause) {
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1596
|
+
return `JSON Schema validation failed: ${String(cause)}`;
|
|
1597
|
+
} finally {
|
|
1598
|
+
prepared?.formats.forEach((_, name) => {
|
|
1599
|
+
delete format[name];
|
|
824
1600
|
});
|
|
825
|
-
return;
|
|
826
1601
|
}
|
|
827
|
-
if (!result.valid)
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
1602
|
+
if (!result.valid) {
|
|
1603
|
+
let error = result.errors[0]?.error ?? "Input does not satisfy the complete JSON Schema.";
|
|
1604
|
+
prepared.renamed.forEach((key, spelling) => {
|
|
1605
|
+
error = error.split(`"${spelling}"`).join(`"${key}"`);
|
|
1606
|
+
});
|
|
1607
|
+
return error;
|
|
1608
|
+
}
|
|
1609
|
+
return innerGuard?.(value);
|
|
1610
|
+
};
|
|
1611
|
+
return new (guardedSchemaClass(parsedSchema.constructor))({
|
|
1612
|
+
...parsedSchema._def,
|
|
1613
|
+
wholeSchemaGuard
|
|
1614
|
+
});
|
|
833
1615
|
};
|
|
834
1616
|
|
|
835
1617
|
//#endregion
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@composio/json-schema-to-zod",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"type": "module",
|
|
@@ -37,12 +37,12 @@
|
|
|
37
37
|
"license": "ISC",
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@types/json-schema": "^7.0.15",
|
|
40
|
-
"@types/node": "^26.
|
|
40
|
+
"@types/node": "^26.6.2",
|
|
41
41
|
"ajv": "^8.20.0",
|
|
42
|
-
"fast-check": "^4.
|
|
42
|
+
"fast-check": "^4.10.2",
|
|
43
43
|
"tsdown": "^0.23.0",
|
|
44
44
|
"typescript": "^7.0.2",
|
|
45
|
-
"vitest": "^
|
|
45
|
+
"vitest": "^5.0.1",
|
|
46
46
|
"zod": "^4.5.4"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
@@ -50,7 +50,8 @@
|
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"@cfworker/json-schema": "^4.1.1",
|
|
53
|
-
"dequal": "^2.0.3"
|
|
53
|
+
"dequal": "^2.0.3",
|
|
54
|
+
"re2js": "^2.8.6"
|
|
54
55
|
},
|
|
55
56
|
"scripts": {
|
|
56
57
|
"clean": "git clean -xdf node_modules",
|