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