@atscript/typescript 0.1.108 → 0.1.110

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/cli.cjs CHANGED
@@ -36,7 +36,7 @@ let node_readline = require("node:readline");
36
36
  let node_url = require("node:url");
37
37
 
38
38
  //#region packages/typescript/src/codegen/code-printer.ts
39
- function _define_property$8(obj, key, value) {
39
+ function _define_property$10(obj, key, value) {
40
40
  if (key in obj) Object.defineProperty(obj, key, {
41
41
  value,
42
42
  enumerable: true,
@@ -129,17 +129,17 @@ var CodePrinter = class {
129
129
  return " ".repeat(this.indentLevel * this.indentSize);
130
130
  }
131
131
  constructor() {
132
- _define_property$8(this, "lines", []);
133
- _define_property$8(this, "currentLine", "");
134
- _define_property$8(this, "indentLevel", 0);
135
- _define_property$8(this, "indentSize", 2);
136
- _define_property$8(this, "blockStack", []);
132
+ _define_property$10(this, "lines", []);
133
+ _define_property$10(this, "currentLine", "");
134
+ _define_property$10(this, "indentLevel", 0);
135
+ _define_property$10(this, "indentSize", 2);
136
+ _define_property$10(this, "blockStack", []);
137
137
  }
138
138
  };
139
139
 
140
140
  //#endregion
141
141
  //#region packages/typescript/src/codegen/base-renderer.ts
142
- function _define_property$7(obj, key, value) {
142
+ function _define_property$9(obj, key, value) {
143
143
  if (key in obj) Object.defineProperty(obj, key, {
144
144
  value,
145
145
  enumerable: true,
@@ -202,7 +202,7 @@ var BaseRenderer = class extends CodePrinter {
202
202
  }
203
203
  }
204
204
  constructor(doc) {
205
- super(), _define_property$7(this, "doc", void 0), _define_property$7(this, "_unused", void 0), this.doc = doc;
205
+ super(), _define_property$9(this, "doc", void 0), _define_property$9(this, "_unused", void 0), this.doc = doc;
206
206
  }
207
207
  };
208
208
 
@@ -225,7 +225,7 @@ function escapeQuotes(str) {
225
225
 
226
226
  //#endregion
227
227
  //#region packages/typescript/src/codegen/type-renderer.ts
228
- function _define_property$6(obj, key, value) {
228
+ function _define_property$8(obj, key, value) {
229
229
  if (key in obj) Object.defineProperty(obj, key, {
230
230
  value,
231
231
  enumerable: true,
@@ -649,7 +649,7 @@ var TypeRenderer = class TypeRenderer extends BaseRenderer {
649
649
  this.writeln(` */`);
650
650
  }
651
651
  constructor(doc, opts) {
652
- super(doc), _define_property$6(this, "opts", void 0), this.opts = opts;
652
+ super(doc), _define_property$8(this, "opts", void 0), this.opts = opts;
653
653
  }
654
654
  };
655
655
  function renderPrimitiveTypeDef(def) {
@@ -666,9 +666,512 @@ function renderPrimitiveTypeDef(def) {
666
666
  }
667
667
  }
668
668
 
669
+ //#endregion
670
+ //#region packages/typescript/src/runtime/validator-keys.ts
671
+ /**
672
+ * Annotation keys the validator pre-check reads, per kind of checked value — shared by the
673
+ * interpreted pre-check (validator-fast-check.ts) and the compiled checks (compiled-check/).
674
+ */ /** Annotations of a string node, in check order. */ const STRING_KEYS = [
675
+ "meta.required",
676
+ "expect.minLength",
677
+ "expect.maxLength",
678
+ "expect.pattern"
679
+ ];
680
+ /** Annotations of a number node, in check order. */ const NUMBER_KEYS = [
681
+ "expect.int",
682
+ "expect.min",
683
+ "expect.max",
684
+ "expect.exclusiveMin",
685
+ "expect.exclusiveMax"
686
+ ];
687
+ /** Annotations of a boolean node. */ const BOOLEAN_KEYS = ["meta.required"];
688
+ /** Annotations of an array node, in check order. */ const ARRAY_KEYS = [
689
+ "expect.minLength",
690
+ "expect.maxLength",
691
+ "expect.array.uniqueItems"
692
+ ];
693
+ /**
694
+ * Every annotation key the validator pre-check reads. The order is the bit order of
695
+ * compiled-check layouts: changing it changes the layout format.
696
+ */ const VALIDATOR_KEYS = [
697
+ "meta.required",
698
+ "expect.minLength",
699
+ "expect.maxLength",
700
+ "expect.pattern",
701
+ "expect.int",
702
+ "expect.min",
703
+ "expect.max",
704
+ "expect.exclusiveMin",
705
+ "expect.exclusiveMax",
706
+ "expect.array.uniqueItems"
707
+ ];
708
+ /**
709
+ * The number a length / bound annotation compares with: the annotation is either the number
710
+ * itself or an object carrying it in `field` (`{ length }`, `{ minValue }`, …).
711
+ */ function boundOf(m, field) {
712
+ return typeof m === "number" ? m : m[field];
713
+ }
714
+
715
+ //#endregion
716
+ //#region packages/typescript/src/runtime/compiled-check/tracking.ts
717
+ /**
718
+ * Mutation tracking for build-time compiled validator checks.
719
+ *
720
+ * A compiled check is bound to the live type tree before use (see registry.ts): the bind
721
+ * verifies that the tree still has the structure the check was compiled for and snapshots
722
+ * the constraint values the check reads. Every tracked mutation of an object a bind has
723
+ * read bumps one global epoch, which makes every compiled check re-bind on its next use.
724
+ *
725
+ * Tracked: `annotate()`, the metadata / props `Map` methods (`set` / `delete` / `clear`),
726
+ * the `defineAnnotatedType()` handle methods and `cloneRefProp()`. Raw property writes
727
+ * (`node.optional = …`, `type.items.push(…)`, editing a constraint object in place, …)
728
+ * cannot be seen: call {@link invalidateCompiledValidators} after them.
729
+ */ const VALIDATOR_KEY_SET = new Set(VALIDATOR_KEYS);
730
+ /** Global mutation epoch: compiled checks bound in an older epoch re-bind before use. */ let epoch = 0;
731
+ /** Some bind has watched an object (until then no mutation can affect a compiled check). */ let tracking = false;
732
+ /** Objects (nodes, type defs, metadata / props maps) read by some compiled-check bind. */ const watched = /* @__PURE__ */ new WeakSet();
733
+ /** The current mutation epoch. */ function currentEpoch() {
734
+ return epoch;
735
+ }
736
+ /** Marks `obj` as read by a bind: tracked mutations of it invalidate compiled checks. */ function watch(obj) {
737
+ tracking = true;
738
+ watched.add(obj);
739
+ }
740
+ /** Records a tracked mutation of `obj` (a no-op unless some bind has read it). */ function touched(obj) {
741
+ if (tracking && watched.has(obj)) epoch++;
742
+ }
743
+ /**
744
+ * Metadata map of runtime type nodes: a `Map` whose writes to validator annotation keys
745
+ * are tracked (see {@link invalidateCompiledValidators}). Reads are the builtin ones.
746
+ */ var AnnotationMap = class extends Map {
747
+ set(key, value) {
748
+ super.set(key, value);
749
+ if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
750
+ return this;
751
+ }
752
+ delete(key) {
753
+ const deleted = super.delete(key);
754
+ if (deleted && tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
755
+ return deleted;
756
+ }
757
+ clear() {
758
+ super.clear();
759
+ touched(this);
760
+ }
761
+ };
762
+ /** Props map of runtime object types: a `Map` whose writes are tracked. */ var PropsMap = class extends Map {
763
+ set(key, value) {
764
+ super.set(key, value);
765
+ touched(this);
766
+ return this;
767
+ }
768
+ delete(key) {
769
+ const deleted = super.delete(key);
770
+ if (deleted) touched(this);
771
+ return deleted;
772
+ }
773
+ clear() {
774
+ super.clear();
775
+ touched(this);
776
+ }
777
+ };
778
+ /** `true` when `key` is an annotation the validator pre-check reads. */ function isValidatorKey(key) {
779
+ return VALIDATOR_KEY_SET.has(key);
780
+ }
781
+
782
+ //#endregion
783
+ //#region packages/typescript/src/runtime/compiled-check/layout.ts
784
+ /**
785
+ * Layout of a compiled validator check: the structure a check was compiled for, as plain
786
+ * data. `buildLayout` (build-layout.ts) derives it from a type tree (the build-time model
787
+ * of a generated module, or a live tree in tests); the binder (registry.ts) verifies a
788
+ * live tree against it and collects the constraint values the compiled code reads into
789
+ * the K slots.
790
+ *
791
+ * ```
792
+ * Layout = [defs: Def[], root: Site, slotCount]
793
+ * Site = [optional: 0|1, keyMask, def: number | EXT | INTERP, patternShape, slot]
794
+ * Def = [FINAL, designType] | [FINAL, designType, literal]
795
+ * | [OBJECT, keys, sites] | [OBJECT_PATTERNS]
796
+ * | [ARRAY, of] | [UNION | INTERSECTION | TUPLE, items] | [UNKNOWN, kind]
797
+ * ```
798
+ * - A site is one annotated-type node (a class root, prop, array element, union / tuple /
799
+ * intersection item). A def is one type-def object: sites sharing a def index share the
800
+ * def object (by identity) at runtime, which is how shared and recursive types are
801
+ * compiled once.
802
+ * - `keyMask` has a bit (by {@link VALIDATOR_KEYS} index) per validator annotation that is
803
+ * *effective* on the node and relevant to its def (present; flags: truthy).
804
+ * `patternShape` has one char per `@expect.pattern` entry: `e` (empty, skipped),
805
+ * `n` (checked), `s` (stateful `g` / `y` regex: the check bails to the walk there).
806
+ * - `slot`: the site's first K slot (see {@link siteSlotCount}); `slotCount` is the total.
807
+ * - `EXT`: an anonymous reference into another module's type; bound to that type's own
808
+ * compiled check (as a template, against the referring node) when it has one, else
809
+ * checked by the interpreted pre-check.
810
+ * - `INTERP`: a node only known at runtime (e.g. a chained reference into another module's
811
+ * type): always checked by the interpreted pre-check.
812
+ */
813
+ /** Layout format version; checks of another version are ignored (interpreted). */ const LAYOUT_VERSION = 2;
814
+ const EXT = -1;
815
+ const INTERP = -2;
816
+ const D_FINAL = 0;
817
+ const D_OBJECT = 1;
818
+ const D_ARRAY = 2;
819
+ const D_UNION = 3;
820
+ const D_INTERSECTION = 4;
821
+ const D_TUPLE = 5;
822
+ const D_UNKNOWN = 6;
823
+ const D_OBJECT_PATTERNS = 7;
824
+ /** Def codes of the kinds with `items`, by kind name. */ const ITEMS_KIND_CODES = {
825
+ union: D_UNION,
826
+ intersection: D_INTERSECTION,
827
+ tuple: D_TUPLE
828
+ };
829
+ /** Kind names of the def codes with `items`. */ const ITEMS_KIND_NAMES = {
830
+ [D_UNION]: "union",
831
+ [D_INTERSECTION]: "intersection",
832
+ [D_TUPLE]: "tuple"
833
+ };
834
+ /** Bits of a compiled check's `flags` argument: the pre-check's TOP / IN_UNION, then options. */ const F_TOP = 1;
835
+ const F_IN_UNION = 2;
836
+ const F_ERROR = 4;
837
+ const F_STRIP = 8;
838
+ const F_PARTIAL_DEEP = 16;
839
+ const F_PARTIAL_TOP = 32;
840
+ /** Key mask bit of a validator annotation. */ function bit(key) {
841
+ return 1 << VALIDATOR_KEYS.indexOf(key);
842
+ }
843
+ function bitsOf(keys) {
844
+ let bits = 0;
845
+ for (const key of keys) bits |= bit(key);
846
+ return bits;
847
+ }
848
+ const B_REQUIRED = bit("meta.required");
849
+ const B_MIN_LENGTH = bit("expect.minLength");
850
+ const B_MAX_LENGTH = bit("expect.maxLength");
851
+ const B_PATTERN = bit("expect.pattern");
852
+ const B_INT = bit("expect.int");
853
+ const B_MIN = bit("expect.min");
854
+ const B_MAX = bit("expect.max");
855
+ const B_EX_MIN = bit("expect.exclusiveMin");
856
+ const B_EX_MAX = bit("expect.exclusiveMax");
857
+ const B_UNIQUE = bit("expect.array.uniqueItems");
858
+ /** Annotations the pre-check reads per kind of value (see validator-keys.ts). */ const STRING_BITS = bitsOf(STRING_KEYS);
859
+ const NUMBER_BITS = bitsOf(NUMBER_KEYS);
860
+ const ARRAY_BITS = bitsOf(ARRAY_KEYS);
861
+ const BOOLEAN_BITS = bitsOf(BOOLEAN_KEYS);
862
+ /** Keys whose value the compiled code reads (one K slot each). */ const VALUE_BITS = B_MIN_LENGTH | B_MAX_LENGTH | B_MIN | B_MAX | B_EX_MIN | B_EX_MAX;
863
+ const FLAG_BITS = B_REQUIRED | B_INT | B_UNIQUE;
864
+ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
865
+ /** The field holding the bound of each value key's object form. */ const BOUND_FIELDS = {
866
+ [B_MIN_LENGTH]: "length",
867
+ [B_MAX_LENGTH]: "length",
868
+ [B_MIN]: "minValue",
869
+ [B_MAX]: "maxValue",
870
+ [B_EX_MIN]: "exclusiveMinValue",
871
+ [B_EX_MAX]: "exclusiveMaxValue"
872
+ };
873
+ /**
874
+ * Validator annotations the pre-check reads for a node of this type def (the rest of the
875
+ * node's annotations cannot change its outcome, so they are not part of the layout).
876
+ */ function relevantBits(type) {
877
+ switch (type.kind) {
878
+ case "":
879
+ if (type.designType === "phantom" || type.value !== void 0) return 0;
880
+ switch (type.designType) {
881
+ case "string": return STRING_BITS;
882
+ case "number": return NUMBER_BITS;
883
+ case "boolean": return BOOLEAN_BITS;
884
+ default: return 0;
885
+ }
886
+ case "array": return ARRAY_BITS;
887
+ case "union": return ALL_BITS;
888
+ default: return 0;
889
+ }
890
+ }
891
+ /**
892
+ * {@link relevantBits} of a site (`undefined`: a type only known at runtime);
893
+ * `meta.required` also matters on any optional node.
894
+ */ function siteBits(type, optional) {
895
+ return (type === void 0 ? 0 : relevantBits(type)) | (optional ? B_REQUIRED : 0);
896
+ }
897
+ /**
898
+ * Number of K slots a site takes, from its first slot on:
899
+ * - INTERP: its interpreted check, then whether its type is a literal;
900
+ * - otherwise, for an optional `@meta.required` node ({@link hasRejectSlot}): the node
901
+ * (its `null` is rejected unless its type accepts `null`, decided live);
902
+ * - then EXT: the bound check of the referenced type, and whether that type is a literal;
903
+ * any other site: its annotation values (see {@link keySlots}).
904
+ */ function siteSlotCount(site) {
905
+ const [, mask, def, shape] = site;
906
+ if (def === INTERP) return 2;
907
+ let n = (hasRejectSlot(site) ? 1 : 0) + (def === EXT ? 2 : 0);
908
+ if (def !== EXT) {
909
+ for (let bits = mask & VALUE_BITS; bits !== 0; bits &= bits - 1) n++;
910
+ for (const c of shape) if (c === "n") n++;
911
+ }
912
+ return n;
913
+ }
914
+ /** An optional node with `@meta.required`: `null` fails unless its type accepts `null`. */ function hasRejectSlot(site) {
915
+ return site[0] === 1 && (site[1] & B_REQUIRED) !== 0;
916
+ }
917
+ /** The K slot of each annotation value of a site whose values start at slot `at`. */ function keySlots(mask, shape, at) {
918
+ let k = at;
919
+ const next = (b) => (mask & b) === 0 ? -1 : k++;
920
+ const minLength = next(B_MIN_LENGTH);
921
+ const maxLength = next(B_MAX_LENGTH);
922
+ const patterns = [];
923
+ for (const c of shape) if (c === "n") patterns.push(k++);
924
+ return {
925
+ minLength,
926
+ maxLength,
927
+ patterns,
928
+ min: next(B_MIN),
929
+ max: next(B_MAX),
930
+ exMin: next(B_EX_MIN),
931
+ exMax: next(B_EX_MAX)
932
+ };
933
+ }
934
+ /** The child sites of a def. */ function childSites(def) {
935
+ switch (def[0]) {
936
+ case D_OBJECT: return def[2];
937
+ case D_ARRAY: return [def[1]];
938
+ case D_UNION:
939
+ case D_INTERSECTION:
940
+ case D_TUPLE: return def[1];
941
+ default: return [];
942
+ }
943
+ }
944
+ /**
945
+ * Computes a node's key mask and pattern shape over `relevant` bits, and — when `out` is
946
+ * given — writes the normalised annotation values from `out[at]` on (the K slots).
947
+ * Throws on annotation values the pre-check itself would throw on (the bind then fails
948
+ * and the interpreted pre-check runs, which reproduces that behaviour).
949
+ */ function readKeys(metadata, relevant, reader, out, at = 0) {
950
+ let mask = 0;
951
+ let shape = "";
952
+ let k = at;
953
+ if (metadata.size === 0) return {
954
+ mask,
955
+ shape
956
+ };
957
+ for (let i = 0; i < VALIDATOR_KEYS.length; i++) {
958
+ const b = 1 << i;
959
+ if ((relevant & b) === 0) continue;
960
+ const raw = metadata.get(VALIDATOR_KEYS[i]);
961
+ if ((b & FLAG_BITS) !== 0) {
962
+ if (raw) mask |= b;
963
+ continue;
964
+ }
965
+ if (b === B_PATTERN) {
966
+ if (!raw) continue;
967
+ if (!Array.isArray(raw)) throw new TypeError("expect.pattern is not an array");
968
+ mask |= b;
969
+ for (const entry of raw) {
970
+ const { pattern, flags } = entry;
971
+ if (!pattern) {
972
+ shape += "e";
973
+ continue;
974
+ }
975
+ const re = reader.regex(pattern, flags);
976
+ if (re.global || re.sticky) {
977
+ shape += "s";
978
+ break;
979
+ }
980
+ shape += "n";
981
+ if (out) out[k] = re;
982
+ k++;
983
+ }
984
+ continue;
985
+ }
986
+ if (raw === void 0) continue;
987
+ mask |= b;
988
+ if (out) out[k] = boundOf(raw, BOUND_FIELDS[b]);
989
+ k++;
990
+ }
991
+ return {
992
+ mask,
993
+ shape
994
+ };
995
+ }
996
+
997
+ //#endregion
998
+ //#region packages/typescript/src/runtime/compiled-check/registry.ts
999
+ /**
1000
+ * Runtime registry and binder of build-time compiled validator checks.
1001
+ *
1002
+ * Generated `.as.js` modules (built with `tsPlugin({ compileValidators: true })`) call
1003
+ * {@link registerCompiledCheck} once per class with the class's layout and a factory of
1004
+ * its check. On first use, and again after each mutation epoch (see tracking.ts), the
1005
+ * entry is bound: `bindLayout` verifies the live type tree against the layout and collects
1006
+ * the constraint values into `K`; the factory turns `K` into the check function. A tree
1007
+ * that no longer matches leaves the entry unbound for that epoch, so the interpreted
1008
+ * pre-check runs instead — always correct, never stale.
1009
+ *
1010
+ * A registered entry is also a template: a node referencing a class of another module
1011
+ * (an `EXT` site) binds that class's layout against itself — its own annotations feed `K`
1012
+ * — so cross-module references, aliases of imported types and cloned imported props run
1013
+ * compiled code whenever their tree matches the referenced type's structure.
1014
+ *
1015
+ * The registry is module-local: classes registered with another copy of this runtime
1016
+ * (dual ESM / CJS loads, duplicate installs) and subclasses of registered classes are
1017
+ * simply validated by the interpreted pre-check.
1018
+ */
1019
+ /** Entries by class (own registrations only: a subclass is not registered). */ const entries = /* @__PURE__ */ new WeakMap();
1020
+ /** Template bindings by referring node. */ const templates = /* @__PURE__ */ new WeakMap();
1021
+ /** Some compiled check is registered (until then lookups return at once). */ let anyCompiled = false;
1022
+ /** The option bits of `opts` for a compiled check's `flags` argument. */ function optionFlags(opts) {
1023
+ const unknownProps = opts.unknownProps;
1024
+ const partial = opts.partial;
1025
+ return (unknownProps === "error" ? F_ERROR : unknownProps === "strip" ? F_STRIP : 0) | (partial === "deep" ? F_PARTIAL_DEEP : partial === true ? F_PARTIAL_TOP : 0);
1026
+ }
1027
+ let autoCompile = null;
1028
+ /** The compiled check to run for `def` in this call, or `null` (interpreted). */ function compiledCheckFor(def, env) {
1029
+ if (!anyCompiled) return null;
1030
+ let entry = entries.get(def);
1031
+ if (entry === void 0) {
1032
+ if (autoCompile === null) return null;
1033
+ autoCompile(def);
1034
+ entry = entries.get(def);
1035
+ if (entry === void 0) return null;
1036
+ }
1037
+ return entry.epoch === currentEpoch() ? entry.fn : bind(entry, entry, def, env, false);
1038
+ }
1039
+ /** (Re)binds `entry`'s layout against `node` for the current epoch. */ function bind(binding, entry, node, env, template) {
1040
+ binding.epoch = currentEpoch();
1041
+ binding.fn = null;
1042
+ binding.binding = true;
1043
+ try {
1044
+ const K = bindLayout(entry.layout, node, env, template);
1045
+ if (K !== void 0) binding.fn = entry.factory(K, env);
1046
+ } catch {} finally {
1047
+ binding.binding = false;
1048
+ }
1049
+ return binding.fn;
1050
+ }
1051
+ /**
1052
+ * Verifies the live tree of `node` against `layout` and collects the K slots; `undefined`
1053
+ * when anything differs. A `template` bind (a node referring to the layout's class) leaves
1054
+ * the root's `optional` to the referring site.
1055
+ */ function bindLayout(layout, node, env, template) {
1056
+ const [defs, root, slotCount] = layout;
1057
+ const bound = [];
1058
+ const K = [];
1059
+ K.length = slotCount;
1060
+ /** An EXT / INTERP site: its check, then whether its type is a literal. */ const bindRuntimeSite = (n, at, ext) => {
1061
+ const type = n.type;
1062
+ if (typeof type !== "object" || type === null || isPhantomType(n)) return false;
1063
+ watch(n);
1064
+ watch(type);
1065
+ K[at] = ext ? externalCheck(n, env) : interpreted(n, env);
1066
+ K[at + 1] = type.value !== void 0;
1067
+ return true;
1068
+ };
1069
+ const bindSite = (site, n) => {
1070
+ const [optional, mask, d, shape, at] = site;
1071
+ if (d === INTERP) return bindRuntimeSite(n, at, false);
1072
+ if (template && site === root ? optional !== 0 : !!n.optional !== (optional === 1)) return false;
1073
+ watch(n);
1074
+ const metadata = n.metadata;
1075
+ if (!(metadata instanceof AnnotationMap)) return false;
1076
+ watch(metadata);
1077
+ let k = at;
1078
+ if (hasRejectSlot(site)) K[k++] = n;
1079
+ if (d === EXT) return readKeys(metadata, siteBits(void 0, optional === 1), env).mask === mask && bindRuntimeSite(n, k, true);
1080
+ const type = n.type;
1081
+ if (bound[d] === void 0) {
1082
+ if (typeof type !== "object" || type === null) return false;
1083
+ bound[d] = type;
1084
+ if (!bindDef(defs[d], type)) return false;
1085
+ } else if (bound[d] !== type) return false;
1086
+ const read = readKeys(metadata, siteBits(type, optional === 1), env, K, k);
1087
+ return read.mask === mask && read.shape === shape;
1088
+ };
1089
+ const bindSites = (sites, nodes) => {
1090
+ if (!Array.isArray(nodes) || nodes.length !== sites.length) return false;
1091
+ for (let i = 0; i < sites.length; i++) if (!bindSite(sites[i], nodes[i])) return false;
1092
+ return true;
1093
+ };
1094
+ const bindDef = (def, type) => {
1095
+ watch(type);
1096
+ switch (def[0]) {
1097
+ case D_FINAL: return type.kind === "" && type.designType === def[1] && (def.length === 2 ? type.value === void 0 : type.value === def[2]);
1098
+ case D_OBJECT: {
1099
+ const props = type.props;
1100
+ if (type.kind !== "object" || !(props instanceof PropsMap) || !Array.isArray(type.propsPatterns) || type.propsPatterns.length > 0) return false;
1101
+ watch(props);
1102
+ const keys = def[1];
1103
+ const sites = def[2];
1104
+ if (props.size !== keys.length) return false;
1105
+ let i = 0;
1106
+ for (const [key, prop] of props) {
1107
+ if (key !== keys[i] || !bindSite(sites[i], prop)) return false;
1108
+ i++;
1109
+ }
1110
+ return true;
1111
+ }
1112
+ case D_OBJECT_PATTERNS: return type.kind === "object" && Array.isArray(type.propsPatterns) && type.propsPatterns.length > 0;
1113
+ case D_ARRAY: return type.kind === "array" && bindSite(def[1], type.of);
1114
+ case D_UNION:
1115
+ case D_INTERSECTION:
1116
+ case D_TUPLE: return type.kind === ITEMS_KIND_NAMES[def[0]] && bindSites(def[1], type.items);
1117
+ case D_UNKNOWN: return type.kind === def[1];
1118
+ default: return false;
1119
+ }
1120
+ };
1121
+ return bindSite(root, node) ? K : void 0;
1122
+ }
1123
+ /** The interpreted pre-check of `node` (its subtree is read live on every call). */ function interpreted(node, env) {
1124
+ const interp = env.interp;
1125
+ return (value, flags, opts) => interp(node, value, flags, opts);
1126
+ }
1127
+ /**
1128
+ * The check of a node referencing another module's type (called for a non-nullish value
1129
+ * when the node is optional; the referring site handles `optional`): the referenced class's
1130
+ * layout bound against the node when it matches, else the interpreted pre-check.
1131
+ */ function externalCheck(node, env) {
1132
+ const entry = templateOf(node);
1133
+ if (entry !== void 0) {
1134
+ let binding = templates.get(node);
1135
+ if (binding === void 0 || binding.entry !== entry) {
1136
+ binding = {
1137
+ entry,
1138
+ epoch: -1,
1139
+ fn: null,
1140
+ binding: false
1141
+ };
1142
+ templates.set(node, binding);
1143
+ }
1144
+ if (binding.binding) {
1145
+ const pending = binding;
1146
+ const fallback = interpreted(node, env);
1147
+ return (value, flags, opts) => (pending.fn ?? fallback)(value, flags, opts);
1148
+ }
1149
+ const fn = binding.epoch === currentEpoch() ? binding.fn : bind(binding, entry, node, env, true);
1150
+ if (fn !== null) return fn;
1151
+ }
1152
+ return interpreted(node, env);
1153
+ }
1154
+ /**
1155
+ * The registered class whose layout a referring node binds against: the target of its
1156
+ * (unchained) reference, through aliases of other modules' types.
1157
+ */ function templateOf(node) {
1158
+ let ref = node.ref;
1159
+ for (let hops = 0; hops < 16 && ref !== void 0 && ref.field === ""; hops++) {
1160
+ let target;
1161
+ try {
1162
+ target = ref.type();
1163
+ } catch {
1164
+ return;
1165
+ }
1166
+ const entry = entries.get(target);
1167
+ if (entry === void 0 || entry.layout[1][2] !== EXT) return entry;
1168
+ ref = target.ref;
1169
+ }
1170
+ }
1171
+
669
1172
  //#endregion
670
1173
  //#region packages/typescript/src/runtime/validator-fast-check.ts
671
- function _define_property$5(obj, key, value) {
1174
+ function _define_property$7(obj, key, value) {
672
1175
  if (key in obj) Object.defineProperty(obj, key, {
673
1176
  value,
674
1177
  enumerable: true,
@@ -692,31 +1195,78 @@ function _define_property$5(obj, key, value) {
692
1195
  * after a validator was created are always honoured — the same as the full walk.
693
1196
  *
694
1197
  * Result contract (relative to the full walk over the same node and value):
695
- * - `PASS` — the walk returns `true`, collects no errors and has no side effects.
696
- * - `FAIL` — the walk returns `false`; every node the walk would visit was visited
697
- * here too (so a walk that would throw makes this throw first) and the walk has
698
- * no side effects for this node.
1198
+ * - `PASS` — the walk returns `true`, collects no errors and has no side effects other
1199
+ * than the strips recorded here (see below).
1200
+ * - `FAIL` — the walk returns `false`. Inside a union, every node the walk would visit
1201
+ * was visited here too (so a walk that would throw makes this throw first) and the
1202
+ * walk's only side effects for this node are the strips recorded here. Outside unions
1203
+ * a `FAIL` always ends in the walk, so it may be returned early.
699
1204
  * - `BAIL` — not decidable here; the caller must run the full walk.
700
1205
  *
701
1206
  * Union branches are tried in declared order, continuing past `FAIL` and stopping
702
1207
  * at `BAIL`, which keeps union results identical to the walk.
1208
+ *
1209
+ * `unknownProps: 'strip'`: the walk deletes an object's unknown keys right after the object
1210
+ * passes (even when an ancestor fails later). This check records those deletions only for
1211
+ * the top-level object (`pendingKeys`), whose strip is the walk's last read of the input:
1212
+ * deferring an earlier strip past later reads could be observed by them (a prototype, a
1213
+ * proxy or an accessor over the stripped object), so a nested object with unknown keys
1214
+ * bails, as does any object visit once a strip is pending (a later intersection member).
1215
+ * The recorded keys are deleted, in the walk's order, only when the whole value passes —
1216
+ * so a `PASS` result still has exactly the walk's side effects, and `FAIL` / `BAIL` leave
1217
+ * the value untouched for the walk.
703
1218
  */ const FAIL = 0;
704
1219
  const PASS = 1;
705
1220
  const BAIL = 2;
706
1221
  /** Node is at walk depth 0 (only object props / array & tuple items increase depth). */ const TOP = 1;
707
1222
  /** Node is inside a union branch — failures must be exhaustive (see contract). */ const IN_UNION = 2;
708
1223
  /** Incremented per {@link fastCheckPasses} call; snapshots verified in older calls re-verify. */ let stamp = 0;
1224
+ /** A 'strip' {@link fastCheckPasses} call is in progress (the pending strips below are its own). */ let stripping = false;
1225
+ /**
1226
+ * Unknown keys of the top-level object the walk would delete (`unknownProps: 'strip'`), in
1227
+ * the walk's deletion order. Deleted when the call passes, dropped otherwise.
1228
+ */ const pendingKeys = [];
709
1229
  /**
710
- * `true` only when the full walk over `value` is guaranteed to pass with no errors
711
- * and no side effects. Any other outcome (including a throw) means "run the walk".
1230
+ * `true` only when the full walk over `value` is guaranteed to pass with no errors and
1231
+ * no side effects other than its 'strip' deletions, which are then performed here, as the
1232
+ * walk would. Any other outcome (including a throw) leaves `value` untouched and means
1233
+ * "run the walk".
712
1234
  */ function fastCheckPasses(def, value, opts) {
1235
+ if (opts.unknownProps === "strip") return fastCheckStripping(def, value, opts);
713
1236
  stamp++;
714
1237
  try {
715
- return fastCheck(def, value, TOP, opts) === PASS;
1238
+ return check(def, value, opts) === PASS;
716
1239
  } catch {
717
1240
  return false;
718
1241
  }
719
1242
  }
1243
+ /** {@link fastCheckPasses} for `unknownProps: 'strip'`: performs the recorded strips on a pass. */ function fastCheckStripping(def, value, opts) {
1244
+ if (stripping) return false;
1245
+ stamp++;
1246
+ stripping = true;
1247
+ let passed;
1248
+ try {
1249
+ passed = check(def, value, opts) === PASS;
1250
+ } catch {
1251
+ passed = false;
1252
+ } finally {
1253
+ stripping = false;
1254
+ }
1255
+ try {
1256
+ if (passed) for (const key of pendingKeys) delete value[key];
1257
+ } finally {
1258
+ pendingKeys.length = 0;
1259
+ }
1260
+ return passed;
1261
+ }
1262
+ /**
1263
+ * The pre-check of the root: the type's build-time compiled check when it has one bound to
1264
+ * the live tree (see compiled-check/registry.ts), else the interpreted one. Both share the
1265
+ * contract above and the strip state.
1266
+ */ function check(def, value, opts) {
1267
+ const compiled = compiledCheckFor(def, COMPILED_ENV);
1268
+ return compiled === null ? fastCheck(def, value, TOP, opts) : compiled(value, TOP | optionFlags(opts), opts);
1269
+ }
720
1270
  const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
721
1271
  const regexCache = /* @__PURE__ */ new Map();
722
1272
  /** Compiled `@expect.pattern` regex, cached per (pattern, flags). */ function getRegex(pattern, flags) {
@@ -750,6 +1300,14 @@ function acceptsNull(def) {
750
1300
  }
751
1301
  return false;
752
1302
  }
1303
+ /** What compiled checks share with the interpreted pre-check. */ const COMPILED_ENV = {
1304
+ pk: pendingKeys,
1305
+ ho: Object.prototype.hasOwnProperty,
1306
+ dec: DECIMAL_RE,
1307
+ regex: getRegex,
1308
+ interp: fastCheck,
1309
+ rn: rejectsNullAsRequired
1310
+ };
753
1311
  function fastCheck(def, value, flags, opts) {
754
1312
  if (def.optional && (value === void 0 || value === null)) return value === null && rejectsNullAsRequired(def) ? FAIL : PASS;
755
1313
  const type = def.type;
@@ -762,6 +1320,7 @@ function fastCheck(def, value, flags, opts) {
762
1320
  for (const item of type.items) {
763
1321
  const result = fastCheck(item, value, branchFlags, opts);
764
1322
  if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
1323
+ if (pendingKeys.length > 0) return BAIL;
765
1324
  }
766
1325
  return FAIL;
767
1326
  }
@@ -838,15 +1397,17 @@ function fastCheckString(metadata, value) {
838
1397
  }
839
1398
  function fastCheckNumber(metadata, value) {
840
1399
  if (metadata.size === 0) return PASS;
841
- return numberConstraints(value, metadata.get("expect.int"), metadata.get("expect.min"), metadata.get("expect.max"));
1400
+ return numberConstraints(value, metadata.get("expect.int"), metadata.get("expect.min"), metadata.get("expect.max"), metadata.get("expect.exclusiveMin"), metadata.get("expect.exclusiveMax"));
842
1401
  }
843
1402
  function booleanConstraints(value, required) {
844
1403
  return required && value !== true ? FAIL : PASS;
845
1404
  }
846
- function numberConstraints(value, int, min, max) {
1405
+ function numberConstraints(value, int, min, max, exMin, exMax) {
847
1406
  if (int && value % 1 !== 0) return FAIL;
848
1407
  if (min !== void 0 && value < (typeof min === "number" ? min : min.minValue)) return FAIL;
849
1408
  if (max !== void 0 && value > (typeof max === "number" ? max : max.maxValue)) return FAIL;
1409
+ if (exMin !== void 0 && value <= (typeof exMin === "number" ? exMin : exMin.exclusiveMinValue)) return FAIL;
1410
+ if (exMax !== void 0 && value >= (typeof exMax === "number" ? exMax : exMax.exclusiveMaxValue)) return FAIL;
850
1411
  return PASS;
851
1412
  }
852
1413
  /** `@expect.minLength` / `@expect.maxLength` (strings and arrays). */ function lengthFails(length, minLength, maxLength) {
@@ -860,9 +1421,12 @@ function fastCheckObject(def, value, flags, opts) {
860
1421
  if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
861
1422
  const type = def.type;
862
1423
  if (type.propsPatterns.length > 0) return BAIL;
1424
+ if (pendingKeys.length > 0) return BAIL;
1425
+ const unknownProps = opts.unknownProps;
1426
+ const inUnion = (flags & IN_UNION) !== 0;
1427
+ if (unknownProps === "error" && !inUnion && hasUnknownKey(type.props, value)) return FAIL;
863
1428
  const partial = opts.partial;
864
1429
  const skipUndefined = partial === "deep" || partial === true && (flags & TOP) !== 0;
865
- const inUnion = (flags & IN_UNION) !== 0;
866
1430
  const propFlags = flags & IN_UNION;
867
1431
  let result = PASS;
868
1432
  for (const [key, item] of type.props) {
@@ -876,16 +1440,28 @@ function fastCheckObject(def, value, flags, opts) {
876
1440
  }
877
1441
  }
878
1442
  if (result !== PASS) return result;
879
- const unknownProps = opts.unknownProps;
880
- if (unknownProps === "error" || unknownProps === "strip") {
881
- const props = type.props;
882
- for (const key of Object.keys(value)) {
883
- const known = props.get(key);
884
- if (known === void 0 || isPhantomType(known)) return unknownProps === "error" ? FAIL : BAIL;
885
- }
1443
+ if (unknownProps === "strip") return pendStrips(type.props, value, flags);
1444
+ return unknownProps === "error" && inUnion && hasUnknownKey(type.props, value) ? FAIL : PASS;
1445
+ }
1446
+ /**
1447
+ * Records the unknown keys of a passing top-level object: the walk deletes them at this
1448
+ * point, after its last read of the input. A nested object's strip would be followed by
1449
+ * more reads, so it is left to the walk.
1450
+ */ function pendStrips(props, value, flags) {
1451
+ for (const key of Object.keys(value)) if (isUnknownKey(props, key)) {
1452
+ if ((flags & TOP) === 0) return BAIL;
1453
+ pendingKeys.push(key);
886
1454
  }
887
1455
  return PASS;
888
1456
  }
1457
+ /** `true` when `value` has a key the walk treats as unknown. */ function hasUnknownKey(props, value) {
1458
+ for (const key of Object.keys(value)) if (isUnknownKey(props, key)) return true;
1459
+ return false;
1460
+ }
1461
+ /** `true` when the walk treats `key` as unknown (no prop, or a phantom one). */ function isUnknownKey(props, key) {
1462
+ const known = props.get(key);
1463
+ return known === void 0 || isPhantomType(known);
1464
+ }
889
1465
  function fastCheckArray(def, value, flags, opts) {
890
1466
  if (!Array.isArray(value)) return FAIL;
891
1467
  const metadata = def.metadata;
@@ -927,39 +1503,41 @@ function isFinalOp(op) {
927
1503
  const plans = /* @__PURE__ */ new WeakMap();
928
1504
  /** One shape for every plan, so plan field access stays monomorphic. */ let Plan = class Plan {
929
1505
  constructor(def) {
930
- _define_property$5(this, "def", void 0);
931
- /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$5(this, "stamp", void 0);
932
- /** Call in which the annotation values (`m0`–`m3`) were last verified. */ _define_property$5(this, "metaStamp", void 0);
933
- _define_property$5(this, "op", void 0);
934
- _define_property$5(this, "type", void 0);
935
- _define_property$5(this, "optional", void 0);
936
- _define_property$5(this, "metadata", void 0);
937
- _define_property$5(this, "kind", void 0);
938
- _define_property$5(this, "designType", void 0);
939
- _define_property$5(this, "literal", void 0);
940
- /** String plans: compiled `@expect.pattern` regexes by position (checked against the live entry). */ _define_property$5(this, "regexes", void 0);
1506
+ _define_property$7(this, "def", void 0);
1507
+ /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$7(this, "stamp", void 0);
1508
+ /** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$7(this, "metaStamp", void 0);
1509
+ _define_property$7(this, "op", void 0);
1510
+ _define_property$7(this, "type", void 0);
1511
+ _define_property$7(this, "optional", void 0);
1512
+ _define_property$7(this, "metadata", void 0);
1513
+ _define_property$7(this, "kind", void 0);
1514
+ _define_property$7(this, "designType", void 0);
1515
+ _define_property$7(this, "literal", void 0);
1516
+ /** String plans: compiled `@expect.pattern` regexes by position (checked against the live entry). */ _define_property$7(this, "regexes", void 0);
941
1517
  /**
942
1518
  * Annotation keys the node's check reads, and their values (`undefined` when absent):
943
1519
  * string `meta.required, expect.minLength, maxLength, pattern`; number `expect.int, min,
944
- * max`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`.
945
- */ _define_property$5(this, "k0", void 0);
946
- _define_property$5(this, "k1", void 0);
947
- _define_property$5(this, "k2", void 0);
948
- _define_property$5(this, "k3", void 0);
949
- _define_property$5(this, "m0", void 0);
950
- _define_property$5(this, "m1", void 0);
951
- _define_property$5(this, "m2", void 0);
952
- _define_property$5(this, "m3", void 0);
953
- _define_property$5(this, "props", void 0);
954
- _define_property$5(this, "propsPatterns", void 0);
955
- _define_property$5(this, "keys", void 0);
956
- /** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$5(this, "edges", void 0);
957
- /** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$5(this, "byKey", void 0);
958
- _define_property$5(this, "nodes", void 0);
959
- _define_property$5(this, "children", void 0);
960
- _define_property$5(this, "of", void 0);
961
- _define_property$5(this, "ofPlan", void 0);
962
- _define_property$5(this, "items", void 0);
1520
+ * max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`.
1521
+ */ _define_property$7(this, "k0", void 0);
1522
+ _define_property$7(this, "k1", void 0);
1523
+ _define_property$7(this, "k2", void 0);
1524
+ _define_property$7(this, "k3", void 0);
1525
+ _define_property$7(this, "k4", void 0);
1526
+ _define_property$7(this, "m0", void 0);
1527
+ _define_property$7(this, "m1", void 0);
1528
+ _define_property$7(this, "m2", void 0);
1529
+ _define_property$7(this, "m3", void 0);
1530
+ _define_property$7(this, "m4", void 0);
1531
+ _define_property$7(this, "props", void 0);
1532
+ _define_property$7(this, "propsPatterns", void 0);
1533
+ _define_property$7(this, "keys", void 0);
1534
+ /** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$7(this, "edges", void 0);
1535
+ /** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$7(this, "byKey", void 0);
1536
+ _define_property$7(this, "nodes", void 0);
1537
+ _define_property$7(this, "children", void 0);
1538
+ _define_property$7(this, "of", void 0);
1539
+ _define_property$7(this, "ofPlan", void 0);
1540
+ _define_property$7(this, "items", void 0);
963
1541
  this.def = def;
964
1542
  this.stamp = -1;
965
1543
  this.metaStamp = -1;
@@ -975,10 +1553,12 @@ const plans = /* @__PURE__ */ new WeakMap();
975
1553
  this.k1 = void 0;
976
1554
  this.k2 = void 0;
977
1555
  this.k3 = void 0;
1556
+ this.k4 = void 0;
978
1557
  this.m0 = void 0;
979
1558
  this.m1 = void 0;
980
1559
  this.m2 = void 0;
981
1560
  this.m3 = void 0;
1561
+ this.m4 = void 0;
982
1562
  this.props = void 0;
983
1563
  this.propsPatterns = void 0;
984
1564
  this.keys = EMPTY;
@@ -1028,7 +1608,7 @@ function planFor(def) {
1028
1608
  }
1029
1609
  /** Brings the annotation values up to date (once per call, when a constraint is read). */ function refreshMeta(plan) {
1030
1610
  const metadata = plan.metadata;
1031
- if (!(metadata.size === 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === void 0 : metadata.get(plan.k0) === plan.m0 && (plan.k1 === void 0 || metadata.get(plan.k1) === plan.m1) && (plan.k2 === void 0 || metadata.get(plan.k2) === plan.m2) && (plan.k3 === void 0 || metadata.get(plan.k3) === plan.m3))) snapshotMeta(plan);
1611
+ if (!(metadata.size === 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === void 0 && plan.m4 === void 0 : metadata.get(plan.k0) === plan.m0 && (plan.k1 === void 0 || metadata.get(plan.k1) === plan.m1) && (plan.k2 === void 0 || metadata.get(plan.k2) === plan.m2) && (plan.k3 === void 0 || metadata.get(plan.k3) === plan.m3) && (plan.k4 === void 0 || metadata.get(plan.k4) === plan.m4))) snapshotMeta(plan);
1032
1612
  plan.metaStamp = stamp;
1033
1613
  }
1034
1614
  function snapshotMeta(plan) {
@@ -1037,12 +1617,14 @@ function snapshotMeta(plan) {
1037
1617
  plan.m1 = metadata.get(plan.k1);
1038
1618
  plan.m2 = metadata.get(plan.k2);
1039
1619
  plan.m3 = metadata.get(plan.k3);
1620
+ plan.m4 = metadata.get(plan.k4);
1040
1621
  }
1041
- function setMetaKeys(plan, k0, k1, k2, k3) {
1622
+ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
1042
1623
  plan.k0 = k0;
1043
1624
  plan.k1 = k1;
1044
1625
  plan.k2 = k2;
1045
1626
  plan.k3 = k3;
1627
+ plan.k4 = k4;
1046
1628
  snapshotMeta(plan);
1047
1629
  plan.metaStamp = stamp;
1048
1630
  }
@@ -1068,20 +1650,20 @@ function setMetaKeys(plan, k0, k1, k2, k3) {
1068
1650
  plan.of = void 0;
1069
1651
  plan.ofPlan = void 0;
1070
1652
  plan.items = void 0;
1071
- setMetaKeys(plan, void 0, void 0, void 0, void 0);
1653
+ setMetaKeys(plan);
1072
1654
  switch (type.kind) {
1073
1655
  case "":
1074
1656
  if (type.designType === "phantom") plan.op = OP_PHANTOM;
1075
1657
  else if (type.value !== void 0) plan.op = OP_FINAL;
1076
1658
  else if (type.designType === "string") {
1077
- setMetaKeys(plan, "meta.required", "expect.minLength", "expect.maxLength", "expect.pattern");
1659
+ setMetaKeys(plan, ...STRING_KEYS);
1078
1660
  plan.regexes = [];
1079
1661
  plan.op = OP_STRING;
1080
1662
  } else if (type.designType === "number") {
1081
- setMetaKeys(plan, "expect.int", "expect.min", "expect.max", void 0);
1663
+ setMetaKeys(plan, ...NUMBER_KEYS);
1082
1664
  plan.op = OP_NUMBER;
1083
1665
  } else if (type.designType === "boolean") {
1084
- setMetaKeys(plan, "meta.required", void 0, void 0, void 0);
1666
+ setMetaKeys(plan, ...BOOLEAN_KEYS);
1085
1667
  plan.op = OP_BOOLEAN;
1086
1668
  } else plan.op = OP_FINAL;
1087
1669
  break;
@@ -1107,7 +1689,7 @@ function setMetaKeys(plan, k0, k1, k2, k3) {
1107
1689
  break;
1108
1690
  }
1109
1691
  case "array":
1110
- setMetaKeys(plan, "expect.minLength", "expect.maxLength", "expect.array.uniqueItems", void 0);
1692
+ setMetaKeys(plan, ...ARRAY_KEYS);
1111
1693
  plan.of = type.of;
1112
1694
  plan.ofPlan = planFor(type.of);
1113
1695
  plan.op = OP_ARRAY;
@@ -1179,7 +1761,7 @@ function setMetaKeys(plan, k0, k1, k2, k3) {
1179
1761
  }
1180
1762
  /** Plan counterpart of {@link fastCheckNumber}; constraint objects are read live. */ function checkNumber(plan, value) {
1181
1763
  if (plan.metaStamp !== stamp) refreshMeta(plan);
1182
- return numberConstraints(value, plan.m0, plan.m1, plan.m2);
1764
+ return numberConstraints(value, plan.m0, plan.m1, plan.m2, plan.m3, plan.m4);
1183
1765
  }
1184
1766
  /** Plan counterpart of {@link fastCheckObject}. */ function checkObject(plan, value, flags, opts) {
1185
1767
  if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
@@ -1245,7 +1827,7 @@ function setMetaKeys(plan, k0, k1, k2, k3) {
1245
1827
 
1246
1828
  //#endregion
1247
1829
  //#region packages/typescript/src/runtime/validator.ts
1248
- function _define_property$4(obj, key, value) {
1830
+ function _define_property$6(obj, key, value) {
1249
1831
  if (key in obj) Object.defineProperty(obj, key, {
1250
1832
  value,
1251
1833
  enumerable: true,
@@ -1693,7 +2275,7 @@ function _define_property$4(obj, key, value) {
1693
2275
  validateNumber(def, value) {
1694
2276
  return this.validateNumberConstraints(def.metadata, value);
1695
2277
  }
1696
- /** `@expect.int` / `min` / `max` checks for a number value. */ validateNumberConstraints(metadata, value) {
2278
+ /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */ validateNumberConstraints(metadata, value) {
1697
2279
  if (metadata.size === 0) return true;
1698
2280
  const int = metadata.get("expect.int");
1699
2281
  if (int && value % 1 !== 0) {
@@ -1704,23 +2286,30 @@ function _define_property$4(obj, key, value) {
1704
2286
  const min = metadata.get("expect.min");
1705
2287
  if (min !== void 0) {
1706
2288
  const minValue = typeof min === "number" ? min : min.minValue;
1707
- if (value < minValue) {
1708
- const message = typeof min === "object" && min.message ? min.message : `Expected minimum ${minValue}, got ${value}`;
1709
- this.error(message);
1710
- return false;
1711
- }
2289
+ if (value < minValue) return this.numberBoundFailed(min, "minimum", minValue, value);
1712
2290
  }
1713
2291
  const max = metadata.get("expect.max");
1714
2292
  if (max !== void 0) {
1715
2293
  const maxValue = typeof max === "number" ? max : max.maxValue;
1716
- if (value > maxValue) {
1717
- const message = typeof max === "object" && max.message ? max.message : `Expected maximum ${maxValue}, got ${value}`;
1718
- this.error(message);
1719
- return false;
1720
- }
2294
+ if (value > maxValue) return this.numberBoundFailed(max, "maximum", maxValue, value);
2295
+ }
2296
+ const exMin = metadata.get("expect.exclusiveMin");
2297
+ if (exMin !== void 0) {
2298
+ const bound = typeof exMin === "number" ? exMin : exMin.exclusiveMinValue;
2299
+ if (value <= bound) return this.numberBoundFailed(exMin, "greater than", bound, value);
2300
+ }
2301
+ const exMax = metadata.get("expect.exclusiveMax");
2302
+ if (exMax !== void 0) {
2303
+ const bound = typeof exMax === "number" ? exMax : exMax.exclusiveMaxValue;
2304
+ if (value >= bound) return this.numberBoundFailed(exMax, "less than", bound, value);
1721
2305
  }
1722
2306
  return true;
1723
2307
  }
2308
+ /** Reports a failed number bound: its custom message, else `Expected <label> <bound>, got <value>`. */ numberBoundFailed(annotation, label, bound, value) {
2309
+ const message = typeof annotation === "object" && annotation.message ? annotation.message : `Expected ${label} ${bound}, got ${value}`;
2310
+ this.error(message);
2311
+ return false;
2312
+ }
1724
2313
  validateBoolean(def, value) {
1725
2314
  return this.validateBooleanConstraints(def.metadata, value);
1726
2315
  }
@@ -1737,17 +2326,17 @@ function _define_property$4(obj, key, value) {
1737
2326
  return true;
1738
2327
  }
1739
2328
  constructor(def, opts) {
1740
- _define_property$4(this, "def", void 0);
1741
- _define_property$4(this, "opts", void 0);
1742
- _define_property$4(this, "hasPlugins", void 0);
1743
- _define_property$4(this, "hasReplace", void 0);
1744
- _define_property$4(this, "replaceCache", void 0);
1745
- /** Validation errors collected during the last {@link validate} call. */ _define_property$4(this, "errors", void 0);
1746
- _define_property$4(this, "stackErrors", void 0);
1747
- _define_property$4(this, "pathSegments", void 0);
1748
- _define_property$4(this, "depth", void 0);
1749
- _define_property$4(this, "limitExceeded", void 0);
1750
- _define_property$4(this, "context", void 0);
2329
+ _define_property$6(this, "def", void 0);
2330
+ _define_property$6(this, "opts", void 0);
2331
+ _define_property$6(this, "hasPlugins", void 0);
2332
+ _define_property$6(this, "hasReplace", void 0);
2333
+ _define_property$6(this, "replaceCache", void 0);
2334
+ /** Validation errors collected during the last {@link validate} call. */ _define_property$6(this, "errors", void 0);
2335
+ _define_property$6(this, "stackErrors", void 0);
2336
+ _define_property$6(this, "pathSegments", void 0);
2337
+ _define_property$6(this, "depth", void 0);
2338
+ _define_property$6(this, "limitExceeded", void 0);
2339
+ _define_property$6(this, "context", void 0);
1751
2340
  this.def = def;
1752
2341
  this.errors = [];
1753
2342
  this.stackErrors = [];
@@ -1792,7 +2381,7 @@ function _define_property$4(obj, key, value) {
1792
2381
  }
1793
2382
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */ var ValidatorError = class extends Error {
1794
2383
  constructor(errors) {
1795
- super(`${errors[0].path ? errors[0].path + ": " : ""}${errors[0].message}`), _define_property$4(this, "errors", void 0), _define_property$4(this, "name", void 0), this.errors = errors, this.name = "Validation Error";
2384
+ super(`${errors[0].path ? errors[0].path + ": " : ""}${errors[0].message}`), _define_property$6(this, "errors", void 0), _define_property$6(this, "name", void 0), this.errors = errors, this.name = "Validation Error";
1796
2385
  }
1797
2386
  };
1798
2387
 
@@ -1809,7 +2398,12 @@ const COMPLEX_KINDS = new Set([
1809
2398
  /**
1810
2399
  * Creates a minimal annotated type node from a type def and metadata map.
1811
2400
  * Centralises the shape so callers never duplicate the boilerplate.
1812
- */ function createAnnotatedTypeNode(type, metadata, opts) {
2401
+ *
2402
+ * `metadata` is used as-is (the node keeps the caller's map, so later writes through it
2403
+ * apply). When omitted, the node gets a new, tracked metadata map. Compiled validator
2404
+ * checks only bind to nodes whose metadata is tracked; nodes built over a caller-supplied
2405
+ * `Map` are always validated by the interpreted validator.
2406
+ */ function createAnnotatedTypeNode(type, metadata = new AnnotationMap(), opts) {
1813
2407
  return {
1814
2408
  __is_atscript_annotated_type: true,
1815
2409
  type,
@@ -1820,6 +2414,26 @@ const COMPLEX_KINDS = new Set([
1820
2414
  ref: opts?.ref
1821
2415
  };
1822
2416
  }
2417
+ /** A new tracked metadata map holding `entries` (see {@link createAnnotatedTypeNode}). */ function createMetadataMap(entries) {
2418
+ return new AnnotationMap(entries);
2419
+ }
2420
+ /**
2421
+ * The metadata map `defineAnnotatedType()` installs on `base`: `base.metadata` itself, except
2422
+ * that an absent map or an empty plain `Map` (what a generated class starts with:
2423
+ * `static metadata = new Map()`) is replaced by a new tracked map, so the node can bind to a
2424
+ * compiled validator check. A non-empty map or a `Map` subclass is always kept as-is (its
2425
+ * identity and overrides preserved; such a node stays interpreted).
2426
+ */ function baseMetadata(metadata) {
2427
+ return !metadata || Object.getPrototypeOf(metadata) === Map.prototype && metadata.size === 0 ? createMetadataMap() : metadata;
2428
+ }
2429
+ /** A new object type def (its props map is tracked, see {@link createAnnotatedTypeNode}). */ function createObjectTypeDef(tags = /* @__PURE__ */ new Set(), propsPatterns = []) {
2430
+ return {
2431
+ kind: "object",
2432
+ props: new PropsMap(),
2433
+ propsPatterns,
2434
+ tags
2435
+ };
2436
+ }
1823
2437
  /**
1824
2438
  * Type Guard to check if a type is atscript-annotated
1825
2439
  */ function isAnnotatedType(type) {
@@ -1832,26 +2446,36 @@ const COMPLEX_KINDS = new Set([
1832
2446
  if (!metadata) return;
1833
2447
  if (asArray) if (metadata.has(key)) {
1834
2448
  const a = metadata.get(key);
1835
- if (Array.isArray(a)) a.push(value);
1836
- else metadata.set(key, [a, value]);
2449
+ if (Array.isArray(a)) {
2450
+ a.push(value);
2451
+ if (isValidatorKey(key)) touched(metadata);
2452
+ } else metadata.set(key, [a, value]);
1837
2453
  } else metadata.set(key, [value]);
1838
2454
  else metadata.set(key, value);
1839
2455
  }
2456
+ /**
2457
+ * Clones a property's type tree in-place so mutations don't leak to shared refs.
2458
+ * Used by mutating annotate codegen when paths cross ref boundaries.
2459
+ */ function cloneRefProp(parentType, propName) {
2460
+ if (parentType.kind !== "object") return;
2461
+ const objType = parentType;
2462
+ const existing = objType.props.get(propName);
2463
+ if (!existing) return;
2464
+ objType.props.set(propName, cloneNode(existing, cloneTypeDef(existing.type)));
2465
+ }
2466
+ /** A copy of `node` (own metadata map) over `type`. */ function cloneNode(node, type) {
2467
+ return createAnnotatedTypeNode(type, createMetadataMap(node.metadata), {
2468
+ id: node.id,
2469
+ optional: node.optional,
2470
+ ref: node.ref
2471
+ });
2472
+ }
1840
2473
  function cloneTypeDef(type) {
1841
2474
  if (type.kind === "object") {
1842
2475
  const obj = type;
1843
- const props = /* @__PURE__ */ new Map();
1844
- for (const [k, v] of obj.props) props.set(k, createAnnotatedTypeNode(v.type, new Map(v.metadata), {
1845
- id: v.id,
1846
- optional: v.optional,
1847
- ref: v.ref
1848
- }));
1849
- return {
1850
- kind: "object",
1851
- props,
1852
- propsPatterns: [...obj.propsPatterns],
1853
- tags: new Set(obj.tags)
1854
- };
2476
+ const clone = createObjectTypeDef(new Set(obj.tags), [...obj.propsPatterns]);
2477
+ for (const [k, v] of obj.props) clone.props.set(k, cloneNode(v, v.type));
2478
+ return clone;
1855
2479
  }
1856
2480
  if (type.kind === "array") {
1857
2481
  const arr = type;
@@ -1896,14 +2520,15 @@ function cloneTypeDef(type) {
1896
2520
  const kind = _kind || "";
1897
2521
  const baseProvided = base !== void 0;
1898
2522
  const type = base?.type || {};
2523
+ touched(type);
1899
2524
  type.kind = kind;
1900
2525
  if (COMPLEX_KINDS.has(kind)) type.items = [];
1901
2526
  if (kind === "object") {
1902
- type.props = /* @__PURE__ */ new Map();
2527
+ type.props = new PropsMap();
1903
2528
  type.propsPatterns = [];
1904
2529
  }
1905
2530
  type.tags = /* @__PURE__ */ new Set();
1906
- const metadata = base?.metadata || /* @__PURE__ */ new Map();
2531
+ const metadata = baseMetadata(base?.metadata);
1907
2532
  const payload = {
1908
2533
  __is_atscript_annotated_type: true,
1909
2534
  metadata,
@@ -1921,18 +2546,22 @@ function cloneTypeDef(type) {
1921
2546
  },
1922
2547
  designType(value) {
1923
2548
  this.$def.designType = value;
2549
+ touched(this.$def);
1924
2550
  return this;
1925
2551
  },
1926
2552
  value(value) {
1927
2553
  this.$def.value = value;
2554
+ touched(this.$def);
1928
2555
  return this;
1929
2556
  },
1930
2557
  of(value) {
1931
2558
  this.$def.of = value;
2559
+ touched(this.$def);
1932
2560
  return this;
1933
2561
  },
1934
2562
  item(value) {
1935
2563
  this.$def.items.push(value);
2564
+ touched(this.$def);
1936
2565
  return this;
1937
2566
  },
1938
2567
  prop(name, value) {
@@ -1944,10 +2573,12 @@ function cloneTypeDef(type) {
1944
2573
  pattern,
1945
2574
  def
1946
2575
  });
2576
+ touched(this.$def);
1947
2577
  return this;
1948
2578
  },
1949
2579
  optional(value = true) {
1950
2580
  this.$type.optional = value;
2581
+ touched(this.$type);
1951
2582
  return this;
1952
2583
  },
1953
2584
  copyMetadata(fromMetadata, ignore) {
@@ -1956,6 +2587,7 @@ function cloneTypeDef(type) {
1956
2587
  },
1957
2588
  refTo(type, chain) {
1958
2589
  const node = this.$type;
2590
+ touched(node);
1959
2591
  const field = chain ? chain.join(".") : "";
1960
2592
  if (isAnnotatedType(type)) {
1961
2593
  let newBase = type;
@@ -2213,36 +2845,42 @@ function cloneTypeDef(type) {
2213
2845
  }
2214
2846
  /** `@expect.minLength` / `maxLength` → `minItems` / `maxItems` on an array schema. */ function applyArrayConstraints(schema, meta) {
2215
2847
  const minLength = meta.get("expect.minLength");
2216
- if (minLength !== void 0) schema.minItems = typeof minLength === "number" ? minLength : minLength.length;
2848
+ if (minLength !== void 0) schema.minItems = boundOf(minLength, "length");
2217
2849
  const maxLength = meta.get("expect.maxLength");
2218
- if (maxLength !== void 0) schema.maxItems = typeof maxLength === "number" ? maxLength : maxLength.length;
2850
+ if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
2219
2851
  }
2220
2852
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
2221
2853
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
2222
2854
  if (schema.type === "string") {
2223
2855
  if (meta.get("meta.required")) schema.minLength = 1;
2224
2856
  const minLength = meta.get("expect.minLength");
2225
- if (minLength !== void 0) schema.minLength = typeof minLength === "number" ? minLength : minLength.length;
2857
+ if (minLength !== void 0) schema.minLength = boundOf(minLength, "length");
2226
2858
  const maxLength = meta.get("expect.maxLength");
2227
- if (maxLength !== void 0) schema.maxLength = typeof maxLength === "number" ? maxLength : maxLength.length;
2859
+ if (maxLength !== void 0) schema.maxLength = boundOf(maxLength, "length");
2228
2860
  const patterns = meta.get("expect.pattern");
2229
2861
  if (patterns?.length) if (patterns.length === 1) schema.pattern = patterns[0].pattern;
2230
2862
  else schema.allOf = (schema.allOf || []).concat(patterns.map((p) => ({ pattern: p.pattern })));
2231
2863
  }
2232
2864
  if (schema.type === "number" || schema.type === "integer") {
2233
2865
  const min = meta.get("expect.min");
2234
- if (min !== void 0) schema.minimum = typeof min === "number" ? min : min.minValue;
2866
+ if (min !== void 0) schema.minimum = boundOf(min, "minValue");
2235
2867
  const max = meta.get("expect.max");
2236
- if (max !== void 0) schema.maximum = typeof max === "number" ? max : max.maxValue;
2868
+ if (max !== void 0) schema.maximum = boundOf(max, "maxValue");
2869
+ const exMin = meta.get("expect.exclusiveMin");
2870
+ if (exMin !== void 0) schema.exclusiveMinimum = boundOf(exMin, "exclusiveMinValue");
2871
+ const exMax = meta.get("expect.exclusiveMax");
2872
+ if (exMax !== void 0) schema.exclusiveMaximum = boundOf(exMax, "exclusiveMaxValue");
2237
2873
  }
2238
2874
  }
2239
2875
  const LOWER_BOUNDS = new Set([
2240
2876
  "minimum",
2877
+ "exclusiveMinimum",
2241
2878
  "minLength",
2242
2879
  "minItems"
2243
2880
  ]);
2244
2881
  const UPPER_BOUNDS = new Set([
2245
2882
  "maximum",
2883
+ "exclusiveMaximum",
2246
2884
  "maxLength",
2247
2885
  "maxItems"
2248
2886
  ]);
@@ -2276,6 +2914,662 @@ const UPPER_BOUNDS = new Set([
2276
2914
  }
2277
2915
  }
2278
2916
 
2917
+ //#endregion
2918
+ //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
2919
+ /**
2920
+ * Build-time layout derivation (renderer and tests; not part of the runtime bundle).
2921
+ */
2922
+ /**
2923
+ * Derives the layout of `root` (see layout.ts). Shared / recursive type defs are recorded
2924
+ * once and referenced by index.
2925
+ */ function buildLayout(root, reader, classify) {
2926
+ const defs = [];
2927
+ const index = /* @__PURE__ */ new Map();
2928
+ let slots = 0;
2929
+ function describeDef(type) {
2930
+ switch (type.kind) {
2931
+ case "": return type.value === void 0 ? [D_FINAL, type.designType] : [
2932
+ D_FINAL,
2933
+ type.designType,
2934
+ type.value
2935
+ ];
2936
+ case "object": {
2937
+ if (type.propsPatterns.length > 0) return [D_OBJECT_PATTERNS];
2938
+ const props = [...type.props];
2939
+ return [
2940
+ D_OBJECT,
2941
+ props.map(([key]) => key),
2942
+ props.map(([, prop]) => site(prop))
2943
+ ];
2944
+ }
2945
+ case "array": return [D_ARRAY, site(type.of)];
2946
+ case "union":
2947
+ case "intersection":
2948
+ case "tuple": return [ITEMS_KIND_CODES[type.kind], type.items.map(site)];
2949
+ default: return [D_UNKNOWN, String(type.kind)];
2950
+ }
2951
+ }
2952
+ function site(node) {
2953
+ const type = node.type;
2954
+ const marker = classify?.(type);
2955
+ const optional = !marker || marker === "ext" ? node.optional ? 1 : 0 : 0;
2956
+ let d;
2957
+ let keys = {
2958
+ mask: 0,
2959
+ shape: ""
2960
+ };
2961
+ if (marker === "interp") d = INTERP;
2962
+ else if (marker === "ext") {
2963
+ d = EXT;
2964
+ keys = readKeys(node.metadata, siteBits(void 0, optional === 1), reader);
2965
+ } else {
2966
+ d = index.get(type) ?? -1;
2967
+ if (d < 0) {
2968
+ d = defs.length;
2969
+ defs.push([]);
2970
+ index.set(type, d);
2971
+ defs[d] = describeDef(type);
2972
+ }
2973
+ keys = readKeys(node.metadata, siteBits(type, optional === 1), reader);
2974
+ }
2975
+ const result = [
2976
+ optional,
2977
+ keys.mask,
2978
+ d,
2979
+ keys.shape,
2980
+ slots
2981
+ ];
2982
+ slots += siteSlotCount(result);
2983
+ return result;
2984
+ }
2985
+ return [
2986
+ defs,
2987
+ site(root),
2988
+ slots
2989
+ ];
2990
+ }
2991
+ /** JS source of a layout literal (plain arrays, strings and numbers incl. NaN / ±Infinity / -0). */ function layoutSource(value) {
2992
+ if (Array.isArray(value)) return `[${value.map(layoutSource).join(",")}]`;
2993
+ return literalSource(value);
2994
+ }
2995
+ /** JS source of a primitive literal. */ function literalSource(value) {
2996
+ if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
2997
+ if (typeof value === "string") return JSON.stringify(value).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
2998
+ if (value === void 0) return "undefined";
2999
+ return JSON.stringify(value);
3000
+ }
3001
+
3002
+ //#endregion
3003
+ //#region packages/typescript/src/runtime/compiled-check/emit.ts
3004
+ /**
3005
+ * Emits the JS source of a compiled validator check factory from its layout.
3006
+ *
3007
+ * Build-time only (the renderer, and test code): the runtime never generates code. The
3008
+ * emitted factory `(K, H) => check` mirrors the interpreted pre-check
3009
+ * (validator-fast-check.ts) node for node — the same checks with the same PASS (1) /
3010
+ * FAIL (0) / BAIL (2) contract — specialised to the layout: one function per object type
3011
+ * def and per def that closes a reference cycle, everything else inlined.
3012
+ *
3013
+ * Generated code conventions:
3014
+ * - Every function is `(v, f, o)`: the value, the flags (TOP, IN_UNION and option bits —
3015
+ * see `optionFlags`) and the validator options (passed on to interpreted sub-checks).
3016
+ * - A FAIL statement always leaves the current check: `return 0` outside unions; inside a
3017
+ * union (where failures must visit everything the walk would) it records the failure and
3018
+ * jumps past the failed node. `q` (`IN_UNION` unset) picks between the two when only the
3019
+ * runtime flags tell. BAIL is always `return 2`.
3020
+ * - Annotation values are closure constants `k<slot>` read from `K` once per bind.
3021
+ */ function _define_property$5(obj, key, value) {
3022
+ if (key in obj) Object.defineProperty(obj, key, {
3023
+ value,
3024
+ enumerable: true,
3025
+ configurable: true,
3026
+ writable: true
3027
+ });
3028
+ else obj[key] = value;
3029
+ return obj;
3030
+ }
3031
+ const ROOT_CTX = {
3032
+ fail: "return 0",
3033
+ inUnionFail: "return 0",
3034
+ union: false,
3035
+ clearTop: false
3036
+ };
3037
+ /** Factory-level helpers (see `TCompiledHelpers`), in declaration order. */ const HELPERS = [
3038
+ ["pk", /\bpk\./],
3039
+ ["ho", /\bho\.call\(/],
3040
+ ["dec", /\bdec\.test\(/],
3041
+ ["rn", /\brn\(/]
3042
+ ];
3043
+ /** Source of the check factory `(K, H) => check` of `layout`. */ function emitCheckFactory(layout) {
3044
+ return new CheckEmitter(layout).emit();
3045
+ }
3046
+ let CheckEmitter = class CheckEmitter {
3047
+ emit() {
3048
+ const body = [];
3049
+ for (let d = 0; d < this.defs.length; d++) if (this.fn[d]) body.push(...this.defFunction(d));
3050
+ const root = this.layout[1];
3051
+ const rootDef = root[2] >= 0 ? this.defs[root[2]][0] : -1;
3052
+ if (root[0] === 0 && this.fn[root[2]] && (rootDef === D_OBJECT || rootDef === D_OBJECT_PATTERNS || rootDef === D_TUPLE || rootDef === D_INTERSECTION)) body.push(`return d${root[2]}`);
3053
+ else {
3054
+ body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
3055
+ body.push("return r");
3056
+ }
3057
+ const code = body.join("\n");
3058
+ const head = [];
3059
+ const helpers = HELPERS.filter(([, use]) => use.test(code)).map(([h]) => `${h} = H.${h}`);
3060
+ if (helpers.length > 0) head.push(`const ${helpers.join(", ")}`);
3061
+ const slots = [...new Set(Array.from(code.matchAll(/\bk(\d+)\b/g), (m) => Number(m[1])))].filter((k) => k < this.layout[2]).sort((a, b) => a - b);
3062
+ for (let i = 0; i < slots.length; i += 16) head.push(`const ${slots.slice(i, i + 16).map((k) => `k${k} = K[${k}]`).join(", ")}`);
3063
+ return [
3064
+ "(K, H) => {",
3065
+ ...indent([...head, ...body]),
3066
+ "}"
3067
+ ].join("\n");
3068
+ }
3069
+ /**
3070
+ * Object defs get a function each; so does every def a reference cycle passes through
3071
+ * (each back-edge target of a DFS), which keeps inlining finite.
3072
+ */ functionDefs() {
3073
+ const defs = this.defs;
3074
+ const fn = defs.map((def) => def[0] === D_OBJECT || def[0] === D_OBJECT_PATTERNS);
3075
+ const state = Array.from({ length: defs.length }).fill(0);
3076
+ const dfs = (d) => {
3077
+ state[d] = 1;
3078
+ for (const site of childSites(defs[d])) {
3079
+ const c = site[2];
3080
+ if (c < 0) continue;
3081
+ if (state[c] === 1) fn[c] = true;
3082
+ else if (state[c] === 0) dfs(c);
3083
+ }
3084
+ state[d] = 2;
3085
+ };
3086
+ for (let d = 0; d < defs.length; d++) if (state[d] === 0) dfs(d);
3087
+ return fn;
3088
+ }
3089
+ next(prefix) {
3090
+ return `${prefix}${this.uid++}`;
3091
+ }
3092
+ /** A check function `name(v, f, o)` declaring the `q` / `t` locals its body uses. */ fnLines(name, body) {
3093
+ const lines = body();
3094
+ const code = lines.join("\n");
3095
+ const locals = [];
3096
+ if (code.includes("if (q) return 0")) locals.push(`const q = (f & ${F_IN_UNION}) === 0`);
3097
+ if (/\bt = /.test(code)) locals.push("let t");
3098
+ return [
3099
+ `function ${name}(v, f, o) {`,
3100
+ ...indent([...locals, ...lines]),
3101
+ "}"
3102
+ ];
3103
+ }
3104
+ defFunction(d) {
3105
+ const def = this.defs[d];
3106
+ return this.fnLines(`d${d}`, () => {
3107
+ switch (def[0]) {
3108
+ case D_OBJECT: return this.objectBody(def);
3109
+ case D_OBJECT_PATTERNS: return [`if (${notObject("v")}) return 0`, "return 2"];
3110
+ case D_ARRAY: return [...this.items(def[1], "v", ROOT_CTX), "return 1"];
3111
+ case D_UNION: return [...this.unionBranches(def[1], "v", false, (item) => [`return ${choose(this.literalExpr(item), "3", "1")}`]), "return 0"];
3112
+ case D_TUPLE: return [...this.tuple(def[1], "v", ROOT_CTX), "return 1"];
3113
+ case D_INTERSECTION: return [...def[1].flatMap((item) => this.site(item, "v", ROOT_CTX)), "return 1"];
3114
+ default: return ["return 2"];
3115
+ }
3116
+ });
3117
+ }
3118
+ /** Mirrors `fastCheckObject` (+ `pendStrips` / `hasUnknownKey`). */ objectBody(def) {
3119
+ const sites = def[2];
3120
+ const props = def[1].map((key, i) => ({
3121
+ key,
3122
+ site: sites[i]
3123
+ })).filter((p) => !this.isPhantom(p.site));
3124
+ const lines = [`if (${notObject("v")}) return 0`, "if (pk.length !== 0) return 2"];
3125
+ if (props.some((p) => p.site[0] === 0 || p.site[2] === INTERP)) {
3126
+ const top = F_PARTIAL_TOP | F_TOP;
3127
+ lines.push(`const sk = (f & ${F_PARTIAL_DEEP}) !== 0 || (f & ${top}) === ${top}`);
3128
+ }
3129
+ if (props.length > 0) lines.push("let r = 1");
3130
+ for (const { key, site } of props) {
3131
+ const p = this.next("P");
3132
+ const x = this.next("x");
3133
+ const access = validIdentifier.test(key) ? `v.${key}` : `v[${literalSource(key)}]`;
3134
+ lines.push(`${p}: {`, ` const ${x} = ${access}`);
3135
+ if (site[0] === 0 || site[2] === INTERP) lines.push(` if (${x} === undefined && sk) break ${p}`);
3136
+ const ctx = recordingCtx(`r = 0; break ${p}`, false, true);
3137
+ lines.push(...indent(this.site(site, x, ctx)), "}");
3138
+ }
3139
+ if (props.length > 0) lines.push("if (r === 0) return 0");
3140
+ const known = props.map((p) => p.key);
3141
+ const onUnknown = `{ if ((f & ${F_ERROR}) !== 0) return 0; if ((f & ${F_TOP}) === 0) return 2; pk.push(k) }`;
3142
+ const scan = known.length === 0 ? [`for (const k in v) if (ho.call(v, k)) ${onUnknown}`] : [
3143
+ "for (const k in v) {",
3144
+ " switch (k) {",
3145
+ ...known.map((key) => ` case ${literalSource(key)}:`),
3146
+ " break",
3147
+ " default:",
3148
+ ` if (ho.call(v, k)) ${onUnknown}`,
3149
+ " }",
3150
+ "}"
3151
+ ];
3152
+ lines.push(`if ((f & ${F_ERROR | F_STRIP}) !== 0) {`, ...indent(scan), "}", "return 1");
3153
+ return lines;
3154
+ }
3155
+ isPhantom(site) {
3156
+ const d = site[2];
3157
+ return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "phantom";
3158
+ }
3159
+ isLiteralDef(d) {
3160
+ return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d].length > 2;
3161
+ }
3162
+ /** A required `never` union branch: it can never match (skipped). */ isNever(site) {
3163
+ const d = site[2];
3164
+ return site[0] === 0 && d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "never" && !this.isLiteralDef(d);
3165
+ }
3166
+ /** Expression telling whether the site's type is a literal (`'true'` / `'false'` when known). */ literalExpr(site) {
3167
+ const [, , d, , slot] = site;
3168
+ if (d >= 0) return this.isLiteralDef(d) ? "true" : "false";
3169
+ return `k${d === INTERP ? slot + 1 : slot + (hasRejectSlot(site) ? 1 : 0) + 1}`;
3170
+ }
3171
+ /** Mirrors `fastCheck` for one node holding `x`. */ site(site, x, ctx) {
3172
+ const [optional, mask, d, shape, slot] = site;
3173
+ if (d === INTERP) return this.call(`k${slot}`, x, ctx);
3174
+ let at = slot;
3175
+ const rej = hasRejectSlot(site) ? at++ : -1;
3176
+ const body = d === EXT ? this.call(`k${at}`, x, ctx) : this.def(d, mask, shape, at, x, ctx);
3177
+ if (!optional) return body;
3178
+ if (rej < 0) return body.length > 0 ? [
3179
+ `if (${x} !== undefined && ${x} !== null) {`,
3180
+ ...indent(body),
3181
+ "}"
3182
+ ] : [];
3183
+ const lines = [`if (${x} === undefined || ${x} === null) {`, ` if (${x} === null && rn(k${rej})) ${ctx.fail}`];
3184
+ if (body.length > 0) lines.push("} else {", ...indent(body));
3185
+ lines.push("}");
3186
+ return lines;
3187
+ }
3188
+ /** Calls a check function returning 0 / 1 / 2. */ call(fn, x, ctx) {
3189
+ this.calls++;
3190
+ return [`t = ${fn}(${x}, ${flags(ctx)}, o)`, `if (t !== 1) { if (t === 2) return 2; ${unblock(ctx.fail)} }`];
3191
+ }
3192
+ def(d, mask, shape, at, x, ctx) {
3193
+ const def = this.defs[d];
3194
+ const kind = def[0];
3195
+ if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) return this.call(`d${d}`, x, ctx);
3196
+ switch (kind) {
3197
+ case D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
3198
+ case D_ARRAY: return [
3199
+ `if (!Array.isArray(${x})) ${ctx.fail}`,
3200
+ ...this.arrayConstraints(mask, keySlots(mask, shape, at), x, ctx.fail),
3201
+ ...this.fn[d] ? this.call(`d${d}`, x, ctx) : this.items(def[1], x, ctx)
3202
+ ];
3203
+ case D_UNION: {
3204
+ const constraints = this.unionConstraints(mask, shape, at, x, ctx.fail);
3205
+ if (!this.fn[d]) return this.union(def[1], {
3206
+ mask,
3207
+ shape,
3208
+ at
3209
+ }, constraints, x, ctx);
3210
+ this.calls++;
3211
+ const lines = [
3212
+ `t = d${d}(${x}, ${flags(ctx)}, o)`,
3213
+ "if (t === 2) return 2",
3214
+ `if (t === 0) ${ctx.fail}`
3215
+ ];
3216
+ if (constraints.length > 0) lines.push("if (t === 1) {", ...indent(constraints), "}");
3217
+ return lines;
3218
+ }
3219
+ case D_INTERSECTION: return def[1].flatMap((item) => this.site(item, x, ctx));
3220
+ case D_TUPLE: return this.tuple(def[1], x, ctx);
3221
+ default: return ["return 2"];
3222
+ }
3223
+ }
3224
+ /** Mirrors `fastCheckFinal` + the string / number / boolean constraints. */ final(def, mask, shape, at, x, fail) {
3225
+ const designType = def[1];
3226
+ if (designType === "phantom") return [];
3227
+ if (def.length > 2) return [`if (${x} !== ${literalSource(def[2])}) ${fail}`];
3228
+ const ks = keySlots(mask, shape, at);
3229
+ switch (designType) {
3230
+ case "string": return this.stringChecks(mask, shape, ks, x, fail, [`typeof ${x} !== "string"`]);
3231
+ case "number": return this.numberChecks(mask, ks, x, fail, [`typeof ${x} !== "number"`, `!Number.isFinite(${x})`]);
3232
+ case "boolean": {
3233
+ const conds = [`typeof ${x} !== "boolean"`];
3234
+ if (mask & B_REQUIRED) conds.push(`${x} !== true`);
3235
+ return [`if (${conds.join(" || ")}) ${fail}`];
3236
+ }
3237
+ case "any": return [];
3238
+ case "never": return [fail];
3239
+ case "undefined": return [`if (${x} !== undefined) ${fail}`];
3240
+ case "null": return [`if (${x} !== null) ${fail}`];
3241
+ case "decimal": return [`if (typeof ${x} !== "string" || !dec.test(${x})) ${fail}`];
3242
+ default: return ["return 2"];
3243
+ }
3244
+ }
3245
+ stringChecks(mask, shape, ks, x, fail, conds) {
3246
+ if (mask & B_REQUIRED) conds.push(`${x}.trim().length === 0`);
3247
+ if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
3248
+ if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
3249
+ const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
3250
+ let p = 0;
3251
+ for (const c of shape) if (c === "n") lines.push(`if (!k${ks.patterns[p++]}.test(${x})) ${fail}`);
3252
+ else if (c === "s") {
3253
+ lines.push("return 2");
3254
+ break;
3255
+ }
3256
+ return lines;
3257
+ }
3258
+ numberChecks(mask, ks, x, fail, conds) {
3259
+ if (mask & B_INT) conds.push(`${x} % 1 !== 0`);
3260
+ if (ks.min >= 0) conds.push(`${x} < k${ks.min}`);
3261
+ if (ks.max >= 0) conds.push(`${x} > k${ks.max}`);
3262
+ if (ks.exMin >= 0) conds.push(`${x} <= k${ks.exMin}`);
3263
+ if (ks.exMax >= 0) conds.push(`${x} >= k${ks.exMax}`);
3264
+ return conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
3265
+ }
3266
+ /** Array length constraints; `uniqueItems` (duplicate detection) is left to the walk. */ arrayConstraints(mask, ks, x, fail) {
3267
+ const conds = [];
3268
+ if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
3269
+ if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
3270
+ const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
3271
+ if (mask & B_UNIQUE) lines.push("return 2");
3272
+ return lines;
3273
+ }
3274
+ /** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
3275
+ const ks = keySlots(mask, shape, at);
3276
+ const branches = [];
3277
+ if (mask & STRING_BITS) branches.push([`typeof ${x} === "string"`, this.stringChecks(mask, shape, ks, x, fail, [])]);
3278
+ if (mask & NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
3279
+ if (mask & B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
3280
+ if (mask & ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
3281
+ const lines = [];
3282
+ branches.forEach(([cond, body], i) => {
3283
+ lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
3284
+ });
3285
+ if (lines.length > 0) lines.push("}");
3286
+ return lines;
3287
+ }
3288
+ /**
3289
+ * The union-level constraints after a non-literal branch passed. A required (non-optional)
3290
+ * branch of a known primitive / array type fixes `typeof`: only that part applies.
3291
+ */ branchConstraints(item, { mask, shape, at }, constraints, x, fail) {
3292
+ const [optional, , d] = item;
3293
+ const def = this.defs[d];
3294
+ if (optional) return constraints;
3295
+ const ks = keySlots(mask, shape, at);
3296
+ if (def[0] === D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
3297
+ if (def[0] !== D_FINAL) return constraints;
3298
+ switch (def[1]) {
3299
+ case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
3300
+ case "number": return this.numberChecks(mask, ks, x, fail, []);
3301
+ case "boolean": return mask & B_REQUIRED ? [`if (${x} !== true) ${fail}`] : [];
3302
+ case "null":
3303
+ case "undefined": return [];
3304
+ default: return constraints;
3305
+ }
3306
+ }
3307
+ /**
3308
+ * Mirrors the `fastCheck` union case: branches in declared order, each a labelled block a
3309
+ * FAIL breaks out of; `onMatch` ends a passing branch.
3310
+ */ unionBranches(items, x, clearTop, onMatch) {
3311
+ const lines = [];
3312
+ for (const item of items) {
3313
+ if (this.isNever(item)) continue;
3314
+ const b = this.next("B");
3315
+ const calls = this.calls;
3316
+ const fail = `break ${b}`;
3317
+ const body = this.site(item, x, {
3318
+ fail,
3319
+ inUnionFail: fail,
3320
+ union: true,
3321
+ clearTop
3322
+ });
3323
+ lines.push(`${b}: {`, ...indent([...body, ...onMatch(item)]), "}");
3324
+ if (this.calls !== calls) lines.push("if (pk.length !== 0) return 2");
3325
+ }
3326
+ return lines;
3327
+ }
3328
+ /** An inline union: the first matching branch passes after the union-level constraints. */ union(items, keys, constraints, x, ctx) {
3329
+ const u = this.next("U");
3330
+ const branches = this.unionBranches(items, x, ctx.clearTop, (item) => {
3331
+ const lines = [];
3332
+ const literal = constraints.length > 0 ? this.literalExpr(item) : "true";
3333
+ if (literal === "false") lines.push(...this.branchConstraints(item, keys, constraints, x, ctx.fail));
3334
+ else if (literal !== "true") lines.push(`if (!${literal}) {`, ...indent(constraints), "}");
3335
+ lines.push(`break ${u}`);
3336
+ return lines;
3337
+ });
3338
+ return [
3339
+ `${u}: {`,
3340
+ ...indent([...branches, ctx.fail]),
3341
+ "}"
3342
+ ];
3343
+ }
3344
+ /** Mirrors `checkItems`: every item is visited inside a union (BAIL beats FAIL). */ items(of, x, ctx) {
3345
+ const y = this.next("y");
3346
+ const a = this.next("a");
3347
+ const body = this.site(of, y, recordingCtx(`${a} = 0; continue`, ctx.union, true));
3348
+ if (body.length === 0) return [`for (const ${y} of ${x}) {}`];
3349
+ return [
3350
+ `let ${a} = 1`,
3351
+ `for (const ${y} of ${x}) {`,
3352
+ ...indent(body),
3353
+ "}",
3354
+ `if (${a} === 0) ${ctx.inUnionFail}`
3355
+ ];
3356
+ }
3357
+ /** Mirrors the `fastCheck` tuple case: stops at the first non-passing item. */ tuple(items, x, ctx) {
3358
+ const lines = [`if (!Array.isArray(${x}) || ${x}.length !== ${items.length}) ${ctx.fail}`];
3359
+ items.forEach((item, i) => {
3360
+ const e = this.next("e");
3361
+ lines.push(`const ${e} = ${x}[${i}]`, ...this.site(item, e, {
3362
+ ...ctx,
3363
+ clearTop: true
3364
+ }));
3365
+ });
3366
+ return lines;
3367
+ }
3368
+ constructor(layout) {
3369
+ _define_property$5(this, "layout", void 0);
3370
+ _define_property$5(this, "defs", void 0);
3371
+ /** Def index → emitted as its own function. */ _define_property$5(this, "fn", void 0);
3372
+ _define_property$5(this, "uid", void 0);
3373
+ /** Calls emitted so far (a union branch without calls cannot record strips). */ _define_property$5(this, "calls", void 0);
3374
+ this.layout = layout;
3375
+ this.uid = 0;
3376
+ this.calls = 0;
3377
+ this.defs = layout[0];
3378
+ this.fn = this.functionDefs();
3379
+ }
3380
+ };
3381
+ /**
3382
+ * Context of a node whose failure is recorded (`record`: e.g. `r = 0; break P1`) when
3383
+ * inside a union and leaves the check otherwise.
3384
+ */ function recordingCtx(record, union, clearTop) {
3385
+ const inUnionFail = `{ ${record} }`;
3386
+ return {
3387
+ fail: union ? inUnionFail : `{ if (q) return 0; ${record} }`,
3388
+ inUnionFail,
3389
+ union,
3390
+ clearTop
3391
+ };
3392
+ }
3393
+ /** Flags passed to a callee. */ function flags(ctx) {
3394
+ if (ctx.clearTop) return ctx.union ? `(f & ${~F_TOP}) | ${F_IN_UNION}` : `f & ${~F_TOP}`;
3395
+ return ctx.union ? `f | ${F_IN_UNION}` : "f";
3396
+ }
3397
+ /** The statements of a `{ … }` block statement (other statements as they are). */ function unblock(statement) {
3398
+ return statement.startsWith("{ ") && statement.endsWith(" }") ? statement.slice(2, -2) : statement;
3399
+ }
3400
+ /** `cond ? a : b` folded when `cond` is a constant. */ function choose(cond, a, b) {
3401
+ return cond === "true" ? a : cond === "false" ? b : `${cond} ? ${a} : ${b}`;
3402
+ }
3403
+ function notObject(x) {
3404
+ return `typeof ${x} !== "object" || ${x} === null || Array.isArray(${x})`;
3405
+ }
3406
+ function indent(lines, n = 2) {
3407
+ const pad = " ".repeat(n);
3408
+ return lines.map((l) => pad + l);
3409
+ }
3410
+
3411
+ //#endregion
3412
+ //#region packages/typescript/src/codegen/validation-model.ts
3413
+ function _define_property$4(obj, key, value) {
3414
+ if (key in obj) Object.defineProperty(obj, key, {
3415
+ value,
3416
+ enumerable: true,
3417
+ configurable: true,
3418
+ writable: true
3419
+ });
3420
+ else obj[key] = value;
3421
+ return obj;
3422
+ }
3423
+ /** Kinds of the opaque types standing for another module's types (see {@link classifyType}). */ const EXT_KIND = "#ext";
3424
+ const INTERP_KIND = "#interp";
3425
+ /**
3426
+ * How the layout treats a model type: `'ext'` — another module's type referenced as a
3427
+ * whole (also an alias / prop clone of one: `cloneTypeDef` keeps the kind); `'interp'` — a
3428
+ * chained reference into another module's type, only known at runtime.
3429
+ */ function classifyType(type) {
3430
+ const kind = type?.kind;
3431
+ return kind === EXT_KIND ? "ext" : kind === INTERP_KIND ? "interp" : void 0;
3432
+ }
3433
+ /**
3434
+ * Build-time model of the runtime type trees a generated `.as.js` module builds, used to
3435
+ * compile validator checks (`compileValidators`).
3436
+ *
3437
+ * The renderer drives it in lockstep with the builder chains it emits, through the real
3438
+ * runtime builder (`defineAnnotatedType`, `annotate`, `cloneRefProp`), so the model has
3439
+ * the same structure, the same type-def sharing (by identity) and the same validator
3440
+ * annotations as the module after its initialisation. Only the annotations the validator
3441
+ * pre-check reads are recorded. Types of other modules are opaque markers: a reference to
3442
+ * one (also an alias or a cloned prop of one) compiles to a cross-module site, bound at
3443
+ * runtime to the referenced class's own compiled check (see compiled-check/registry.ts).
3444
+ *
3445
+ * Anything the model cannot follow marks it broken; nothing is compiled then. A model that
3446
+ * nevertheless diverges from the runtime only costs speed: the runtime bind detects it and
3447
+ * the interpreted pre-check runs.
3448
+ */ var ValidationModel = class {
3449
+ /** Runs a model step; a throw marks the model broken. */ run(step) {
3450
+ if (this.broken) return;
3451
+ try {
3452
+ return step();
3453
+ } catch {
3454
+ this.broken = true;
3455
+ return;
3456
+ }
3457
+ }
3458
+ /** Declares a generated class (`static type = {}; static metadata = new Map()`). */ declare(name) {
3459
+ this.classes.set(name, {
3460
+ __is_atscript_annotated_type: true,
3461
+ type: {},
3462
+ metadata: /* @__PURE__ */ new Map(),
3463
+ name
3464
+ });
3465
+ }
3466
+ /** The model of a class declared in this module (anything else: the emitted code throws). */ classBase(name) {
3467
+ const cls = this.classes.get(name);
3468
+ if (!cls) throw new Error(`${name} is not a class of this module`);
3469
+ return cls;
3470
+ }
3471
+ /** `$(kind, name?)`. */ handle(kind, name) {
3472
+ return this.run(() => defineAnnotatedType(kind, name === void 0 ? void 0 : this.classBase(name)));
3473
+ }
3474
+ /** `.refTo(Local)` / `.refTo(() => Imported)` (with an optional chain). */ refTo(handle, name, imported, chain) {
3475
+ this.run(() => {
3476
+ if (!handle) throw new Error("no chain");
3477
+ if (imported) {
3478
+ const marker = this.marker(name, chain ? INTERP_KIND : EXT_KIND);
3479
+ handle.refTo(() => marker, chain);
3480
+ } else handle.refTo(this.classBase(name), chain);
3481
+ });
3482
+ }
3483
+ /** The opaque stand-in of another module's type `name`. */ marker(name, kind) {
3484
+ const key = `${name}${kind}`;
3485
+ let marker = this.markers.get(key);
3486
+ if (!marker) {
3487
+ marker = {
3488
+ __is_atscript_annotated_type: true,
3489
+ type: { kind },
3490
+ metadata: /* @__PURE__ */ new Map()
3491
+ };
3492
+ this.markers.set(key, marker);
3493
+ }
3494
+ return marker;
3495
+ }
3496
+ /** `.annotate(key, value, multiple)` on the current chain (validator keys only). */ annotate(key, value, multiple) {
3497
+ if (!isValidatorKey(key)) return;
3498
+ this.run(() => {
3499
+ if (!this.current) throw new Error("no chain");
3500
+ this.current.annotate(key, value, multiple);
3501
+ });
3502
+ }
3503
+ /** The node a mutating-annotate accessor (`Name.type.props.get("a")?…`) points at. */ resolve(name, steps) {
3504
+ let cur = this.classes.get(name);
3505
+ for (const step of steps) {
3506
+ if (cur === void 0 || cur === null) return;
3507
+ if (step === "type") {
3508
+ cur = cur.type;
3509
+ if (classifyType(cur) !== void 0) return;
3510
+ } else if (step[0] === "props") cur = cur.props?.get(step[1]);
3511
+ else cur = cur.items?.[step[1]];
3512
+ }
3513
+ return cur;
3514
+ }
3515
+ /** `$c(<accessor>, "prop")`. */ cloneProp(name, steps, prop) {
3516
+ this.run(() => {
3517
+ const parent = this.resolve(name, steps);
3518
+ if (parent) cloneRefProp(parent, prop);
3519
+ });
3520
+ }
3521
+ /** `<accessor>.metadata.delete(key)`. */ deleteAnnotation(name, steps, key) {
3522
+ this.run(() => {
3523
+ this.resolve(name, steps)?.metadata?.delete(key);
3524
+ });
3525
+ }
3526
+ /** `$a(<accessor>.metadata, key, value, multiple)`. */ mutateAnnotation(name, steps, key, value, multiple) {
3527
+ if (!isValidatorKey(key)) return;
3528
+ this.run(() => {
3529
+ annotate(this.resolve(name, steps)?.metadata, key, value, multiple);
3530
+ });
3531
+ }
3532
+ /**
3533
+ * `$cv(Name, version, layout, factory)` for class `name`, or `undefined` when it cannot be
3534
+ * compiled (its root type is only known at runtime, or the model is broken).
3535
+ */ registration(name) {
3536
+ if (this.broken) return;
3537
+ const cls = this.classes.get(name);
3538
+ if (!cls) return;
3539
+ let layout;
3540
+ try {
3541
+ layout = buildLayout(cls, { regex: getRegex }, classifyType);
3542
+ } catch {
3543
+ return;
3544
+ }
3545
+ const root = layout[1][2];
3546
+ if (root === INTERP || root >= 0 && layout[0][root][0] === D_UNKNOWN) return;
3547
+ return `$cv(${name}, ${LAYOUT_VERSION}, ${layoutSource(layout)}, ${emitCheckFactory(layout)})`;
3548
+ }
3549
+ constructor() {
3550
+ /** The model could not follow the emitted code: compile nothing. */ _define_property$4(this, "broken", false);
3551
+ /** Handle of the chain being emitted (the target of `.annotate(…)` lines). */ _define_property$4(this, "current", void 0);
3552
+ _define_property$4(this, "classes", /* @__PURE__ */ new Map());
3553
+ _define_property$4(this, "markers", /* @__PURE__ */ new Map());
3554
+ }
3555
+ };
3556
+ /**
3557
+ * Runtime value of an annotation argument the emitted code writes as a raw expression
3558
+ * (`true`, `5`, `-1.5`, …). Anything else is opaque (truthy and not a number): the bind
3559
+ * compares only presence / truthiness and reads the real values at runtime.
3560
+ */ function rawLiteralValue(text) {
3561
+ switch (text) {
3562
+ case "true": return true;
3563
+ case "false": return false;
3564
+ case "null": return null;
3565
+ case "undefined": return;
3566
+ default: {
3567
+ const n = Number(text);
3568
+ return text.trim() !== "" && !Number.isNaN(n) ? n : { opaque: text };
3569
+ }
3570
+ }
3571
+ }
3572
+
2279
3573
  //#endregion
2280
3574
  //#region packages/typescript/src/codegen/js-renderer.ts
2281
3575
  function _define_property$3(obj, key, value) {
@@ -2301,7 +3595,24 @@ const QUERY_OP_MAP = {
2301
3595
  "exists": "$exists",
2302
3596
  "not exists": "$exists"
2303
3597
  };
3598
+ /** Value field of each number-bound annotation's object form. */ const NUMBER_BOUND_FIELDS = {
3599
+ "expect.min": "minValue",
3600
+ "expect.max": "maxValue",
3601
+ "expect.exclusiveMin": "exclusiveMinValue",
3602
+ "expect.exclusiveMax": "exclusiveMaxValue"
3603
+ };
2304
3604
  const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
3605
+ /** The runtime value of an annotation argument (see `JsRenderer.computeAnnotationValue`). */ function runtimeArg(type, token) {
3606
+ return type === "string" || type === void 0 && token.type === "text" ? token.text : rawLiteralValue(token.text);
3607
+ }
3608
+ /**
3609
+ * The runtime accessor of a mutating-annotate path: `Name` followed by the steps
3610
+ * (`.type`, `.props.get("a")?`, `.items[0]`).
3611
+ */ function accessorPath(targetName, steps) {
3612
+ let path = targetName;
3613
+ for (const step of steps) path += step === "type" ? ".type" : step[0] === "props" ? `.props.get("${escapeQuotes(step[1])}")?` : `.items[${step[1]}]`;
3614
+ return path;
3615
+ }
2305
3616
  var JsRenderer = class extends BaseRenderer {
2306
3617
  /**
2307
3618
  * Relative imports get the configured `moduleExtension`; bare specifiers
@@ -2480,6 +3791,7 @@ var JsRenderer = class extends BaseRenderer {
2480
3791
  if (jsonSchemaMode === "lazy") imports.push("buildJsonSchema as $$");
2481
3792
  if (this.opts?.exampleData) imports.push("createDataFromAnnotatedType as $e");
2482
3793
  if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
3794
+ if (this.model) imports.push("registerCompiledCheck as $cv");
2483
3795
  this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
2484
3796
  this.computeSynthesizedImports();
2485
3797
  this.writeln(SYNTH_IMPORTS_MARKER);
@@ -2527,7 +3839,7 @@ var JsRenderer = class extends BaseRenderer {
2527
3839
  if ((0, _atscript_core.isInterface)(def)) if (def.hasExtends) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
2528
3840
  else def = def.getDefinition() || def;
2529
3841
  this._adHocAnnotations = this.buildAdHocMap([annotateNode]);
2530
- this.annotateType(def, node.id);
3842
+ this.modelClass(node.id, () => this.annotateType(def, node.id));
2531
3843
  this._adHocAnnotations = null;
2532
3844
  this.indent();
2533
3845
  this.defineMetadataForAnnotateAlias(annotateNode);
@@ -2541,13 +3853,38 @@ var JsRenderer = class extends BaseRenderer {
2541
3853
  const resolved = this.doc.resolveInterfaceExtends(node);
2542
3854
  if (resolved) def = resolved;
2543
3855
  }
2544
- this.annotateType(def, node.id);
3856
+ this.modelClass(node.id, () => this.annotateType(def, node.id));
2545
3857
  this.indent().defineMetadata(node).unindent();
2546
3858
  this.writeln();
2547
3859
  }
3860
+ this.renderCompiledChecks();
2548
3861
  this.writeln("// prettier-ignore-end");
2549
3862
  super.post();
2550
3863
  }
3864
+ /**
3865
+ * Emits class `name`'s chain; the validation model follows it (its handle stays the current
3866
+ * chain, the target of the class-level annotations emitted next).
3867
+ */ modelClass(name, emit) {
3868
+ if (this.model) this.model.current = void 0;
3869
+ emit();
3870
+ if (this.model?.current) this.modelClasses.push(name);
3871
+ }
3872
+ /**
3873
+ * `compileValidators`: one `$cv(Class, …)` registration per class, after every chain and
3874
+ * mutating annotate of the module ran (the compiled check binds on first use).
3875
+ */ renderCompiledChecks() {
3876
+ if (!this.model) return;
3877
+ const registrations = [];
3878
+ for (const name of this.modelClasses) {
3879
+ const registration = this.model.registration(name);
3880
+ if (registration) registrations.push(registration);
3881
+ }
3882
+ if (registrations.length > 0) {
3883
+ this.writeln("// Compiled validator checks");
3884
+ for (const registration of registrations) for (const line of registration.split("\n")) this.writeln(line);
3885
+ this.writeln();
3886
+ }
3887
+ }
2551
3888
  renderClassStatics(node) {
2552
3889
  this.writeln("static __is_atscript_annotated_type = true");
2553
3890
  this.writeln("static type = {}");
@@ -2578,6 +3915,7 @@ var JsRenderer = class extends BaseRenderer {
2578
3915
  this.write(exported ? "export " : "");
2579
3916
  this.write(`class ${node.id} `);
2580
3917
  this.blockln("{}");
3918
+ this.model?.declare(node.id);
2581
3919
  this.renderClassStatics(node);
2582
3920
  this.popln();
2583
3921
  this.postAnnotate.push(node);
@@ -2627,23 +3965,63 @@ var JsRenderer = class extends BaseRenderer {
2627
3965
  if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
2628
3966
  }
2629
3967
  toAnnotatedType(node) {
2630
- return this.toAnnotatedHandle(node).$type;
3968
+ return node?.entity === "interface" || node?.entity === "type" ? this.declType(node) : this.toAnnotatedHandle(node).$type;
2631
3969
  }
2632
- toAnnotatedHandle(node, skipAnnotations = false) {
2633
- if (!node) return defineAnnotatedType();
3970
+ /**
3971
+ * The build-time runtime type of an interface / type declaration (see `_declTypes`);
3972
+ * `doc` is the document that declares it (where an alias's target name resolves).
3973
+ */ declType(node, doc = this.doc) {
3974
+ const known = this._declTypes.get(node);
3975
+ if (known) return known;
3976
+ let def = node.getDefinition();
3977
+ if ((0, _atscript_core.isInterface)(node) && node.hasExtends) {
3978
+ const resolved = this.doc.resolveInterfaceExtends(node);
3979
+ if (resolved) def = resolved;
3980
+ }
3981
+ const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
3982
+ let handle;
3983
+ if (def && (0, _atscript_core.isRef)(def)) {
3984
+ const ref = def;
3985
+ const decl = doc.unwindType(ref.id, ref.chain)?.def;
3986
+ const target = this.refTarget(ref, decl, doc);
3987
+ handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
3988
+ } else {
3989
+ const base = {
3990
+ __is_atscript_annotated_type: true,
3991
+ type: {},
3992
+ metadata: /* @__PURE__ */ new Map(),
3993
+ id: typeId
3994
+ };
3995
+ this._declTypes.set(node, base);
3996
+ if (def) this._declTypes.set(def, base);
3997
+ handle = this.toAnnotatedHandle(def, true, base);
3998
+ }
3999
+ this._declTypes.set(node, handle.$type);
4000
+ if (typeId) handle.id(typeId);
4001
+ this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
4002
+ return handle.$type;
4003
+ }
4004
+ /**
4005
+ * The declaration type a reference points at (see `declType`), or `undefined` when it is
4006
+ * not a declaration (a chained reference into a prop, an unresolved name). A plain
4007
+ * reference to a type alias points at the alias itself (its own type and id, like the
4008
+ * runtime `$().refTo(Alias)`), not at what the alias unwinds to.
4009
+ */ refTarget(ref, decl, doc = this.doc) {
4010
+ if (!decl) return;
4011
+ const owner = ref.hasChain ? void 0 : this.resolveOwner(doc, ref.id);
4012
+ if (owner?.node?.entity === "type" || owner?.node?.entity === "interface") return this.declType(owner.node, owner.doc);
4013
+ const known = this._declTypes.get(decl);
4014
+ if (known) return known;
4015
+ return (0, _atscript_core.isInterface)(decl) ? this.declType(decl) : void 0;
4016
+ }
4017
+ /**
4018
+ * The build-time runtime type of an expression node; with `base`, built into that object
4019
+ * (a declaration's type, see `declType`).
4020
+ */ toAnnotatedHandle(node, skipAnnotations = false, base) {
4021
+ if (!node) return defineAnnotatedType(void 0, base);
2634
4022
  switch (node.entity) {
2635
4023
  case "interface":
2636
- case "type": {
2637
- let def = node.getDefinition();
2638
- if ((0, _atscript_core.isInterface)(node) && node.hasExtends) {
2639
- const resolved = this.doc.resolveInterfaceExtends(node);
2640
- if (resolved) def = resolved;
2641
- }
2642
- const handle = this.toAnnotatedHandle(def, true);
2643
- const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
2644
- if (typeId) handle.id(typeId);
2645
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
2646
- }
4024
+ case "type": return defineAnnotatedType().refTo(this.declType(node));
2647
4025
  case "prop": {
2648
4026
  const prop = node;
2649
4027
  const def = prop.getDefinition();
@@ -2657,7 +4035,8 @@ var JsRenderer = class extends BaseRenderer {
2657
4035
  case "ref": {
2658
4036
  const ref = node;
2659
4037
  const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
2660
- const handle = this.toAnnotatedHandle(decl, true);
4038
+ const target = this.refTarget(ref, decl);
4039
+ const handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
2661
4040
  if (skipAnnotations) return handle;
2662
4041
  const own = this.doc.evalAnnotationsForNode(node);
2663
4042
  const referred = this.refTargetAnnotations(ref, decl);
@@ -2665,14 +4044,14 @@ var JsRenderer = class extends BaseRenderer {
2665
4044
  }
2666
4045
  case "primitive": {
2667
4046
  const prim = node;
2668
- const handle = defineAnnotatedType();
4047
+ const handle = defineAnnotatedType(void 0, base);
2669
4048
  handle.designType(prim.id === "never" ? "never" : prim.config.type);
2670
4049
  if (!skipAnnotations) this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
2671
4050
  return handle;
2672
4051
  }
2673
4052
  case "const": {
2674
4053
  const c = node;
2675
- const handle = defineAnnotatedType();
4054
+ const handle = defineAnnotatedType(void 0, base);
2676
4055
  const t = c.token("identifier")?.type;
2677
4056
  handle.designType(t === "number" ? "number" : "string");
2678
4057
  handle.value(t === "number" ? Number(c.id) : c.id);
@@ -2680,7 +4059,7 @@ var JsRenderer = class extends BaseRenderer {
2680
4059
  }
2681
4060
  case "structure": {
2682
4061
  const struct = node;
2683
- const handle = defineAnnotatedType("object");
4062
+ const handle = defineAnnotatedType("object", base);
2684
4063
  for (const prop of Array.from(struct.props.values())) {
2685
4064
  const propHandle = this.toAnnotatedHandle(prop);
2686
4065
  const pattern = prop.token("identifier")?.pattern;
@@ -2691,24 +4070,24 @@ var JsRenderer = class extends BaseRenderer {
2691
4070
  }
2692
4071
  case "group": {
2693
4072
  const group = node;
2694
- const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection");
4073
+ const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection", base);
2695
4074
  for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
2696
4075
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
2697
4076
  }
2698
4077
  case "tuple": {
2699
4078
  const group = node;
2700
- const handle = defineAnnotatedType("tuple");
4079
+ const handle = defineAnnotatedType("tuple", base);
2701
4080
  for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
2702
4081
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
2703
4082
  }
2704
4083
  case "array": {
2705
4084
  const arr = node;
2706
- const handle = defineAnnotatedType("array");
4085
+ const handle = defineAnnotatedType("array", base);
2707
4086
  handle.of(this.toAnnotatedHandle(arr.getDefinition()).$type);
2708
4087
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
2709
4088
  }
2710
4089
  default: {
2711
- const handle = defineAnnotatedType();
4090
+ const handle = defineAnnotatedType(void 0, base);
2712
4091
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
2713
4092
  }
2714
4093
  }
@@ -2724,14 +4103,11 @@ var JsRenderer = class extends BaseRenderer {
2724
4103
  });
2725
4104
  break;
2726
4105
  case "expect.min":
2727
- if (a.args[0]) handle.annotate(a.name, {
2728
- minValue: Number(a.args[0].text),
2729
- message: a.args[1]?.text
2730
- });
2731
- break;
2732
4106
  case "expect.max":
4107
+ case "expect.exclusiveMin":
4108
+ case "expect.exclusiveMax":
2733
4109
  if (a.args[0]) handle.annotate(a.name, {
2734
- maxValue: Number(a.args[0].text),
4110
+ [NUMBER_BOUND_FIELDS[a.name]]: Number(a.args[0].text),
2735
4111
  message: a.args[1]?.text
2736
4112
  });
2737
4113
  break;
@@ -2783,8 +4159,10 @@ var JsRenderer = class extends BaseRenderer {
2783
4159
  node: synth.ownerNode
2784
4160
  } : this.resolveOwner(this.doc, ref.id);
2785
4161
  const refName = synth?.alias ?? ref.id;
2786
- const refExpr = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false) ? `() => ${refName}` : refName;
4162
+ const isImported = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false);
4163
+ const refExpr = isImported ? `() => ${refName}` : refName;
2787
4164
  this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().writeln(`.refTo(${refExpr}${chain})`);
4165
+ this.model?.refTo(this.modelHandle("", name), refName, isImported, ref.hasChain ? ref.chain.map((c) => c.text) : void 0);
2788
4166
  if (!ref.hasChain) {
2789
4167
  if (ownerDecl?.node) ownerDecl.doc.evalReferredAnnotations(ownerDecl.node)?.forEach((an) => {
2790
4168
  this.resolveAnnotationValue(ownerDecl.node, an);
@@ -2797,29 +4175,63 @@ var JsRenderer = class extends BaseRenderer {
2797
4175
  this.definePrimitive(node, name);
2798
4176
  return this;
2799
4177
  case "const":
4178
+ this.modelHandle("", name);
2800
4179
  this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().defineConst(node).unindent();
2801
4180
  return this;
2802
4181
  case "structure":
4182
+ this.modelHandle("object", name);
2803
4183
  this.writeln(`$("object"${name ? `, ${name}` : ""})`).indent().defineObject(node).unindent();
2804
4184
  return this;
2805
4185
  case "group":
2806
4186
  kind = node.op === "|" ? "union" : "intersection";
4187
+ this.modelHandle(kind, name);
2807
4188
  this.writeln(`$("${kind}"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
2808
4189
  return this;
2809
4190
  case "tuple":
4191
+ this.modelHandle("tuple", name);
2810
4192
  this.writeln(`$("tuple"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
2811
4193
  return this;
2812
4194
  case "array":
4195
+ this.modelHandle("array", name);
2813
4196
  this.writeln(`$("array"${name ? `, ${name}` : ""})`).indent().defineArray(node).unindent();
2814
4197
  return this;
2815
4198
  default: return this;
2816
4199
  }
2817
4200
  }
4201
+ /** `$(kind, name?)` in the validation model; it becomes the current chain. */ modelHandle(kind, name) {
4202
+ if (!this.model) return;
4203
+ const h = this.model.handle(kind, name);
4204
+ this.model.current = h;
4205
+ return h;
4206
+ }
4207
+ /**
4208
+ * The model handle of a nested chain (`emit` writes it and its annotations): `current`
4209
+ * is cleared first so a chain that emits nothing breaks the model instead of leaving a
4210
+ * stale handle, and restored to the parent chain afterwards.
4211
+ */ modelChild(emit) {
4212
+ if (!this.model) {
4213
+ emit();
4214
+ return;
4215
+ }
4216
+ const parent = this.model.current;
4217
+ this.model.current = void 0;
4218
+ emit();
4219
+ const child = this.model.current;
4220
+ this.model.current = parent;
4221
+ if (!child) this.model.broken = true;
4222
+ return child;
4223
+ }
2818
4224
  defineConst(node) {
2819
4225
  const t = node.token("identifier")?.type;
2820
4226
  const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
2821
4227
  this.writeln(`.designType("${escapeQuotes(designType)}")`);
2822
4228
  this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
4229
+ if (this.model) {
4230
+ const h = this.model.current;
4231
+ this.model.run(() => {
4232
+ h.designType(designType).value(t === "text" ? node.id : rawLiteralValue(node.id));
4233
+ });
4234
+ }
2823
4235
  return this;
2824
4236
  }
2825
4237
  definePrimitive(node, name) {
@@ -2827,66 +4239,82 @@ var JsRenderer = class extends BaseRenderer {
2827
4239
  this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
2828
4240
  return this;
2829
4241
  }
2830
- renderPrimitiveDef(def, name) {
4242
+ /** Emits a primitive's builder chain (and follows it in the validation model). */ renderPrimitiveDef(def, name) {
2831
4243
  const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
2832
- if (!def) return this.writeln(`$(${d()}).designType("any")`);
2833
- if (typeof def === "string") return this.writeln(`$(${d()}).designType("${def === "void" ? "undefined" : def}")`);
4244
+ const final = (designType) => {
4245
+ this.writeln(`$(${d()}).designType("${designType}")`);
4246
+ const h = this.modelHandle("", name);
4247
+ this.model?.run(() => h.designType(designType));
4248
+ };
4249
+ if (!def) return final("any");
4250
+ if (typeof def === "string") return final(def === "void" ? "undefined" : def);
2834
4251
  switch (def.kind) {
2835
- case "final": return this.writeln(`$(${d()}).designType("${def.value === "void" ? "undefined" : def.value}")`);
4252
+ case "final": return final(def.value === "void" ? "undefined" : def.value);
2836
4253
  case "union":
2837
4254
  case "intersection":
2838
4255
  case "tuple":
2839
4256
  this.writeln(`$(${d(def.kind)})`);
4257
+ this.modelHandle(def.kind, name);
2840
4258
  this.indent();
2841
4259
  for (const itemDef of def.items) {
2842
4260
  this.write(`.item(`);
2843
4261
  this.indent();
2844
- this.renderPrimitiveDef(itemDef);
4262
+ const child = this.modelChild(() => this.renderPrimitiveDef(itemDef));
2845
4263
  this.writeln(".$type");
2846
4264
  this.unindent();
2847
4265
  this.write(`)`);
4266
+ this.model?.run(() => this.model.current.item(child.$type));
2848
4267
  }
2849
4268
  this.unindent();
2850
4269
  return;
2851
- case "array":
4270
+ case "array": {
2852
4271
  this.writeln(`$(${d("array")})`);
4272
+ this.modelHandle("array", name);
2853
4273
  this.indent();
2854
4274
  this.write(".of(");
2855
4275
  this.indent();
2856
- this.renderPrimitiveDef(def.of);
4276
+ const child = this.modelChild(() => this.renderPrimitiveDef(def.of));
2857
4277
  this.writeln(`.$type`);
2858
4278
  this.unindent();
2859
4279
  this.writeln(`)`);
2860
4280
  this.unindent();
4281
+ this.model?.run(() => this.model.current.of(child.$type));
2861
4282
  return;
2862
- case "object":
4283
+ }
4284
+ case "object": {
2863
4285
  this.writeln(`$(${d("object")})`);
4286
+ this.modelHandle("object", name);
2864
4287
  this.indent();
2865
- for (const [key, propDef] of Object.entries(def.props)) {
4288
+ const props = [...Object.entries(def.props).map(([k, p]) => [
4289
+ k,
4290
+ p,
4291
+ false
4292
+ ]), ...Object.entries(def.propsPatterns).map(([k, p]) => [
4293
+ k,
4294
+ p,
4295
+ true
4296
+ ])];
4297
+ for (const [key, propDef, isPattern] of props) {
2866
4298
  const optional = typeof propDef === "object" && propDef.optional;
2867
- this.writeln(`.prop(`);
4299
+ this.writeln(isPattern ? `.propPattern(` : `.prop(`);
2868
4300
  this.indent();
2869
- this.writeln(`"${escapeQuotes(key)}",`);
2870
- this.renderPrimitiveDef(propDef);
2871
- if (optional) this.writeln(".optional()");
2872
- this.writeln(".$type");
2873
- this.unindent();
2874
- this.write(`)`);
2875
- }
2876
- for (const [key, propDef] of Object.entries(def.propsPatterns)) {
2877
- const optional = typeof propDef === "object" && propDef.optional;
2878
- this.writeln(`.propPattern(`);
2879
- this.indent();
2880
- this.writeln(`${key},`);
2881
- this.renderPrimitiveDef(propDef);
2882
- if (optional) this.writeln(".optional()");
4301
+ this.writeln(isPattern ? `${key},` : `"${escapeQuotes(key)}",`);
4302
+ const child = this.modelChild(() => {
4303
+ this.renderPrimitiveDef(propDef);
4304
+ if (optional) {
4305
+ this.writeln(".optional()");
4306
+ this.model?.run(() => this.model.current.optional());
4307
+ }
4308
+ });
2883
4309
  this.writeln(".$type");
2884
4310
  this.unindent();
2885
4311
  this.write(`)`);
4312
+ this.model?.run(() => isPattern ? this.model.current.propPattern(/./, child.$type) : this.model.current.prop(key, child.$type));
2886
4313
  }
2887
4314
  this.unindent();
2888
4315
  return;
2889
- default: return this.writeln(`$(${d()}).designType("any")`);
4316
+ }
4317
+ default: return final("any");
2890
4318
  }
2891
4319
  }
2892
4320
  defineObject(node) {
@@ -2904,25 +4332,39 @@ var JsRenderer = class extends BaseRenderer {
2904
4332
  this.indent();
2905
4333
  this.writeln(`"${escapeQuotes(prop.id)}",`);
2906
4334
  }
2907
- this.annotateType(prop.getDefinition());
2908
- this.indent().defineMetadata(prop).unindent();
4335
+ const child = this.modelChild(() => {
4336
+ this.annotateType(prop.getDefinition());
4337
+ this.indent().defineMetadata(prop).unindent();
4338
+ });
2909
4339
  if (optional) this.writeln(" .optional()");
2910
4340
  this.writeln(" .$type");
2911
4341
  this.unindent();
2912
4342
  this.write(`)`);
2913
4343
  this._propPath.pop();
4344
+ this.model?.run(() => {
4345
+ if (optional) child.optional();
4346
+ if (pattern) this.model.current.propPattern(pattern, child.$type);
4347
+ else this.model.current.prop(prop.id, child.$type);
4348
+ });
2914
4349
  }
2915
4350
  this.writeln();
2916
4351
  return this;
2917
4352
  }
2918
4353
  defineGroup(node) {
2919
- const items = node.unwrap();
2920
- for (const item of items) this.write(".item(").indent().annotateType(item).defineInlinePrimitiveMetadata(item).write(" .$type").writeln(`)`).unindent();
4354
+ for (const item of node.unwrap()) {
4355
+ this.write(".item(").indent();
4356
+ const child = this.modelChild(() => this.annotateType(item).defineInlinePrimitiveMetadata(item));
4357
+ this.write(" .$type").writeln(`)`).unindent();
4358
+ this.model?.run(() => this.model.current.item(child.$type));
4359
+ }
2921
4360
  return this;
2922
4361
  }
2923
4362
  defineArray(node) {
2924
4363
  const of = node.getDefinition();
2925
- this.write(".of(").indent().annotateType(of).defineInlinePrimitiveMetadata(of).write(" .$type").writeln(`)`).unindent();
4364
+ this.write(".of(").indent();
4365
+ const child = this.modelChild(() => this.annotateType(of).defineInlinePrimitiveMetadata(of));
4366
+ this.write(" .$type").writeln(`)`).unindent();
4367
+ this.model?.run(() => this.model.current.of(child.$type));
2926
4368
  return this;
2927
4369
  }
2928
4370
  /**
@@ -2993,9 +4435,10 @@ var JsRenderer = class extends BaseRenderer {
2993
4435
  return this;
2994
4436
  }
2995
4437
  resolveAnnotationValue(node, an) {
2996
- const { value, multiple } = this.computeAnnotationValue(node, an);
4438
+ const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
2997
4439
  if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
2998
4440
  else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
4441
+ this.model?.annotate(an.name, runtime, multiple);
2999
4442
  }
3000
4443
  emitRefValue(text, origin) {
3001
4444
  const dotIdx = text.indexOf(".");
@@ -3074,33 +4517,50 @@ var JsRenderer = class extends BaseRenderer {
3074
4517
  default: return token.text;
3075
4518
  }
3076
4519
  }
3077
- computeAnnotationValue(node, an) {
4520
+ /**
4521
+ * The JS source of an annotation's value, and (for the validation model, which only reads
4522
+ * validator annotations: numbers, strings, flags) the runtime value it evaluates to;
4523
+ * other argument kinds are opaque there.
4524
+ */ computeAnnotationValue(node, an) {
3078
4525
  const origin = this.doc.annotationOrigin(an);
3079
4526
  const spec = this.doc.resolveAnnotation(an.name);
3080
4527
  let targetValue = "true";
4528
+ let runtime = true;
3081
4529
  let multiple = false;
3082
4530
  if (spec) {
3083
4531
  multiple = spec.config.multiple;
3084
4532
  const length = spec.arguments.length;
3085
- if (length !== 0) if (Array.isArray(spec.config.argument)) {
3086
- targetValue = "{ ";
3087
- let i = 0;
3088
- for (const aSpec of spec.arguments) {
3089
- if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
3090
- i++;
4533
+ if (length !== 0) {
4534
+ if (Array.isArray(spec.config.argument)) {
4535
+ targetValue = "{ ";
4536
+ const fields = {};
4537
+ let i = 0;
4538
+ for (const aSpec of spec.arguments) {
4539
+ if (an.args[i]) {
4540
+ targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
4541
+ fields[aSpec.name] = runtimeArg(aSpec.type, an.args[i]);
4542
+ }
4543
+ i++;
4544
+ }
4545
+ targetValue += "}";
4546
+ runtime = fields;
4547
+ } else if (an.args[0]) {
4548
+ const aSpec = spec.arguments[0];
4549
+ targetValue = this.emitArgValue(aSpec, an.args[0], origin);
4550
+ runtime = runtimeArg(aSpec.type, an.args[0]);
3091
4551
  }
3092
- targetValue += "}";
3093
- } else {
3094
- const aSpec = spec.arguments[0];
3095
- targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0], origin) : "true";
3096
4552
  }
3097
4553
  } else {
3098
4554
  multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
3099
- if (an.args.length > 0) targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
4555
+ if (an.args.length > 0) {
4556
+ targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
4557
+ runtime = runtimeArg(void 0, an.args[0]);
4558
+ }
3100
4559
  }
3101
4560
  return {
3102
4561
  value: targetValue,
3103
- multiple: !!multiple
4562
+ multiple: !!multiple,
4563
+ runtime
3104
4564
  };
3105
4565
  }
3106
4566
  renderMutatingAnnotateNode(node) {
@@ -3113,7 +4573,7 @@ var JsRenderer = class extends BaseRenderer {
3113
4573
  const anns = entry.annotations;
3114
4574
  if (!anns || anns.length === 0) continue;
3115
4575
  const parts = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)] : [entry.id];
3116
- const { accessors, clones } = this.buildMutatingAccessors(targetName, targetDef, parts);
4576
+ const { accessors, clones } = this.buildMutatingAccessors(targetDef, parts);
3117
4577
  allClones.push(...clones);
3118
4578
  entryAccessors.push({
3119
4579
  entry,
@@ -3122,29 +4582,36 @@ var JsRenderer = class extends BaseRenderer {
3122
4582
  }
3123
4583
  const cloneKeys = /* @__PURE__ */ new Set();
3124
4584
  for (const clone of allClones) {
3125
- const key = `${clone.parentPath}|${clone.propName}`;
4585
+ const parentPath = accessorPath(targetName, clone.parentSteps);
4586
+ const key = `${parentPath}|${clone.propName}`;
3126
4587
  if (!cloneKeys.has(key)) {
3127
4588
  cloneKeys.add(key);
3128
- this.writeln(`$c(${clone.parentPath}, "${escapeQuotes(clone.propName)}")`);
4589
+ this.writeln(`$c(${parentPath}, "${escapeQuotes(clone.propName)}")`);
4590
+ this.model?.cloneProp(targetName, clone.parentSteps, clone.propName);
3129
4591
  }
3130
4592
  }
3131
- for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor);
4593
+ for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor, targetName);
3132
4594
  const topAnnotations = node.annotations;
3133
- if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, targetName);
4595
+ if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, [], targetName);
3134
4596
  this.writeln();
3135
4597
  }
3136
- emitMutatingAnnotations(node, annotations, accessor) {
4598
+ emitMutatingAnnotations(node, annotations, steps, targetName) {
4599
+ const accessor = accessorPath(targetName, steps);
3137
4600
  const cleared = /* @__PURE__ */ new Set();
3138
4601
  for (const an of annotations) {
3139
- const { value, multiple } = this.computeAnnotationValue(node, an);
4602
+ const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
3140
4603
  if (multiple) {
3141
4604
  if (!cleared.has(an.name)) {
3142
4605
  const spec = this.doc.resolveAnnotation(an.name);
3143
- if (!spec || spec.config.mergeStrategy !== "append") this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
4606
+ if (!spec || spec.config.mergeStrategy !== "append") {
4607
+ this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
4608
+ this.model?.deleteAnnotation(targetName, steps, an.name);
4609
+ }
3144
4610
  cleared.add(an.name);
3145
4611
  }
3146
4612
  this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value}, true)`);
3147
4613
  } else this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value})`);
4614
+ this.model?.mutateAnnotation(targetName, steps, an.name, runtime, multiple);
3148
4615
  }
3149
4616
  }
3150
4617
  resolveTargetDef(targetName) {
@@ -3155,51 +4622,48 @@ var JsRenderer = class extends BaseRenderer {
3155
4622
  return def;
3156
4623
  }
3157
4624
  /**
3158
- * Builds the runtime accessor paths for mutating annotate entries.
4625
+ * Builds the accessor paths (as steps, see `accessorPath`) for mutating annotate entries.
3159
4626
  * Computes exact paths at compile time by walking the AST,
3160
4627
  * so the generated JS accesses props directly without runtime search.
3161
4628
  * Returns multiple paths when a property appears in multiple union branches.
3162
- */ buildMutatingAccessors(targetName, targetDef, parts) {
4629
+ */ buildMutatingAccessors(targetDef, parts) {
3163
4630
  let accessors = [{
3164
- prefix: `${targetName}.type`,
4631
+ steps: ["type"],
3165
4632
  def: targetDef
3166
4633
  }];
3167
4634
  const clones = [];
3168
4635
  for (let i = 0; i < parts.length; i++) {
4636
+ const last = i === parts.length - 1;
3169
4637
  const nextAccessors = [];
3170
- for (const { prefix, def } of accessors) {
4638
+ for (const { steps, def } of accessors) {
3171
4639
  const results = this.buildPropPaths(def, parts[i]);
3172
- if (results.length > 0) for (const result of results) if (i < parts.length - 1) {
3173
- if (result.propDef && (0, _atscript_core.isRef)(result.propDef)) clones.push({
3174
- parentPath: prefix,
4640
+ const found = results.length > 0 ? results : [{
4641
+ steps: [["props", parts[i]]],
4642
+ propDef: void 0
4643
+ }];
4644
+ for (const result of found) {
4645
+ if (!last && result.propDef && (0, _atscript_core.isRef)(result.propDef)) clones.push({
4646
+ parentSteps: steps,
3175
4647
  propName: parts[i]
3176
4648
  });
4649
+ const next = [...steps, ...result.steps];
4650
+ if (!last) next.push("type");
3177
4651
  nextAccessors.push({
3178
- prefix: `${prefix}${result.path}?.type`,
4652
+ steps: next,
3179
4653
  def: result.propDef
3180
4654
  });
3181
- } else nextAccessors.push({
3182
- prefix: `${prefix}${result.path}?`,
3183
- def: result.propDef
3184
- });
3185
- else {
3186
- const suffix = `.props.get("${escapeQuotes(parts[i])}")${i < parts.length - 1 ? "?.type" : "?"}`;
3187
- nextAccessors.push({
3188
- prefix: `${prefix}${suffix}`,
3189
- def: void 0
3190
- });
3191
4655
  }
3192
4656
  }
3193
4657
  accessors = nextAccessors;
3194
4658
  }
3195
4659
  return {
3196
- accessors: accessors.map((a) => a.prefix),
4660
+ accessors: accessors.map((a) => a.steps),
3197
4661
  clones
3198
4662
  };
3199
4663
  }
3200
4664
  /**
3201
4665
  * Finds a property in a type tree at compile time, returning all
3202
- * matching runtime path strings and prop definitions for further chaining.
4666
+ * matching accessor steps and prop definitions for further chaining.
3203
4667
  * Returns multiple results when the same property appears in different union branches.
3204
4668
  */ buildPropPaths(def, propName) {
3205
4669
  if (!def) return [];
@@ -3213,7 +4677,7 @@ var JsRenderer = class extends BaseRenderer {
3213
4677
  if ((0, _atscript_core.isStructure)(def)) {
3214
4678
  const prop = def.props.get(propName);
3215
4679
  if (prop) return [{
3216
- path: `.props.get("${escapeQuotes(propName)}")`,
4680
+ steps: [["props", propName]],
3217
4681
  propDef: prop.getDefinition()
3218
4682
  }];
3219
4683
  return [];
@@ -3222,7 +4686,11 @@ var JsRenderer = class extends BaseRenderer {
3222
4686
  const items = def.unwrap();
3223
4687
  const results = [];
3224
4688
  for (let i = 0; i < items.length; i++) for (const result of this.buildPropPaths(items[i], propName)) results.push({
3225
- path: `.items[${i}].type${result.path}`,
4689
+ steps: [
4690
+ ["items", i],
4691
+ "type",
4692
+ ...result.steps
4693
+ ],
3226
4694
  propDef: result.propDef
3227
4695
  });
3228
4696
  return results;
@@ -3230,13 +4698,19 @@ var JsRenderer = class extends BaseRenderer {
3230
4698
  return [];
3231
4699
  }
3232
4700
  constructor(doc, opts) {
3233
- super(doc), _define_property$3(this, "opts", void 0), _define_property$3(this, "postAnnotate", void 0), _define_property$3(this, "_adHocAnnotations", void 0), _define_property$3(this, "_propPath", void 0), _define_property$3(this, "typeIds", void 0), _define_property$3(this, "_unusedJs", void 0), _define_property$3(this, "_extendsRefs", void 0), _define_property$3(this, "_refSynthInfo", void 0), _define_property$3(this, "_synthImports", void 0), _define_property$3(this, "_synthComputed", void 0), _define_property$3(this, "_synthTaken", void 0), _define_property$3(this, "_synthAllocated", void 0), _define_property$3(this, "_synthPathCache", void 0), _define_property$3(this, "_ownerCache", void 0), this.opts = opts, this.postAnnotate = [], this._adHocAnnotations = null, this._propPath = [], this.typeIds = /* @__PURE__ */ new Map(), this._refSynthInfo = /* @__PURE__ */ new Map(), this._synthImports = /* @__PURE__ */ new Map(), this._synthComputed = false, this._synthAllocated = /* @__PURE__ */ new Map(), this._synthPathCache = /* @__PURE__ */ new Map(), this._ownerCache = /* @__PURE__ */ new Map();
4701
+ super(doc), _define_property$3(this, "opts", void 0), _define_property$3(this, "postAnnotate", void 0), _define_property$3(this, "_adHocAnnotations", void 0), _define_property$3(this, "_propPath", void 0), _define_property$3(this, "typeIds", void 0), _define_property$3(this, "_unusedJs", void 0), _define_property$3(this, "_extendsRefs", void 0), _define_property$3(this, "_refSynthInfo", void 0), _define_property$3(this, "_synthImports", void 0), _define_property$3(this, "_synthComputed", void 0), _define_property$3(this, "_synthTaken", void 0), _define_property$3(this, "_synthAllocated", void 0), _define_property$3(this, "_synthPathCache", void 0), _define_property$3(this, "_ownerCache", void 0), _define_property$3(this, "model", void 0), _define_property$3(this, "modelClasses", void 0), _define_property$3(this, "_declTypes", void 0), this.opts = opts, this.postAnnotate = [], this._adHocAnnotations = null, this._propPath = [], this.typeIds = /* @__PURE__ */ new Map(), this._refSynthInfo = /* @__PURE__ */ new Map(), this._synthImports = /* @__PURE__ */ new Map(), this._synthComputed = false, this._synthAllocated = /* @__PURE__ */ new Map(), this._synthPathCache = /* @__PURE__ */ new Map(), this._ownerCache = /* @__PURE__ */ new Map(), this.modelClasses = [], this._declTypes = /* @__PURE__ */ new Map();
4702
+ if (opts?.compileValidators) this.model = new ValidationModel();
3234
4703
  }
3235
4704
  };
3236
4705
 
3237
4706
  //#endregion
3238
4707
  //#region packages/typescript/src/plugin.ts
3239
4708
  /**
4709
+ * Render formats of the JS output that override {@link TTsPluginOptions.compileValidators}
4710
+ * (used by `unplugin-atscript`'s `compileValidators` option).
4711
+ */ const JS_COMPILED_FORMAT = "js:compiled";
4712
+ const JS_INTERPRETED_FORMAT = "js:interpreted";
4713
+ /**
3240
4714
  * Resolves the effective JSON schema mode from plugin options.
3241
4715
  */ function resolveJsonSchemaMode(opts) {
3242
4716
  if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
@@ -3250,10 +4724,16 @@ const tsPlugin = (opts) => {
3250
4724
  fileName: `${doc.name}.d.ts`,
3251
4725
  content: new TypeRenderer(doc, opts).render()
3252
4726
  }];
3253
- if (format === "js") return [{
3254
- fileName: `${doc.name}.js`,
3255
- content: new JsRenderer(doc, opts).render()
3256
- }];
4727
+ if (format === "js" || format === JS_COMPILED_FORMAT || format === JS_INTERPRETED_FORMAT) {
4728
+ const jsOpts = format === "js" ? opts : {
4729
+ ...opts,
4730
+ compileValidators: format === JS_COMPILED_FORMAT
4731
+ };
4732
+ return [{
4733
+ fileName: `${doc.name}.js`,
4734
+ content: new JsRenderer(doc, jsOpts).render()
4735
+ }];
4736
+ }
3257
4737
  },
3258
4738
  async buildEnd(output, format, repo) {
3259
4739
  if (format === "dts" || format === _atscript_core.DEFAULT_FORMAT) {