@atscript/typescript 0.2.8 → 0.2.10

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/utils.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as VALIDATOR_KEYS, A as propAtChain, B as registerCompiledCheck, C as createAnnotatedTypeNode, D as isAnnotatedType, E as defineAnnotatedType, F as VALIDATOR_MESSAGES, G as $nr, H as jsonSchemaPattern, I as formatCodeOf, J as watchLayer, K as LayerMap, L as formatValidatorMessage, M as ValidatorError, N as unionDiscriminator, O as isAnnotatedTypeOfPrimitive, P as VALIDATOR_ERROR_CODES, Q as DECIMAL_RE, R as localizeErrors, S as annotate, T as createObjectTypeDef, U as statelessRegExp, V as detectDiscriminator, W as $ak, X as touched, Y as invalidateCompiledValidators, Z as typeWriteCount, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, et as arrayKeyProps, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, o as uniqueName, p as $ps, q as metaEmpty, r as registerUserText, s as $alias, t as $ut, tt as boundOf, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as messagesTranslator } from "./user-text-DZR5hfLa.mjs";
1
+ import { $ as DECIMAL_RE, A as propAtChain, B as acceptsNull$2, C as createAnnotatedTypeNode, D as isAnnotatedType, E as defineAnnotatedType, F as VALIDATOR_MESSAGES, G as $ak, H as detectDiscriminator, I as formatCodeOf, J as metaEmpty, K as $nr, L as formatValidatorMessage, M as ValidatorError, N as unionDiscriminator, O as isAnnotatedTypeOfPrimitive, P as VALIDATOR_ERROR_CODES, Q as typeWriteCount, R as localizeErrors, S as annotate, T as createObjectTypeDef, U as jsonSchemaPattern, V as registerCompiledCheck, W as statelessRegExp, X as invalidateCompiledValidators, Y as watchLayer, Z as touched, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, et as VALIDATOR_KEYS, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, nt as boundOf, o as uniqueName, p as $ps, q as LayerMap, r as registerUserText, s as $alias, t as $ut, tt as arrayKeyProps, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as messagesTranslator } from "./user-text-DS0lorlV.mjs";
2
2
 
3
3
  //#region packages/typescript/src/runtime/copy-on-change.ts
4
4
  /**
@@ -16,13 +16,7 @@ import { $ as VALIDATOR_KEYS, A as propAtChain, B as registerCompiledCheck, C as
16
16
  for (let i = 0; i < keys.length; i++) {
17
17
  const key = keys[i];
18
18
  const input = value[key];
19
- let def = type.props.get(key);
20
- if (!def) {
21
- for (const { pattern, def: patternDef } of type.propsPatterns) if (pattern.test(key)) {
22
- def = patternDef;
23
- break;
24
- }
25
- }
19
+ const def = propOf(type, key);
26
20
  const mapped = def ? step(def, input, ctx) : input;
27
21
  if (mapped === NO_MATCH) return NO_MATCH;
28
22
  if (out) setOwn(out, key, mapped);
@@ -34,6 +28,11 @@ import { $ as VALIDATOR_KEYS, A as propAtChain, B as registerCompiledCheck, C as
34
28
  }
35
29
  return out ?? value;
36
30
  }
31
+ /** The def of prop `key` of object `type`: its declared prop, else the first pattern `key` matches. */ function propOf(type, key) {
32
+ const def = type.props.get(key);
33
+ if (def) return def;
34
+ for (const p of type.propsPatterns) if (p.pattern.test(key)) return p.def;
35
+ }
37
36
  /**
38
37
  * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
39
38
  * items). Copy-on-first-change, as {@link mapProps}.
@@ -453,12 +452,18 @@ function judgesFor(opts) {
453
452
  * backtracking). A scalar branch takes what it parses; an object (tuple)
454
453
  * branch takes a plain object (an array of its length) unless a literal
455
454
  * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
456
- * does not coerce to it, a string compared after the normalizers of the
457
- * literal and of the unions it is in. An object takes the branch its
458
- * discriminator names (as the validator does: the literal itself first, else
459
- * `"2"` names a `2` literal), else the first whose shape it has (required
460
- * props present, no undeclared key), else the first that takes it. When no
461
- * branch takes the value, it is returned untouched.
455
+ * does not coerce to it (`"2"` coerces to a `2` literal), a string compared
456
+ * after the normalizers of the literal and of the unions it is in. A scalar
457
+ * takes the first branch that takes it. An object or array takes the only
458
+ * branch that takes it, else the one it fits best, judged in this order
459
+ * (never looking deeper than its own keys and items): its props (items) hold
460
+ * values of their kinds (a string that parses for a `number` prop, `null`
461
+ * where `null` is allowed); it has no undeclared key; it has every required
462
+ * prop (the last two can be waived by `partial` / `unknownProps`, a wrong
463
+ * kind cannot); a nested union's branches count as the union's own. Ties go
464
+ * to the branch an object's discriminator names by the literal itself, then
465
+ * to declared order. When no branch takes the value, it is returned
466
+ * untouched.
462
467
  * - Objects recurse into props when the input is a plain object (covers
463
468
  * `@Query()` DTOs where every field arrives as a string), whatever their
464
469
  * literal props hold unless tried as a union branch.
@@ -543,34 +548,161 @@ function scalar(designType, value) {
543
548
  }
544
549
  }
545
550
  /**
546
- * The branch of union `items` that takes `value` (see {@link takes}): the one an object's
547
- * discriminator names; else, for an object, the first that takes it and whose shape it has (see
548
- * {@link fits}); else the first that takes it, in declared order (a partial patch); `undefined`
549
- * when none does.
551
+ * The score bits of a union branch for an object (array), most weighty first (see {@link score} and
552
+ * {@link coerceForType}): props (items) hold their kinds; no undeclared key; required props present.
553
+ */ const HOLDS = 4;
554
+ const DECLARED = 2;
555
+ const COMPLETE = 1;
556
+ const BEST = DECLARED | 5;
557
+ /** The score of a branch not scored yet (the only taker so far, see {@link TPick}). */ const UNSCORED = -1;
558
+ /**
559
+ * The branch of union `items` that takes `value` (see {@link takes}); `undefined` when none does.
560
+ * A scalar: the first taker. An object or array: of the leaf branches (see {@link leavesOf}), the
561
+ * only taker, else the best scored one (see {@link score}); the branch the discriminator names is
562
+ * tried first, then declared order, and a tie keeps the earlier one.
550
563
  */ function branchOf(items, value) {
551
- let first;
552
- if (isPlainObject$1(value)) {
553
- const named = discriminatedBranch(items, value);
554
- if (named && takes(named, value)) return named;
555
- for (const item of items) if (takes(item, value)) {
556
- if (fits(item, value)) return item;
557
- first ?? (first = item);
558
- }
559
- return first;
564
+ if (!isPlainObject$1(value) && !Array.isArray(value)) return items.find((item) => takes(item, value));
565
+ const leaves = leavesOf(items);
566
+ const pick = {
567
+ branch: void 0,
568
+ score: UNSCORED,
569
+ keys: void 0,
570
+ values: void 0
571
+ };
572
+ const named = Array.isArray(value) ? void 0 : discriminatedBranch(leaves, value);
573
+ if (named) consider(named, value, pick);
574
+ for (const leaf of leaves) {
575
+ if (pick.score === BEST) break;
576
+ if (leaf !== named) consider(leaf, value, pick);
560
577
  }
561
- return items.find((item) => takes(item, value));
578
+ return pick.branch;
562
579
  }
580
+ /** {@link leavesOf} by union items: valid until the next type tree write (see `typeWriteCount`). */ let leavesCache = /* @__PURE__ */ new WeakMap();
581
+ let leavesStamp = -1;
563
582
  /**
564
- * Whether object `value` has the shape of branch `def`, by its own keys alone: every required
565
- * prop is one of them, and each of them is a prop (or matches a prop pattern) of the branch. A
566
- * union: one of its branches; a branch that is not an object (nor an intersection of objects)
567
- * has any shape.
568
- */ function fits(def, value) {
569
- if (def.type.kind === "union") return def.type.items.some((item) => fits(item, value));
583
+ * The branches of union `items` that are not unions, a nested union's in its place, in declared
584
+ * order, so `(A | B) | C` and `A | B | C` rank alike: `items` itself when none is a union, else
585
+ * the same array for the same items (the discriminator over them is decided once).
586
+ */ function leavesOf(items) {
587
+ if (!items.some(isUnion)) return items;
588
+ const writes = typeWriteCount();
589
+ if (writes !== leavesStamp) {
590
+ leavesStamp = writes;
591
+ leavesCache = /* @__PURE__ */ new WeakMap();
592
+ }
593
+ let leaves = leavesCache.get(items);
594
+ if (!leaves) {
595
+ leaves = [];
596
+ collectLeaves(items, leaves);
597
+ leavesCache.set(items, leaves);
598
+ }
599
+ return leaves;
600
+ }
601
+ function isUnion(def) {
602
+ return def.type.kind === "union";
603
+ }
604
+ function collectLeaves(items, out) {
605
+ for (const item of items) if (isUnion(item)) collectLeaves(item.type.items, out);
606
+ else out.push(item);
607
+ }
608
+ /** Takes leaf branch `def` for `pick` when it takes `value` and scores above the best so far. */ function consider(def, value, pick) {
609
+ if (!takes(def, value)) return;
610
+ if (!pick.branch) {
611
+ pick.branch = def;
612
+ return;
613
+ }
614
+ if (pick.score === UNSCORED) {
615
+ pick.score = score(pick.branch, value, pick);
616
+ if (pick.score === BEST) return;
617
+ }
618
+ const s = score(def, value, pick);
619
+ if (s > pick.score) {
620
+ pick.branch = def;
621
+ pick.score = s;
622
+ }
623
+ }
624
+ /**
625
+ * The bits (see {@link HOLDS}) leaf branch `def`, which takes object (array) `value`, scores; once
626
+ * it cannot beat `pick.score`, any score not above it. Only an object branch can miss
627
+ * {@link DECLARED} or {@link COMPLETE}.
628
+ */ function score(def, value, pick) {
629
+ var _pick, _pick1;
570
630
  const objects = [];
571
- if (!objectsOf(def, objects)) return true;
572
- for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return false;
573
- return Object.keys(value).every((key) => objects.some((o) => o.props.has(key) || o.propsPatterns.some((p) => p.pattern.test(key))));
631
+ if (Array.isArray(value) || !objectsOf(def, objects)) return (holdsAll(def, value) ? HOLDS : 0) | 3;
632
+ const floor = pick.score;
633
+ let bits = BEST;
634
+ const keys = (_pick = pick).keys ?? (_pick.keys = Object.keys(value));
635
+ const values = (_pick1 = pick).values ?? (_pick1.values = keys.map((key) => value[key]));
636
+ for (let i = 0; i < keys.length; i++) {
637
+ const key = keys[i];
638
+ let declared = false;
639
+ for (const o of objects) {
640
+ const prop = propOf(o, key);
641
+ if (prop) {
642
+ declared = true;
643
+ if (bits & HOLDS && !holds(prop, values[i])) bits &= ~HOLDS;
644
+ }
645
+ }
646
+ if (!declared) bits &= ~DECLARED;
647
+ if (bits <= floor) return bits;
648
+ if (bits <= COMPLETE) break;
649
+ }
650
+ for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return bits & ~COMPLETE;
651
+ return bits;
652
+ }
653
+ /**
654
+ * Whether each prop (pattern prop) of branch `def` that object `value` has, or each item of array
655
+ * `value`, holds a value of its kind (see {@link holds}). Looks at `value`'s own keys and items
656
+ * only. `def` takes `value` (see {@link takes}).
657
+ */ function holdsAll(def, value) {
658
+ const type = def.type;
659
+ switch (type.kind) {
660
+ case "object": {
661
+ const o = type;
662
+ const record = value;
663
+ return Object.keys(record).every((key) => {
664
+ const prop = propOf(o, key);
665
+ return !prop || holds(prop, record[key]);
666
+ });
667
+ }
668
+ case "array": {
669
+ const of = type.of;
670
+ return value.every((item) => holds(of, item));
671
+ }
672
+ case "tuple": return type.items.every((item, i) => holds(item, value[i]));
673
+ case "union": return type.items.some((item) => takes(item, value) && holdsAll(item, value));
674
+ case "intersection": return type.items.every((item) => holdsAll(item, value));
675
+ default: return true;
676
+ }
677
+ }
678
+ /**
679
+ * Whether `input` is of the kind of prop (item) `def`, never looking inside it: a scalar that
680
+ * coerces to the prop's scalar type, or to one of its literals (a string after the normalizers on
681
+ * the literal's way, see `literalNodes`); a plain object for an object, an array for an array (of
682
+ * the tuple's length); `null` where the prop takes `null` (optional or a nullable type).
683
+ * `inherited`: the normalizer flags of the unions `def` is in.
684
+ */ function holds(def, input, inherited = 0) {
685
+ if (input === void 0) return true;
686
+ if (input === null) return def.optional === true || acceptsNull$2(def);
687
+ const type = def.type;
688
+ switch (type.kind) {
689
+ case "": {
690
+ const final = type;
691
+ return final.value === void 0 ? scalar(final.designType, input) !== NO_MATCH : coercesTo(def, flagsOf(def, inherited), input);
692
+ }
693
+ case "object": return isPlainObject$1(input);
694
+ case "array": return Array.isArray(input);
695
+ case "tuple": return Array.isArray(input) && input.length === type.items.length;
696
+ case "union": {
697
+ const flags = flagsOf(def, inherited);
698
+ return type.items.some((item) => holds(item, input, flags));
699
+ }
700
+ case "intersection": {
701
+ const flags = flagsOf(def, inherited);
702
+ return type.items.every((item) => holds(item, input, flags));
703
+ }
704
+ default: return false;
705
+ }
574
706
  }
575
707
  /** Collects the objects `def` is (an object, an intersection of objects); `false` for others. */ function objectsOf(def, out) {
576
708
  const type = def.type;
@@ -592,7 +724,7 @@ function scalar(designType, value) {
592
724
  case "": return coerce(def, value) !== NO_MATCH;
593
725
  case "object":
594
726
  if (!isPlainObject$1(value)) return false;
595
- for (const [key, prop] of type.props) if (Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
727
+ for (const [key, prop] of type.props) if (mayBeLiteral(prop) && Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
596
728
  return true;
597
729
  case "array": return Array.isArray(value);
598
730
  case "tuple": {
@@ -604,6 +736,10 @@ function scalar(designType, value) {
604
736
  default: return false;
605
737
  }
606
738
  }
739
+ /** Whether `def` can be a literal prop (see `literalNodes`): a literal or a union. */ function mayBeLiteral(def) {
740
+ const type = def.type;
741
+ return type.kind === "" ? type.value !== void 0 : type.kind === "union";
742
+ }
607
743
  /**
608
744
  * Whether prop (item) `def` of a union branch can hold `input`: anything, but a literal prop
609
745
  * (see `literalNodes`: `kind: 'cat'`, `kind: 'cat' | null`) only a value that coerces to one of
@@ -612,32 +748,361 @@ function scalar(designType, value) {
612
748
  */ function holdsLiteral(def, input) {
613
749
  if (input === void 0 || input === null) return true;
614
750
  const literals = literalNodes(def);
615
- return !literals || literals.some((literal) => coercesTo(literal, input));
751
+ return !literals || literals.some((literal) => coercesTo(literal.node, literal.flags, input));
616
752
  }
617
- /** Whether `input` coerces to the value of `literal` (see `holdsLiteral`). */ function coercesTo(literal, input) {
618
- const value = typeof input === "string" ? applyFlags(input, literal.flags) : input;
619
- return coerce(literal.node, value) !== NO_MATCH;
753
+ /**
754
+ * Whether `input` coerces to the value of literal `node`, a string after normalizer `flags` (see
755
+ * `holdsLiteral`).
756
+ */ function coercesTo(node, flags, input) {
757
+ return coerce(node, typeof input === "string" ? applyFlags(input, flags) : input) !== NO_MATCH;
620
758
  }
621
759
  /**
622
- * The branch of union `items` the discriminator of object `value` names: its literal itself,
623
- * else the one its value coerces to (`"2"` names `2`, see {@link coercesTo}); `undefined` when the
624
- * union has no discriminator or the value names no branch.
760
+ * The branch of union `items` whose discriminator literal is exactly the one object `value` holds
761
+ * (`"1"` names a `'1'` literal, not a `1`, though it makes a `1` branch a taker, see {@link takes});
762
+ * `undefined` when the union has no discriminator or no branch's literal is that value.
625
763
  */ function discriminatedBranch(items, value) {
626
764
  const disc = unionDiscriminator(items);
627
- if (disc === void 0) return;
628
- const tag = Object.hasOwn(value, disc.property) ? value[disc.property] : void 0;
629
- if (tag === void 0 || tag === null) return;
765
+ if (disc === void 0 || !Object.hasOwn(value, disc.property)) return;
766
+ const tag = value[disc.property];
630
767
  for (const [index, literal] of disc.branches) if (literal === tag) return items[index];
631
- for (const [index] of disc.branches) {
632
- const prop = items[index].type.props.get(disc.property);
633
- if (prop && holdsLiteral(prop, tag)) return items[index];
634
- }
635
768
  }
636
769
  /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
637
770
  const result = coerce(def, input);
638
771
  return result === NO_MATCH ? input : result;
639
772
  }
640
773
 
774
+ //#endregion
775
+ //#region packages/typescript/src/runtime/json-schema-strict.ts
776
+ /** The keywords every provider takes: the shape of the schema, its notes and literals. */ const BASE_KEYWORDS = {
777
+ type: true,
778
+ properties: true,
779
+ required: true,
780
+ additionalProperties: true,
781
+ items: true,
782
+ anyOf: true,
783
+ $ref: true,
784
+ $defs: true,
785
+ enum: true,
786
+ const: true,
787
+ title: true,
788
+ description: true
789
+ };
790
+ /** The string formats both providers list. */ const FORMATS = new Set([
791
+ "date-time",
792
+ "time",
793
+ "date",
794
+ "duration",
795
+ "email",
796
+ "hostname",
797
+ "ipv4",
798
+ "ipv6",
799
+ "uuid"
800
+ ]);
801
+ /**
802
+ * OpenAI Structured Outputs / `strict: true` function calling: every property required
803
+ * (optional ones nullable), objects closed, an object root, no `allOf`; patterns without
804
+ * lookaround, backreferences or modifier groups, numeric bounds and `minItems` / `maxItems`
805
+ * kept; string lengths, `uniqueItems` and key counts dropped. Recursion is allowed.
806
+ */ const OPENAI_STRICT = {
807
+ name: "openai",
808
+ keywords: {
809
+ ...BASE_KEYWORDS,
810
+ pattern: (value) => decodablePattern(value),
811
+ format: (value) => FORMATS.has(value),
812
+ minimum: true,
813
+ maximum: true,
814
+ exclusiveMinimum: true,
815
+ exclusiveMaximum: true,
816
+ multipleOf: true,
817
+ minItems: true,
818
+ maxItems: true
819
+ },
820
+ requireAll: true,
821
+ collapseAllOf: true,
822
+ describeDropped: true,
823
+ allowRecursion: true,
824
+ objectRoot: true
825
+ };
826
+ /**
827
+ * Anthropic strict tool use / structured outputs: objects closed, an object root (a tool's
828
+ * `input_schema`), no recursion; simple patterns kept (no lookaround, backreferences, word
829
+ * boundaries or large `{n,m}`), `minItems` only `0` / `1`; numeric bounds, string lengths,
830
+ * `maxItems`, `uniqueItems` and key counts dropped. `allOf` is allowed
831
+ * except with a `$ref` (collapsed). Optional properties stay optional.
832
+ */ const ANTHROPIC_STRICT = {
833
+ name: "anthropic",
834
+ keywords: {
835
+ ...BASE_KEYWORDS,
836
+ allOf: true,
837
+ pattern: (value) => simplePattern(value),
838
+ format: (value) => FORMATS.has(value) || value === "uri",
839
+ minItems: (value) => value === 0 || value === 1
840
+ },
841
+ requireAll: false,
842
+ collapseAllOf: true,
843
+ describeDropped: true,
844
+ allowRecursion: false,
845
+ objectRoot: true
846
+ };
847
+ /** The largest `{n,m}` bound a simple pattern has (see {@link simplePattern}). */ const SIMPLE_BOUND = 100;
848
+ /**
849
+ * A pattern without lookaround, backreferences, word boundaries, Unicode property escapes,
850
+ * modifier groups or `{n,m}` bounds above {@link SIMPLE_BOUND} (Anthropic's simple patterns).
851
+ * Named groups are fine; `\b` in a class is a backspace.
852
+ */ function simplePattern(pattern) {
853
+ return scanPattern(pattern, true);
854
+ }
855
+ /** A pattern without lookaround, backreferences or modifier groups (OpenAI). */ function decodablePattern(pattern) {
856
+ return scanPattern(pattern, false);
857
+ }
858
+ /** {@link simplePattern} (`simple`), else {@link decodablePattern}. */ function scanPattern(pattern, simple) {
859
+ let inClass = false;
860
+ for (let i = 0; i < pattern.length; i++) {
861
+ const c = pattern[i];
862
+ if (c === "\\") {
863
+ const next = pattern[++i];
864
+ if (next === void 0 || /[1-9k]/.test(next)) return false;
865
+ if (simple && (/[pPB]/.test(next) || next === "b" && !inClass)) return false;
866
+ } else if (inClass) inClass = c !== "]";
867
+ else if (c === "[") inClass = true;
868
+ else if (c === "(" && pattern[i + 1] === "?") {
869
+ const kind = pattern[i + 2];
870
+ const named = kind === "<" && pattern[i + 3] !== "=" && pattern[i + 3] !== "!";
871
+ if (kind !== ":" && !named) return false;
872
+ } else if (simple && c === "{") {
873
+ const bounds = /^\{(\d+)(?:,(\d*))?\}/.exec(pattern.slice(i));
874
+ if (bounds && (Number(bounds[1]) > SIMPLE_BOUND || Number(bounds[2] || 0) > SIMPLE_BOUND)) return false;
875
+ }
876
+ }
877
+ return true;
878
+ }
879
+ /** The `$defs` name a `$ref` this builder writes points to. */ function refName(ref) {
880
+ return ref.slice(8);
881
+ }
882
+ /** The `$defs` names `schema` refers to (through any keyword but `$defs`). */ function refsOf(schema, out = /* @__PURE__ */ new Set()) {
883
+ if (Array.isArray(schema)) for (const item of schema) refsOf(item, out);
884
+ else if (schema && typeof schema === "object") {
885
+ for (const [key, value] of Object.entries(schema)) if (key === "$ref" && typeof value === "string") out.add(refName(value));
886
+ else if (key !== "$defs") refsOf(value, out);
887
+ }
888
+ return out;
889
+ }
890
+ /** The refs of each `$defs` entry, by name. */ function edgesOf(defs) {
891
+ return new Map(Object.entries(defs).map(([name, def]) => [name, refsOf(def)]));
892
+ }
893
+ /** The `$defs` names reachable from `from` through `edges`. */ function reachable(from, edges) {
894
+ const seen = /* @__PURE__ */ new Set();
895
+ const stack = [...from];
896
+ for (let name = stack.pop(); name !== void 0; name = stack.pop()) if (!seen.has(name)) {
897
+ seen.add(name);
898
+ stack.push(...edges.get(name) ?? []);
899
+ }
900
+ return seen;
901
+ }
902
+ /** The first `$defs` entry that refers to itself, through any others; `undefined`: none. */ function recursiveDef(defs) {
903
+ const edges = edgesOf(defs);
904
+ return [...edges.keys()].find((name) => reachable(edges.get(name), edges).has(name));
905
+ }
906
+ /** `n` `one`(s): `1 item`, `2 items`. */ function count(n, one, many = `${one}s`) {
907
+ return `${n} ${n === 1 ? one : many}`;
908
+ }
909
+ /** A dropped keyword in plain words (`pattern` `\S`: the `@meta.required` check). */ function describe(keyword, value) {
910
+ switch (keyword) {
911
+ case "minLength": return `At least ${count(value, "character")}.`;
912
+ case "maxLength": return `At most ${count(value, "character")}.`;
913
+ case "pattern": return value === "\\S" ? "Must not be blank." : `Must match the pattern ${JSON.stringify(value)}.`;
914
+ case "format": return `Format: ${value}.`;
915
+ case "minimum": return `Minimum ${value}.`;
916
+ case "maximum": return `Maximum ${value}.`;
917
+ case "exclusiveMinimum": return `Greater than ${value}.`;
918
+ case "exclusiveMaximum": return `Less than ${value}.`;
919
+ case "multipleOf": return `A multiple of ${value}.`;
920
+ case "minItems": return `At least ${count(value, "item")}.`;
921
+ case "maxItems": return `At most ${count(value, "item")}.`;
922
+ case "uniqueItems": return value ? "Items must be unique." : "";
923
+ case "minProperties": return `At least ${count(value, "property", "properties")}.`;
924
+ case "maxProperties": return `At most ${count(value, "property", "properties")}.`;
925
+ default: return `${keyword}: ${JSON.stringify(value)}.`;
926
+ }
927
+ }
928
+ /** A schema `type` of objects (`'object'`, or a type list with it: an optional object). */ function isObjectType(type) {
929
+ return type === "object" || Array.isArray(type) && type.includes("object");
930
+ }
931
+ /** Whether `schema` accepts `null` as it is (a `null` type, value or `anyOf` member). */ function acceptsNull$1(schema) {
932
+ if ("const" in schema) return schema.const === null;
933
+ if (Array.isArray(schema.enum)) return schema.enum.includes(null);
934
+ if (schema.type !== void 0) return schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null");
935
+ return Array.isArray(schema.anyOf) && schema.anyOf.some(acceptsNull$1);
936
+ }
937
+ /**
938
+ * `schema` also accepting `null`: `type: [t, 'null']` for a plain typed schema, else an `anyOf`
939
+ * with a `null` member (the title / description stay beside it).
940
+ */ function orNull(schema) {
941
+ if (acceptsNull$1(schema)) return schema;
942
+ if (schema.type !== void 0 && !("const" in schema) && schema.enum === void 0) return {
943
+ ...schema,
944
+ type: [schema.type, "null"].flat()
945
+ };
946
+ const { title, description, ...body } = schema;
947
+ const notes = {};
948
+ if (title !== void 0) notes.title = title;
949
+ if (description !== void 0) notes.description = description;
950
+ return {
951
+ anyOf: [...Object.keys(body).length === 1 && Array.isArray(body.anyOf) ? body.anyOf : [body], { type: "null" }],
952
+ ...notes
953
+ };
954
+ }
955
+ /**
956
+ * Object schema `out` with every property required (`requireAll`): those not in `required`
957
+ * (optional) made nullable.
958
+ */ function requireAll(out, required) {
959
+ const properties = out.properties ?? {};
960
+ const keys = Object.keys(properties);
961
+ const requiredKeys = new Set(required);
962
+ for (const key of keys) if (!requiredKeys.has(key)) properties[key] = orNull(properties[key]);
963
+ if (keys.length > 0) out.required = keys;
964
+ else delete out.required;
965
+ }
966
+ /** Whether `schema` carries the `@meta.required` check of a string (the pattern `\S`). */ function hasBlankCheck(schema) {
967
+ return schema.pattern === "\\S" || Array.isArray(schema.allOf) && schema.allOf.some((item) => item.pattern === "\\S");
968
+ }
969
+ /**
970
+ * `out` with the `dropped` keywords described in its `description` (`blank`: it has the
971
+ * `@meta.required` check, kept or described, which says what its `minLength: 1` would). A lone
972
+ * `$ref` takes no keywords beside it: it moves into an `anyOf` of its own.
973
+ */ function described(out, dropped, blank) {
974
+ const notes = dropped.filter(([key, value]) => !(blank && key === "minLength" && value === 1)).map(([key, value]) => describe(key, value)).filter(Boolean).join(" ");
975
+ if (!notes) return out;
976
+ let schema = out;
977
+ if (schema.$ref !== void 0) {
978
+ const { $ref, ...rest } = schema;
979
+ schema = {
980
+ anyOf: [{ $ref }],
981
+ ...rest
982
+ };
983
+ }
984
+ schema.description = schema.description ? `${schema.description}\n\n${notes}` : notes;
985
+ return schema;
986
+ }
987
+ /**
988
+ * `schema` (built closed by {@link buildJsonSchema}) rewritten to `profile` (see
989
+ * {@link TStrictProfile}). Throws for a shape the profile can't take.
990
+ */ function strictSchema(schema, profile) {
991
+ const fail = (what) => {
992
+ throw new Error(`buildJsonSchema (strict: ${profile.name}): ${what}`);
993
+ };
994
+ const defs = schema.$defs ?? {};
995
+ if (!profile.allowRecursion) {
996
+ const recursive = recursiveDef(defs);
997
+ if (recursive !== void 0) fail(`recursive type "${recursive}" is not supported`);
998
+ }
999
+ if (profile.objectRoot && schema.type !== "object") fail("the root must be an object type");
1000
+ const allowed = (keyword, value) => {
1001
+ const rule = profile.keywords[keyword];
1002
+ return rule === true || rule !== void 0 && rule(value);
1003
+ };
1004
+ /** `$defs` entries being inlined (a use of an entry inside itself stays a reference). */ const inlining = /* @__PURE__ */ new Set();
1005
+ /**
1006
+ * `s` rewritten; the constraints it drops are described on it. `part`: a subschema of an
1007
+ * `allOf` (a constraint of the schema it sits in, no type of its own).
1008
+ */ const rewrite = (s, at, part = false) => {
1009
+ /** The dropped keywords and their values (described at the end). */ const dropped = [];
1010
+ /** The `$defs` entries inlined here (see `collapse`). */ const entered = [];
1011
+ let source = profile.collapseAllOf ? collapse(s, dropped, entered) : s;
1012
+ if (source.oneOf && !profile.keywords.oneOf) {
1013
+ const { oneOf, discriminator: _, ...rest } = source;
1014
+ source = {
1015
+ ...rest,
1016
+ anyOf: oneOf
1017
+ };
1018
+ }
1019
+ const where = at || "the root";
1020
+ if (Array.isArray(source.items)) fail(`a tuple (at ${where}) has no strict schema`);
1021
+ if (source.patternProperties !== void 0) fail(`a record (at ${where}) has no strict schema; use an array of key/value objects`);
1022
+ if (!part && source.type === void 0 && source.anyOf === void 0 && source.allOf === void 0 && source.$ref === void 0 && source.not === void 0 && !("const" in source) && source.enum === void 0) fail(`a value of any type (at ${where}) has no strict schema`);
1023
+ const out = {};
1024
+ for (const [key, value] of Object.entries(source)) {
1025
+ if (key === "discriminator" && !profile.keywords.discriminator) continue;
1026
+ if (!allowed(key, value)) {
1027
+ if (key === "allOf" || key === "not") fail(`${key === "allOf" ? "an intersection" : "an impossible type"} (at ${where}) has no strict schema`);
1028
+ dropped.push([key, value]);
1029
+ continue;
1030
+ }
1031
+ out[key] = rewriteValue(key, value, at);
1032
+ }
1033
+ for (const name of entered) inlining.delete(name);
1034
+ if (isObjectType(out.type)) {
1035
+ out.additionalProperties = false;
1036
+ if (profile.requireAll) requireAll(out, source.required);
1037
+ }
1038
+ return profile.describeDropped && dropped.length > 0 ? described(out, dropped, hasBlankCheck(s) || hasBlankCheck(source)) : out;
1039
+ };
1040
+ /** The value of keyword `key` rewritten (its subschemas). */ const rewriteValue = (key, value, at) => {
1041
+ switch (key) {
1042
+ case "properties": return Object.fromEntries(Object.entries(value).map(([name, p]) => [name, rewrite(p, at ? `${at}.${name}` : name)]));
1043
+ case "items": return rewrite(value, `${at}[]`);
1044
+ case "anyOf": return value.map((item) => rewrite(item, at));
1045
+ case "allOf": return value.map((item) => rewrite(item, at, true));
1046
+ case "$defs": return Object.fromEntries(Object.entries(value).map(([name, d]) => {
1047
+ inlining.add(name);
1048
+ const entry = rewrite(d, `$defs.${name}`);
1049
+ inlining.delete(name);
1050
+ return [name, entry];
1051
+ }));
1052
+ default: return value;
1053
+ }
1054
+ };
1055
+ /**
1056
+ * `s` with its `allOf` collapsed (see `collapseAllOf`): what it drops in `dropped`, the
1057
+ * `$defs` entries it inlines in `entered` (and `inlining`, until `s` is rewritten).
1058
+ */ const collapse = (s, dropped, entered) => {
1059
+ if (!Array.isArray(s.allOf)) return s;
1060
+ const { allOf, ...rest } = s;
1061
+ const ref = allOf.length === 1 && Object.keys(allOf[0]).length === 1 ? allOf[0].$ref : void 0;
1062
+ if (typeof ref === "string") {
1063
+ const name = refName(ref);
1064
+ const target = defs[name];
1065
+ if (target === void 0 || inlining.has(name)) return {
1066
+ anyOf: [{ $ref: ref }],
1067
+ ...rest
1068
+ };
1069
+ inlining.add(name);
1070
+ entered.push(name);
1071
+ return collapse({
1072
+ ...target,
1073
+ ...rest
1074
+ }, dropped, entered);
1075
+ }
1076
+ if (!allOf.every((item) => Object.keys(item).length === 1 && "pattern" in item)) return s;
1077
+ if (profile.keywords.allOf) {
1078
+ const kept = allOf.filter((item) => {
1079
+ if (allowed("pattern", item.pattern)) return true;
1080
+ dropped.push(["pattern", item.pattern]);
1081
+ return false;
1082
+ });
1083
+ if (kept.length > 1 || kept.length === 1 && rest.pattern !== void 0) return {
1084
+ ...rest,
1085
+ allOf: kept
1086
+ };
1087
+ return kept.length === 1 ? {
1088
+ ...rest,
1089
+ pattern: kept[0].pattern
1090
+ } : rest;
1091
+ }
1092
+ const out = { ...rest };
1093
+ for (const { pattern } of allOf) if (out.pattern === void 0 && allowed("pattern", pattern)) out.pattern = pattern;
1094
+ else dropped.push(["pattern", pattern]);
1095
+ return out;
1096
+ };
1097
+ const out = rewrite(schema, "");
1098
+ if (out.$defs) {
1099
+ const used = reachable(refsOf(out), edgesOf(out.$defs));
1100
+ for (const name of Object.keys(out.$defs)) if (!used.has(name)) delete out.$defs[name];
1101
+ if (Object.keys(out.$defs).length === 0) delete out.$defs;
1102
+ }
1103
+ return out;
1104
+ }
1105
+
641
1106
  //#endregion
642
1107
  //#region packages/typescript/src/runtime/traverse.ts
643
1108
  /**
@@ -706,6 +1171,11 @@ function scalar(designType, value) {
706
1171
  * @param opts - {@link TJsonSchemaOptions}.
707
1172
  * @returns A JSON Schema object.
708
1173
  */ function buildJsonSchema(type, opts) {
1174
+ if (opts?.strict) return strictSchema(buildJsonSchema(type, {
1175
+ ...opts,
1176
+ strict: void 0,
1177
+ closed: true
1178
+ }), opts.strict);
709
1179
  const closed = opts?.closed === true;
710
1180
  const annotations = opts?.annotations !== false;
711
1181
  const enums = opts?.enums !== false;
@@ -1555,6 +2025,91 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1555
2025
  return out;
1556
2026
  }
1557
2027
 
2028
+ //#endregion
2029
+ //#region packages/typescript/src/runtime/drop-optional-nulls.ts
2030
+ /**
2031
+ * What `value` looks like without the `null` values the model sends for fields it leaves out under
2032
+ * a `requireAll` profile (`OPENAI_STRICT`), before it goes to the validator. The validator
2033
+ * takes a missing optional field, but not `null` on an optional `@meta.required` one.
2034
+ *
2035
+ * A `null` is dropped only from an optional field whose type does not accept `null`: for
2036
+ * `x?: string | null` it stays (`null` and a missing field mean different things, e.g. "clear"
2037
+ * and "keep" in a patch). In a union, the branch its discriminator picks applies; else every
2038
+ * branch does, and a key is dropped only when every branch (and, in an intersection, every part)
2039
+ * that declares it has it optional and not accepting `null`: one that needs the `null` keeps it.
2040
+ *
2041
+ * Copy-on-change: `value` is never mutated (a frozen one works); the same reference comes back
2042
+ * when nothing is dropped, else a copy with the changed objects and arrays rebuilt.
2043
+ */ function dropOptionalNulls(type, value) {
2044
+ return dropNulls([type], value);
2045
+ }
2046
+ /** The discriminator of a union, found once per union type. */ const discriminators = /* @__PURE__ */ new WeakMap();
2047
+ function discriminatorOf(union) {
2048
+ let disc = discriminators.get(union);
2049
+ if (disc === void 0) {
2050
+ disc = detectDiscriminator(union.items);
2051
+ discriminators.set(union, disc);
2052
+ }
2053
+ return disc;
2054
+ }
2055
+ /**
2056
+ * The defs `value` is checked against, unions and intersections expanded: the branch a
2057
+ * discriminator picks, else every branch.
2058
+ */ function expand(defs, value, out) {
2059
+ for (const def of defs) {
2060
+ const type = def.type;
2061
+ if (type.kind === "union" || type.kind === "intersection") {
2062
+ const union = type;
2063
+ const isObject = value !== null && typeof value === "object" && !Array.isArray(value);
2064
+ const disc = type.kind === "union" && isObject ? discriminatorOf(union) : null;
2065
+ const picked = disc ? disc.indexMapping[String(value[disc.propertyName])] : void 0;
2066
+ expand(picked === void 0 ? union.items : [union.items[picked]], value, out);
2067
+ } else out.push(def);
2068
+ }
2069
+ }
2070
+ /** {@link dropOptionalNulls} of `value` as every one of `defs` (alternatives or parts). */ function dropNulls(defs, value) {
2071
+ if (value === null || typeof value !== "object") return value;
2072
+ const leaves = [];
2073
+ expand(defs, value, leaves);
2074
+ if (Array.isArray(value)) return dropNullsOfArray(leaves, value);
2075
+ let out;
2076
+ for (const key of Object.keys(value)) {
2077
+ const current = value[key];
2078
+ if (current !== null && typeof current !== "object") continue;
2079
+ const declared = [];
2080
+ for (const leaf of leaves) {
2081
+ const prop = leaf.type.kind === "object" ? leaf.type.props.get(key) : void 0;
2082
+ if (prop !== void 0 && !isPhantomType(prop)) declared.push(prop);
2083
+ }
2084
+ if (declared.length === 0) continue;
2085
+ if (current === null) {
2086
+ if (declared.every((prop) => prop.optional && !acceptsNull$2(prop))) {
2087
+ out ?? (out = { ...value });
2088
+ delete out[key];
2089
+ }
2090
+ continue;
2091
+ }
2092
+ const next = dropNulls(declared, current);
2093
+ if (next !== current) {
2094
+ out ?? (out = { ...value });
2095
+ out[key] = next;
2096
+ }
2097
+ }
2098
+ return out ?? value;
2099
+ }
2100
+ /** {@link dropNulls} of an array `value`: the items of every array and tuple among `leaves`. */ function dropNullsOfArray(leaves, value) {
2101
+ return mapList(value, (item, i) => {
2102
+ if (item === null || typeof item !== "object") return item;
2103
+ const declared = [];
2104
+ for (const leaf of leaves) {
2105
+ const type = leaf.type;
2106
+ if (type.kind === "array") declared.push(type.of);
2107
+ else if (type.kind === "tuple" && i < type.items.length) declared.push(type.items[i]);
2108
+ }
2109
+ return dropNulls(declared, item);
2110
+ });
2111
+ }
2112
+
1558
2113
  //#endregion
1559
2114
  //#region packages/typescript/src/runtime/default-value.ts
1560
2115
  /**
@@ -2502,6 +3057,26 @@ function* deserializeTypeDef(t, resolved) {
2502
3057
  texts
2503
3058
  };
2504
3059
  }
3060
+ /**
3061
+ * Translates the value of one metadata key (live, as a compiled type holds it — not serialized)
3062
+ * with `t`, by the rules {@link translateServed} applies to serialized metadata, so a client
3063
+ * translating compiled types reads one catalogue with the server: a text key's string (each item
3064
+ * of a `multiple` list; the named fields of a value object, e.g. `message` of `meta.required`) is
3065
+ * replaced by `t(text)` — except a primitive's built-in format message, which is reported by its
3066
+ * code. Returns `value` itself when the key holds no user text or nothing is translated; it is
3067
+ * never changed.
3068
+ *
3069
+ * Expressions are left as they are: their string literals are translated in a served type's
3070
+ * `texts`, and a client translates what an expression returns (by exact match), not its source.
3071
+ *
3072
+ * @example
3073
+ * ```ts
3074
+ * const label = translateUserText('meta.label', 'Street', text => dict[text]) // dict['Street']
3075
+ * ```
3076
+ */ function translateUserText(key, value, t) {
3077
+ const mode = userTextOf(key);
3078
+ return mode === void 0 ? value : walk(value, mode, { t });
3079
+ }
2505
3080
  /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
2506
3081
  if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
2507
3082
  if (typeof value === "string") {
@@ -2510,6 +3085,7 @@ function* deserializeTypeDef(t, resolved) {
2510
3085
  return value;
2511
3086
  }
2512
3087
  if (typeof value !== "object" || value === null) return value;
3088
+ if (ctx.texts === void 0 && typeof mode !== "object") return value;
2513
3089
  return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
2514
3090
  }
2515
3091
  /**
@@ -2524,10 +3100,12 @@ function* deserializeTypeDef(t, resolved) {
2524
3100
  const out = ctx.t(text);
2525
3101
  return typeof out === "string" ? out : void 0;
2526
3102
  }
2527
- /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
2528
- for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
3103
+ /** Adds the translated string literals of expression `source` to `ctx.texts` (a served type only). */ function collectLiterals(source, ctx) {
3104
+ const { texts } = ctx;
3105
+ if (!texts) return;
3106
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(texts, literal)) {
2529
3107
  const translated = translate(literal, ctx);
2530
- if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
3108
+ if (translated !== void 0 && translated !== literal) texts[literal] = translated;
2531
3109
  }
2532
3110
  }
2533
3111
  /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
@@ -2683,4 +3261,4 @@ let LiteralScanner = class LiteralScanner {
2683
3261
  }
2684
3262
 
2685
3263
  //#endregion
2686
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, LayerMap, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
3264
+ export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, ANTHROPIC_STRICT, LayerMap, OPENAI_STRICT, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, dropOptionalNulls, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, translateUserText, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };