@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.
@@ -25,13 +25,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  }) : target, mod));
26
26
 
27
27
  //#endregion
28
- const require_json_schema = require('./json-schema-BqpH_eYJ.cjs');
28
+ const require_json_schema = require('./json-schema-B3iAqkGQ.cjs');
29
29
  let path = require("path");
30
30
  path = __toESM(path);
31
31
  let _atscript_core = require("@atscript/core");
32
32
 
33
33
  //#region packages/typescript/src/codegen/code-printer.ts
34
- function _define_property$3(obj, key, value) {
34
+ function _define_property$5(obj, key, value) {
35
35
  if (key in obj) Object.defineProperty(obj, key, {
36
36
  value,
37
37
  enumerable: true,
@@ -124,17 +124,17 @@ var CodePrinter = class {
124
124
  return " ".repeat(this.indentLevel * this.indentSize);
125
125
  }
126
126
  constructor() {
127
- _define_property$3(this, "lines", []);
128
- _define_property$3(this, "currentLine", "");
129
- _define_property$3(this, "indentLevel", 0);
130
- _define_property$3(this, "indentSize", 2);
131
- _define_property$3(this, "blockStack", []);
127
+ _define_property$5(this, "lines", []);
128
+ _define_property$5(this, "currentLine", "");
129
+ _define_property$5(this, "indentLevel", 0);
130
+ _define_property$5(this, "indentSize", 2);
131
+ _define_property$5(this, "blockStack", []);
132
132
  }
133
133
  };
134
134
 
135
135
  //#endregion
136
136
  //#region packages/typescript/src/codegen/base-renderer.ts
137
- function _define_property$2(obj, key, value) {
137
+ function _define_property$4(obj, key, value) {
138
138
  if (key in obj) Object.defineProperty(obj, key, {
139
139
  value,
140
140
  enumerable: true,
@@ -197,7 +197,7 @@ var BaseRenderer = class extends CodePrinter {
197
197
  }
198
198
  }
199
199
  constructor(doc) {
200
- super(), _define_property$2(this, "doc", void 0), _define_property$2(this, "_unused", void 0), this.doc = doc;
200
+ super(), _define_property$4(this, "doc", void 0), _define_property$4(this, "_unused", void 0), this.doc = doc;
201
201
  }
202
202
  };
203
203
 
@@ -220,7 +220,7 @@ function escapeQuotes(str) {
220
220
 
221
221
  //#endregion
222
222
  //#region packages/typescript/src/codegen/type-renderer.ts
223
- function _define_property$1(obj, key, value) {
223
+ function _define_property$3(obj, key, value) {
224
224
  if (key in obj) Object.defineProperty(obj, key, {
225
225
  value,
226
226
  enumerable: true,
@@ -644,7 +644,7 @@ var TypeRenderer = class TypeRenderer extends BaseRenderer {
644
644
  this.writeln(` */`);
645
645
  }
646
646
  constructor(doc, opts) {
647
- super(doc), _define_property$1(this, "opts", void 0), this.opts = opts;
647
+ super(doc), _define_property$3(this, "opts", void 0), this.opts = opts;
648
648
  }
649
649
  };
650
650
  function renderPrimitiveTypeDef(def) {
@@ -661,6 +661,662 @@ function renderPrimitiveTypeDef(def) {
661
661
  }
662
662
  }
663
663
 
664
+ //#endregion
665
+ //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
666
+ /**
667
+ * Build-time layout derivation (renderer and tests; not part of the runtime bundle).
668
+ */
669
+ /**
670
+ * Derives the layout of `root` (see layout.ts). Shared / recursive type defs are recorded
671
+ * once and referenced by index.
672
+ */ function buildLayout(root, reader, classify) {
673
+ const defs = [];
674
+ const index = /* @__PURE__ */ new Map();
675
+ let slots = 0;
676
+ function describeDef(type) {
677
+ switch (type.kind) {
678
+ case "": return type.value === void 0 ? [require_json_schema.D_FINAL, type.designType] : [
679
+ require_json_schema.D_FINAL,
680
+ type.designType,
681
+ type.value
682
+ ];
683
+ case "object": {
684
+ if (type.propsPatterns.length > 0) return [require_json_schema.D_OBJECT_PATTERNS];
685
+ const props = [...type.props];
686
+ return [
687
+ require_json_schema.D_OBJECT,
688
+ props.map(([key]) => key),
689
+ props.map(([, prop]) => site(prop))
690
+ ];
691
+ }
692
+ case "array": return [require_json_schema.D_ARRAY, site(type.of)];
693
+ case "union":
694
+ case "intersection":
695
+ case "tuple": return [require_json_schema.ITEMS_KIND_CODES[type.kind], type.items.map(site)];
696
+ default: return [require_json_schema.D_UNKNOWN, String(type.kind)];
697
+ }
698
+ }
699
+ function site(node) {
700
+ const type = node.type;
701
+ const marker = classify?.(type);
702
+ const optional = !marker || marker === "ext" ? node.optional ? 1 : 0 : 0;
703
+ let d;
704
+ let keys = {
705
+ mask: 0,
706
+ shape: ""
707
+ };
708
+ if (marker === "interp") d = require_json_schema.INTERP;
709
+ else if (marker === "ext") {
710
+ d = require_json_schema.EXT;
711
+ keys = require_json_schema.readKeys(node.metadata, require_json_schema.siteBits(void 0, optional === 1), reader);
712
+ } else {
713
+ d = index.get(type) ?? -1;
714
+ if (d < 0) {
715
+ d = defs.length;
716
+ defs.push([]);
717
+ index.set(type, d);
718
+ defs[d] = describeDef(type);
719
+ }
720
+ keys = require_json_schema.readKeys(node.metadata, require_json_schema.siteBits(type, optional === 1), reader);
721
+ }
722
+ const result = [
723
+ optional,
724
+ keys.mask,
725
+ d,
726
+ keys.shape,
727
+ slots
728
+ ];
729
+ slots += require_json_schema.siteSlotCount(result);
730
+ return result;
731
+ }
732
+ return [
733
+ defs,
734
+ site(root),
735
+ slots
736
+ ];
737
+ }
738
+ /** JS source of a layout literal (plain arrays, strings and numbers incl. NaN / ±Infinity / -0). */ function layoutSource(value) {
739
+ if (Array.isArray(value)) return `[${value.map(layoutSource).join(",")}]`;
740
+ return literalSource(value);
741
+ }
742
+ /** JS source of a primitive literal. */ function literalSource(value) {
743
+ if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
744
+ if (typeof value === "string") return JSON.stringify(value).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
745
+ if (value === void 0) return "undefined";
746
+ return JSON.stringify(value);
747
+ }
748
+
749
+ //#endregion
750
+ //#region packages/typescript/src/runtime/compiled-check/emit.ts
751
+ /**
752
+ * Emits the JS source of a compiled validator check factory from its layout.
753
+ *
754
+ * Build-time only (the renderer, and test code): the runtime never generates code. The
755
+ * emitted factory `(K, H) => check` mirrors the interpreted pre-check
756
+ * (validator-fast-check.ts) node for node — the same checks with the same PASS (1) /
757
+ * FAIL (0) / BAIL (2) contract — specialised to the layout: one function per object type
758
+ * def and per def that closes a reference cycle, everything else inlined.
759
+ *
760
+ * Generated code conventions:
761
+ * - Every function is `(v, f, o)`: the value, the flags (TOP, IN_UNION and option bits —
762
+ * see `optionFlags`) and the validator options (passed on to interpreted sub-checks).
763
+ * - A FAIL statement always leaves the current check: `return 0` outside unions; inside a
764
+ * union (where failures must visit everything the walk would) it records the failure and
765
+ * jumps past the failed node. `q` (`IN_UNION` unset) picks between the two when only the
766
+ * runtime flags tell. BAIL is always `return 2`.
767
+ * - Annotation values are closure constants `k<slot>` read from `K` once per bind.
768
+ */ function _define_property$2(obj, key, value) {
769
+ if (key in obj) Object.defineProperty(obj, key, {
770
+ value,
771
+ enumerable: true,
772
+ configurable: true,
773
+ writable: true
774
+ });
775
+ else obj[key] = value;
776
+ return obj;
777
+ }
778
+ const ROOT_CTX = {
779
+ fail: "return 0",
780
+ inUnionFail: "return 0",
781
+ union: false,
782
+ clearTop: false
783
+ };
784
+ /** Factory-level helpers (see `TCompiledHelpers`), in declaration order. */ const HELPERS = [
785
+ ["pk", /\bpk\./],
786
+ ["ho", /\bho\.call\(/],
787
+ ["dec", /\bdec\.test\(/],
788
+ ["rn", /\brn\(/]
789
+ ];
790
+ /** Source of the check factory `(K, H) => check` of `layout`. */ function emitCheckFactory(layout) {
791
+ return new CheckEmitter(layout).emit();
792
+ }
793
+ let CheckEmitter = class CheckEmitter {
794
+ emit() {
795
+ const body = [];
796
+ for (let d = 0; d < this.defs.length; d++) if (this.fn[d]) body.push(...this.defFunction(d));
797
+ const root = this.layout[1];
798
+ const rootDef = root[2] >= 0 ? this.defs[root[2]][0] : -1;
799
+ if (root[0] === 0 && this.fn[root[2]] && (rootDef === require_json_schema.D_OBJECT || rootDef === require_json_schema.D_OBJECT_PATTERNS || rootDef === require_json_schema.D_TUPLE || rootDef === require_json_schema.D_INTERSECTION)) body.push(`return d${root[2]}`);
800
+ else {
801
+ body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
802
+ body.push("return r");
803
+ }
804
+ const code = body.join("\n");
805
+ const head = [];
806
+ const helpers = HELPERS.filter(([, use]) => use.test(code)).map(([h]) => `${h} = H.${h}`);
807
+ if (helpers.length > 0) head.push(`const ${helpers.join(", ")}`);
808
+ 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);
809
+ for (let i = 0; i < slots.length; i += 16) head.push(`const ${slots.slice(i, i + 16).map((k) => `k${k} = K[${k}]`).join(", ")}`);
810
+ return [
811
+ "(K, H) => {",
812
+ ...indent([...head, ...body]),
813
+ "}"
814
+ ].join("\n");
815
+ }
816
+ /**
817
+ * Object defs get a function each; so does every def a reference cycle passes through
818
+ * (each back-edge target of a DFS), which keeps inlining finite.
819
+ */ functionDefs() {
820
+ const defs = this.defs;
821
+ const fn = defs.map((def) => def[0] === require_json_schema.D_OBJECT || def[0] === require_json_schema.D_OBJECT_PATTERNS);
822
+ const state = Array.from({ length: defs.length }).fill(0);
823
+ const dfs = (d) => {
824
+ state[d] = 1;
825
+ for (const site of require_json_schema.childSites(defs[d])) {
826
+ const c = site[2];
827
+ if (c < 0) continue;
828
+ if (state[c] === 1) fn[c] = true;
829
+ else if (state[c] === 0) dfs(c);
830
+ }
831
+ state[d] = 2;
832
+ };
833
+ for (let d = 0; d < defs.length; d++) if (state[d] === 0) dfs(d);
834
+ return fn;
835
+ }
836
+ next(prefix) {
837
+ return `${prefix}${this.uid++}`;
838
+ }
839
+ /** A check function `name(v, f, o)` declaring the `q` / `t` locals its body uses. */ fnLines(name, body) {
840
+ const lines = body();
841
+ const code = lines.join("\n");
842
+ const locals = [];
843
+ if (code.includes("if (q) return 0")) locals.push(`const q = (f & ${require_json_schema.F_IN_UNION}) === 0`);
844
+ if (/\bt = /.test(code)) locals.push("let t");
845
+ return [
846
+ `function ${name}(v, f, o) {`,
847
+ ...indent([...locals, ...lines]),
848
+ "}"
849
+ ];
850
+ }
851
+ defFunction(d) {
852
+ const def = this.defs[d];
853
+ return this.fnLines(`d${d}`, () => {
854
+ switch (def[0]) {
855
+ case require_json_schema.D_OBJECT: return this.objectBody(def);
856
+ case require_json_schema.D_OBJECT_PATTERNS: return [`if (${notObject("v")}) return 0`, "return 2"];
857
+ case require_json_schema.D_ARRAY: return [...this.items(def[1], "v", ROOT_CTX), "return 1"];
858
+ case require_json_schema.D_UNION: return [...this.unionBranches(def[1], "v", false, (item) => [`return ${choose(this.literalExpr(item), "3", "1")}`]), "return 0"];
859
+ case require_json_schema.D_TUPLE: return [...this.tuple(def[1], "v", ROOT_CTX), "return 1"];
860
+ case require_json_schema.D_INTERSECTION: return [...def[1].flatMap((item) => this.site(item, "v", ROOT_CTX)), "return 1"];
861
+ default: return ["return 2"];
862
+ }
863
+ });
864
+ }
865
+ /** Mirrors `fastCheckObject` (+ `pendStrips` / `hasUnknownKey`). */ objectBody(def) {
866
+ const sites = def[2];
867
+ const props = def[1].map((key, i) => ({
868
+ key,
869
+ site: sites[i]
870
+ })).filter((p) => !this.isPhantom(p.site));
871
+ const lines = [`if (${notObject("v")}) return 0`, "if (pk.length !== 0) return 2"];
872
+ if (props.some((p) => p.site[0] === 0 || p.site[2] === require_json_schema.INTERP)) {
873
+ const top = require_json_schema.F_PARTIAL_TOP | require_json_schema.F_TOP;
874
+ lines.push(`const sk = (f & ${require_json_schema.F_PARTIAL_DEEP}) !== 0 || (f & ${top}) === ${top}`);
875
+ }
876
+ if (props.length > 0) lines.push("let r = 1");
877
+ for (const { key, site } of props) {
878
+ const p = this.next("P");
879
+ const x = this.next("x");
880
+ const access = validIdentifier.test(key) ? `v.${key}` : `v[${literalSource(key)}]`;
881
+ lines.push(`${p}: {`, ` const ${x} = ${access}`);
882
+ if (site[0] === 0 || site[2] === require_json_schema.INTERP) lines.push(` if (${x} === undefined && sk) break ${p}`);
883
+ const ctx = recordingCtx(`r = 0; break ${p}`, false, true);
884
+ lines.push(...indent(this.site(site, x, ctx)), "}");
885
+ }
886
+ if (props.length > 0) lines.push("if (r === 0) return 0");
887
+ const known = props.map((p) => p.key);
888
+ const onUnknown = `{ if ((f & ${require_json_schema.F_ERROR}) !== 0) return 0; if ((f & ${require_json_schema.F_TOP}) === 0) return 2; pk.push(k) }`;
889
+ const scan = known.length === 0 ? [`for (const k in v) if (ho.call(v, k)) ${onUnknown}`] : [
890
+ "for (const k in v) {",
891
+ " switch (k) {",
892
+ ...known.map((key) => ` case ${literalSource(key)}:`),
893
+ " break",
894
+ " default:",
895
+ ` if (ho.call(v, k)) ${onUnknown}`,
896
+ " }",
897
+ "}"
898
+ ];
899
+ lines.push(`if ((f & ${require_json_schema.F_ERROR | require_json_schema.F_STRIP}) !== 0) {`, ...indent(scan), "}", "return 1");
900
+ return lines;
901
+ }
902
+ isPhantom(site) {
903
+ const d = site[2];
904
+ return d >= 0 && this.defs[d][0] === require_json_schema.D_FINAL && this.defs[d][1] === "phantom";
905
+ }
906
+ isLiteralDef(d) {
907
+ return d >= 0 && this.defs[d][0] === require_json_schema.D_FINAL && this.defs[d].length > 2;
908
+ }
909
+ /** A required `never` union branch: it can never match (skipped). */ isNever(site) {
910
+ const d = site[2];
911
+ return site[0] === 0 && d >= 0 && this.defs[d][0] === require_json_schema.D_FINAL && this.defs[d][1] === "never" && !this.isLiteralDef(d);
912
+ }
913
+ /** Expression telling whether the site's type is a literal (`'true'` / `'false'` when known). */ literalExpr(site) {
914
+ const [, , d, , slot] = site;
915
+ if (d >= 0) return this.isLiteralDef(d) ? "true" : "false";
916
+ return `k${d === require_json_schema.INTERP ? slot + 1 : slot + (require_json_schema.hasRejectSlot(site) ? 1 : 0) + 1}`;
917
+ }
918
+ /** Mirrors `fastCheck` for one node holding `x`. */ site(site, x, ctx) {
919
+ const [optional, mask, d, shape, slot] = site;
920
+ if (d === require_json_schema.INTERP) return this.call(`k${slot}`, x, ctx);
921
+ let at = slot;
922
+ const rej = require_json_schema.hasRejectSlot(site) ? at++ : -1;
923
+ const body = d === require_json_schema.EXT ? this.call(`k${at}`, x, ctx) : this.def(d, mask, shape, at, x, ctx);
924
+ if (!optional) return body;
925
+ if (rej < 0) return body.length > 0 ? [
926
+ `if (${x} !== undefined && ${x} !== null) {`,
927
+ ...indent(body),
928
+ "}"
929
+ ] : [];
930
+ const lines = [`if (${x} === undefined || ${x} === null) {`, ` if (${x} === null && rn(k${rej})) ${ctx.fail}`];
931
+ if (body.length > 0) lines.push("} else {", ...indent(body));
932
+ lines.push("}");
933
+ return lines;
934
+ }
935
+ /** Calls a check function returning 0 / 1 / 2. */ call(fn, x, ctx) {
936
+ this.calls++;
937
+ return [`t = ${fn}(${x}, ${flags(ctx)}, o)`, `if (t !== 1) { if (t === 2) return 2; ${unblock(ctx.fail)} }`];
938
+ }
939
+ def(d, mask, shape, at, x, ctx) {
940
+ const def = this.defs[d];
941
+ const kind = def[0];
942
+ if (this.fn[d] && kind !== require_json_schema.D_ARRAY && kind !== require_json_schema.D_UNION) return this.call(`d${d}`, x, ctx);
943
+ switch (kind) {
944
+ case require_json_schema.D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
945
+ case require_json_schema.D_ARRAY: return [
946
+ `if (!Array.isArray(${x})) ${ctx.fail}`,
947
+ ...this.arrayConstraints(mask, require_json_schema.keySlots(mask, shape, at), x, ctx.fail),
948
+ ...this.fn[d] ? this.call(`d${d}`, x, ctx) : this.items(def[1], x, ctx)
949
+ ];
950
+ case require_json_schema.D_UNION: {
951
+ const constraints = this.unionConstraints(mask, shape, at, x, ctx.fail);
952
+ if (!this.fn[d]) return this.union(def[1], {
953
+ mask,
954
+ shape,
955
+ at
956
+ }, constraints, x, ctx);
957
+ this.calls++;
958
+ const lines = [
959
+ `t = d${d}(${x}, ${flags(ctx)}, o)`,
960
+ "if (t === 2) return 2",
961
+ `if (t === 0) ${ctx.fail}`
962
+ ];
963
+ if (constraints.length > 0) lines.push("if (t === 1) {", ...indent(constraints), "}");
964
+ return lines;
965
+ }
966
+ case require_json_schema.D_INTERSECTION: return def[1].flatMap((item) => this.site(item, x, ctx));
967
+ case require_json_schema.D_TUPLE: return this.tuple(def[1], x, ctx);
968
+ default: return ["return 2"];
969
+ }
970
+ }
971
+ /** Mirrors `fastCheckFinal` + the string / number / boolean constraints. */ final(def, mask, shape, at, x, fail) {
972
+ const designType = def[1];
973
+ if (designType === "phantom") return [];
974
+ if (def.length > 2) return [`if (${x} !== ${literalSource(def[2])}) ${fail}`];
975
+ const ks = require_json_schema.keySlots(mask, shape, at);
976
+ switch (designType) {
977
+ case "string": return this.stringChecks(mask, shape, ks, x, fail, [`typeof ${x} !== "string"`]);
978
+ case "number": return this.numberChecks(mask, ks, x, fail, [`typeof ${x} !== "number"`, `!Number.isFinite(${x})`]);
979
+ case "boolean": {
980
+ const conds = [`typeof ${x} !== "boolean"`];
981
+ if (mask & require_json_schema.B_REQUIRED) conds.push(`${x} !== true`);
982
+ return [`if (${conds.join(" || ")}) ${fail}`];
983
+ }
984
+ case "any": return [];
985
+ case "never": return [fail];
986
+ case "undefined": return [`if (${x} !== undefined) ${fail}`];
987
+ case "null": return [`if (${x} !== null) ${fail}`];
988
+ case "decimal": return [`if (typeof ${x} !== "string" || !dec.test(${x})) ${fail}`];
989
+ default: return ["return 2"];
990
+ }
991
+ }
992
+ stringChecks(mask, shape, ks, x, fail, conds) {
993
+ if (mask & require_json_schema.B_REQUIRED) conds.push(`${x}.trim().length === 0`);
994
+ if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
995
+ if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
996
+ const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
997
+ let p = 0;
998
+ for (const c of shape) if (c === "n") lines.push(`if (!k${ks.patterns[p++]}.test(${x})) ${fail}`);
999
+ else if (c === "s") {
1000
+ lines.push("return 2");
1001
+ break;
1002
+ }
1003
+ return lines;
1004
+ }
1005
+ numberChecks(mask, ks, x, fail, conds) {
1006
+ if (mask & require_json_schema.B_INT) conds.push(`${x} % 1 !== 0`);
1007
+ if (ks.min >= 0) conds.push(`${x} < k${ks.min}`);
1008
+ if (ks.max >= 0) conds.push(`${x} > k${ks.max}`);
1009
+ if (ks.exMin >= 0) conds.push(`${x} <= k${ks.exMin}`);
1010
+ if (ks.exMax >= 0) conds.push(`${x} >= k${ks.exMax}`);
1011
+ return conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
1012
+ }
1013
+ /** Array length constraints; `uniqueItems` (duplicate detection) is left to the walk. */ arrayConstraints(mask, ks, x, fail) {
1014
+ const conds = [];
1015
+ if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
1016
+ if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
1017
+ const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
1018
+ if (mask & require_json_schema.B_UNIQUE) lines.push("return 2");
1019
+ return lines;
1020
+ }
1021
+ /** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
1022
+ const ks = require_json_schema.keySlots(mask, shape, at);
1023
+ const branches = [];
1024
+ if (mask & require_json_schema.STRING_BITS) branches.push([`typeof ${x} === "string"`, this.stringChecks(mask, shape, ks, x, fail, [])]);
1025
+ if (mask & require_json_schema.NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
1026
+ if (mask & require_json_schema.B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
1027
+ if (mask & require_json_schema.ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
1028
+ const lines = [];
1029
+ branches.forEach(([cond, body], i) => {
1030
+ lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
1031
+ });
1032
+ if (lines.length > 0) lines.push("}");
1033
+ return lines;
1034
+ }
1035
+ /**
1036
+ * The union-level constraints after a non-literal branch passed. A required (non-optional)
1037
+ * branch of a known primitive / array type fixes `typeof`: only that part applies.
1038
+ */ branchConstraints(item, { mask, shape, at }, constraints, x, fail) {
1039
+ const [optional, , d] = item;
1040
+ const def = this.defs[d];
1041
+ if (optional) return constraints;
1042
+ const ks = require_json_schema.keySlots(mask, shape, at);
1043
+ if (def[0] === require_json_schema.D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
1044
+ if (def[0] !== require_json_schema.D_FINAL) return constraints;
1045
+ switch (def[1]) {
1046
+ case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
1047
+ case "number": return this.numberChecks(mask, ks, x, fail, []);
1048
+ case "boolean": return mask & require_json_schema.B_REQUIRED ? [`if (${x} !== true) ${fail}`] : [];
1049
+ case "null":
1050
+ case "undefined": return [];
1051
+ default: return constraints;
1052
+ }
1053
+ }
1054
+ /**
1055
+ * Mirrors the `fastCheck` union case: branches in declared order, each a labelled block a
1056
+ * FAIL breaks out of; `onMatch` ends a passing branch.
1057
+ */ unionBranches(items, x, clearTop, onMatch) {
1058
+ const lines = [];
1059
+ for (const item of items) {
1060
+ if (this.isNever(item)) continue;
1061
+ const b = this.next("B");
1062
+ const calls = this.calls;
1063
+ const fail = `break ${b}`;
1064
+ const body = this.site(item, x, {
1065
+ fail,
1066
+ inUnionFail: fail,
1067
+ union: true,
1068
+ clearTop
1069
+ });
1070
+ lines.push(`${b}: {`, ...indent([...body, ...onMatch(item)]), "}");
1071
+ if (this.calls !== calls) lines.push("if (pk.length !== 0) return 2");
1072
+ }
1073
+ return lines;
1074
+ }
1075
+ /** An inline union: the first matching branch passes after the union-level constraints. */ union(items, keys, constraints, x, ctx) {
1076
+ const u = this.next("U");
1077
+ const branches = this.unionBranches(items, x, ctx.clearTop, (item) => {
1078
+ const lines = [];
1079
+ const literal = constraints.length > 0 ? this.literalExpr(item) : "true";
1080
+ if (literal === "false") lines.push(...this.branchConstraints(item, keys, constraints, x, ctx.fail));
1081
+ else if (literal !== "true") lines.push(`if (!${literal}) {`, ...indent(constraints), "}");
1082
+ lines.push(`break ${u}`);
1083
+ return lines;
1084
+ });
1085
+ return [
1086
+ `${u}: {`,
1087
+ ...indent([...branches, ctx.fail]),
1088
+ "}"
1089
+ ];
1090
+ }
1091
+ /** Mirrors `checkItems`: every item is visited inside a union (BAIL beats FAIL). */ items(of, x, ctx) {
1092
+ const y = this.next("y");
1093
+ const a = this.next("a");
1094
+ const body = this.site(of, y, recordingCtx(`${a} = 0; continue`, ctx.union, true));
1095
+ if (body.length === 0) return [`for (const ${y} of ${x}) {}`];
1096
+ return [
1097
+ `let ${a} = 1`,
1098
+ `for (const ${y} of ${x}) {`,
1099
+ ...indent(body),
1100
+ "}",
1101
+ `if (${a} === 0) ${ctx.inUnionFail}`
1102
+ ];
1103
+ }
1104
+ /** Mirrors the `fastCheck` tuple case: stops at the first non-passing item. */ tuple(items, x, ctx) {
1105
+ const lines = [`if (!Array.isArray(${x}) || ${x}.length !== ${items.length}) ${ctx.fail}`];
1106
+ items.forEach((item, i) => {
1107
+ const e = this.next("e");
1108
+ lines.push(`const ${e} = ${x}[${i}]`, ...this.site(item, e, {
1109
+ ...ctx,
1110
+ clearTop: true
1111
+ }));
1112
+ });
1113
+ return lines;
1114
+ }
1115
+ constructor(layout) {
1116
+ _define_property$2(this, "layout", void 0);
1117
+ _define_property$2(this, "defs", void 0);
1118
+ /** Def index → emitted as its own function. */ _define_property$2(this, "fn", void 0);
1119
+ _define_property$2(this, "uid", void 0);
1120
+ /** Calls emitted so far (a union branch without calls cannot record strips). */ _define_property$2(this, "calls", void 0);
1121
+ this.layout = layout;
1122
+ this.uid = 0;
1123
+ this.calls = 0;
1124
+ this.defs = layout[0];
1125
+ this.fn = this.functionDefs();
1126
+ }
1127
+ };
1128
+ /**
1129
+ * Context of a node whose failure is recorded (`record`: e.g. `r = 0; break P1`) when
1130
+ * inside a union and leaves the check otherwise.
1131
+ */ function recordingCtx(record, union, clearTop) {
1132
+ const inUnionFail = `{ ${record} }`;
1133
+ return {
1134
+ fail: union ? inUnionFail : `{ if (q) return 0; ${record} }`,
1135
+ inUnionFail,
1136
+ union,
1137
+ clearTop
1138
+ };
1139
+ }
1140
+ /** Flags passed to a callee. */ function flags(ctx) {
1141
+ if (ctx.clearTop) return ctx.union ? `(f & ${~require_json_schema.F_TOP}) | ${require_json_schema.F_IN_UNION}` : `f & ${~require_json_schema.F_TOP}`;
1142
+ return ctx.union ? `f | ${require_json_schema.F_IN_UNION}` : "f";
1143
+ }
1144
+ /** The statements of a `{ … }` block statement (other statements as they are). */ function unblock(statement) {
1145
+ return statement.startsWith("{ ") && statement.endsWith(" }") ? statement.slice(2, -2) : statement;
1146
+ }
1147
+ /** `cond ? a : b` folded when `cond` is a constant. */ function choose(cond, a, b) {
1148
+ return cond === "true" ? a : cond === "false" ? b : `${cond} ? ${a} : ${b}`;
1149
+ }
1150
+ function notObject(x) {
1151
+ return `typeof ${x} !== "object" || ${x} === null || Array.isArray(${x})`;
1152
+ }
1153
+ function indent(lines, n = 2) {
1154
+ const pad = " ".repeat(n);
1155
+ return lines.map((l) => pad + l);
1156
+ }
1157
+
1158
+ //#endregion
1159
+ //#region packages/typescript/src/codegen/validation-model.ts
1160
+ function _define_property$1(obj, key, value) {
1161
+ if (key in obj) Object.defineProperty(obj, key, {
1162
+ value,
1163
+ enumerable: true,
1164
+ configurable: true,
1165
+ writable: true
1166
+ });
1167
+ else obj[key] = value;
1168
+ return obj;
1169
+ }
1170
+ /** Kinds of the opaque types standing for another module's types (see {@link classifyType}). */ const EXT_KIND = "#ext";
1171
+ const INTERP_KIND = "#interp";
1172
+ /**
1173
+ * How the layout treats a model type: `'ext'` — another module's type referenced as a
1174
+ * whole (also an alias / prop clone of one: `cloneTypeDef` keeps the kind); `'interp'` — a
1175
+ * chained reference into another module's type, only known at runtime.
1176
+ */ function classifyType(type) {
1177
+ const kind = type?.kind;
1178
+ return kind === EXT_KIND ? "ext" : kind === INTERP_KIND ? "interp" : void 0;
1179
+ }
1180
+ /**
1181
+ * Build-time model of the runtime type trees a generated `.as.js` module builds, used to
1182
+ * compile validator checks (`compileValidators`).
1183
+ *
1184
+ * The renderer drives it in lockstep with the builder chains it emits, through the real
1185
+ * runtime builder (`defineAnnotatedType`, `annotate`, `cloneRefProp`), so the model has
1186
+ * the same structure, the same type-def sharing (by identity) and the same validator
1187
+ * annotations as the module after its initialisation. Only the annotations the validator
1188
+ * pre-check reads are recorded. Types of other modules are opaque markers: a reference to
1189
+ * one (also an alias or a cloned prop of one) compiles to a cross-module site, bound at
1190
+ * runtime to the referenced class's own compiled check (see compiled-check/registry.ts).
1191
+ *
1192
+ * Anything the model cannot follow marks it broken; nothing is compiled then. A model that
1193
+ * nevertheless diverges from the runtime only costs speed: the runtime bind detects it and
1194
+ * the interpreted pre-check runs.
1195
+ */ var ValidationModel = class {
1196
+ /** Runs a model step; a throw marks the model broken. */ run(step) {
1197
+ if (this.broken) return;
1198
+ try {
1199
+ return step();
1200
+ } catch {
1201
+ this.broken = true;
1202
+ return;
1203
+ }
1204
+ }
1205
+ /** Declares a generated class (`static type = {}; static metadata = new Map()`). */ declare(name) {
1206
+ this.classes.set(name, {
1207
+ __is_atscript_annotated_type: true,
1208
+ type: {},
1209
+ metadata: /* @__PURE__ */ new Map(),
1210
+ name
1211
+ });
1212
+ }
1213
+ /** The model of a class declared in this module (anything else: the emitted code throws). */ classBase(name) {
1214
+ const cls = this.classes.get(name);
1215
+ if (!cls) throw new Error(`${name} is not a class of this module`);
1216
+ return cls;
1217
+ }
1218
+ /** `$(kind, name?)`. */ handle(kind, name) {
1219
+ return this.run(() => require_json_schema.defineAnnotatedType(kind, name === void 0 ? void 0 : this.classBase(name)));
1220
+ }
1221
+ /** `.refTo(Local)` / `.refTo(() => Imported)` (with an optional chain). */ refTo(handle, name, imported, chain) {
1222
+ this.run(() => {
1223
+ if (!handle) throw new Error("no chain");
1224
+ if (imported) {
1225
+ const marker = this.marker(name, chain ? INTERP_KIND : EXT_KIND);
1226
+ handle.refTo(() => marker, chain);
1227
+ } else handle.refTo(this.classBase(name), chain);
1228
+ });
1229
+ }
1230
+ /** The opaque stand-in of another module's type `name`. */ marker(name, kind) {
1231
+ const key = `${name}${kind}`;
1232
+ let marker = this.markers.get(key);
1233
+ if (!marker) {
1234
+ marker = {
1235
+ __is_atscript_annotated_type: true,
1236
+ type: { kind },
1237
+ metadata: /* @__PURE__ */ new Map()
1238
+ };
1239
+ this.markers.set(key, marker);
1240
+ }
1241
+ return marker;
1242
+ }
1243
+ /** `.annotate(key, value, multiple)` on the current chain (validator keys only). */ annotate(key, value, multiple) {
1244
+ if (!require_json_schema.isValidatorKey(key)) return;
1245
+ this.run(() => {
1246
+ if (!this.current) throw new Error("no chain");
1247
+ this.current.annotate(key, value, multiple);
1248
+ });
1249
+ }
1250
+ /** The node a mutating-annotate accessor (`Name.type.props.get("a")?…`) points at. */ resolve(name, steps) {
1251
+ let cur = this.classes.get(name);
1252
+ for (const step of steps) {
1253
+ if (cur === void 0 || cur === null) return;
1254
+ if (step === "type") {
1255
+ cur = cur.type;
1256
+ if (classifyType(cur) !== void 0) return;
1257
+ } else if (step[0] === "props") cur = cur.props?.get(step[1]);
1258
+ else cur = cur.items?.[step[1]];
1259
+ }
1260
+ return cur;
1261
+ }
1262
+ /** `$c(<accessor>, "prop")`. */ cloneProp(name, steps, prop) {
1263
+ this.run(() => {
1264
+ const parent = this.resolve(name, steps);
1265
+ if (parent) require_json_schema.cloneRefProp(parent, prop);
1266
+ });
1267
+ }
1268
+ /** `<accessor>.metadata.delete(key)`. */ deleteAnnotation(name, steps, key) {
1269
+ this.run(() => {
1270
+ this.resolve(name, steps)?.metadata?.delete(key);
1271
+ });
1272
+ }
1273
+ /** `$a(<accessor>.metadata, key, value, multiple)`. */ mutateAnnotation(name, steps, key, value, multiple) {
1274
+ if (!require_json_schema.isValidatorKey(key)) return;
1275
+ this.run(() => {
1276
+ require_json_schema.annotate(this.resolve(name, steps)?.metadata, key, value, multiple);
1277
+ });
1278
+ }
1279
+ /**
1280
+ * `$cv(Name, version, layout, factory)` for class `name`, or `undefined` when it cannot be
1281
+ * compiled (its root type is only known at runtime, or the model is broken).
1282
+ */ registration(name) {
1283
+ if (this.broken) return;
1284
+ const cls = this.classes.get(name);
1285
+ if (!cls) return;
1286
+ let layout;
1287
+ try {
1288
+ layout = buildLayout(cls, { regex: require_json_schema.getRegex }, classifyType);
1289
+ } catch {
1290
+ return;
1291
+ }
1292
+ const root = layout[1][2];
1293
+ if (root === require_json_schema.INTERP || root >= 0 && layout[0][root][0] === require_json_schema.D_UNKNOWN) return;
1294
+ return `$cv(${name}, ${require_json_schema.LAYOUT_VERSION}, ${layoutSource(layout)}, ${emitCheckFactory(layout)})`;
1295
+ }
1296
+ constructor() {
1297
+ /** The model could not follow the emitted code: compile nothing. */ _define_property$1(this, "broken", false);
1298
+ /** Handle of the chain being emitted (the target of `.annotate(…)` lines). */ _define_property$1(this, "current", void 0);
1299
+ _define_property$1(this, "classes", /* @__PURE__ */ new Map());
1300
+ _define_property$1(this, "markers", /* @__PURE__ */ new Map());
1301
+ }
1302
+ };
1303
+ /**
1304
+ * Runtime value of an annotation argument the emitted code writes as a raw expression
1305
+ * (`true`, `5`, `-1.5`, …). Anything else is opaque (truthy and not a number): the bind
1306
+ * compares only presence / truthiness and reads the real values at runtime.
1307
+ */ function rawLiteralValue(text) {
1308
+ switch (text) {
1309
+ case "true": return true;
1310
+ case "false": return false;
1311
+ case "null": return null;
1312
+ case "undefined": return;
1313
+ default: {
1314
+ const n = Number(text);
1315
+ return text.trim() !== "" && !Number.isNaN(n) ? n : { opaque: text };
1316
+ }
1317
+ }
1318
+ }
1319
+
664
1320
  //#endregion
665
1321
  //#region packages/typescript/src/codegen/js-renderer.ts
666
1322
  function _define_property(obj, key, value) {
@@ -686,7 +1342,24 @@ const QUERY_OP_MAP = {
686
1342
  "exists": "$exists",
687
1343
  "not exists": "$exists"
688
1344
  };
1345
+ /** Value field of each number-bound annotation's object form. */ const NUMBER_BOUND_FIELDS = {
1346
+ "expect.min": "minValue",
1347
+ "expect.max": "maxValue",
1348
+ "expect.exclusiveMin": "exclusiveMinValue",
1349
+ "expect.exclusiveMax": "exclusiveMaxValue"
1350
+ };
689
1351
  const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
1352
+ /** The runtime value of an annotation argument (see `JsRenderer.computeAnnotationValue`). */ function runtimeArg(type, token) {
1353
+ return type === "string" || type === void 0 && token.type === "text" ? token.text : rawLiteralValue(token.text);
1354
+ }
1355
+ /**
1356
+ * The runtime accessor of a mutating-annotate path: `Name` followed by the steps
1357
+ * (`.type`, `.props.get("a")?`, `.items[0]`).
1358
+ */ function accessorPath(targetName, steps) {
1359
+ let path = targetName;
1360
+ for (const step of steps) path += step === "type" ? ".type" : step[0] === "props" ? `.props.get("${escapeQuotes(step[1])}")?` : `.items[${step[1]}]`;
1361
+ return path;
1362
+ }
690
1363
  var JsRenderer = class extends BaseRenderer {
691
1364
  /**
692
1365
  * Relative imports get the configured `moduleExtension`; bare specifiers
@@ -865,6 +1538,7 @@ var JsRenderer = class extends BaseRenderer {
865
1538
  if (jsonSchemaMode === "lazy") imports.push("buildJsonSchema as $$");
866
1539
  if (this.opts?.exampleData) imports.push("createDataFromAnnotatedType as $e");
867
1540
  if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
1541
+ if (this.model) imports.push("registerCompiledCheck as $cv");
868
1542
  this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
869
1543
  this.computeSynthesizedImports();
870
1544
  this.writeln(SYNTH_IMPORTS_MARKER);
@@ -912,7 +1586,7 @@ var JsRenderer = class extends BaseRenderer {
912
1586
  if ((0, _atscript_core.isInterface)(def)) if (def.hasExtends) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
913
1587
  else def = def.getDefinition() || def;
914
1588
  this._adHocAnnotations = this.buildAdHocMap([annotateNode]);
915
- this.annotateType(def, node.id);
1589
+ this.modelClass(node.id, () => this.annotateType(def, node.id));
916
1590
  this._adHocAnnotations = null;
917
1591
  this.indent();
918
1592
  this.defineMetadataForAnnotateAlias(annotateNode);
@@ -926,13 +1600,38 @@ var JsRenderer = class extends BaseRenderer {
926
1600
  const resolved = this.doc.resolveInterfaceExtends(node);
927
1601
  if (resolved) def = resolved;
928
1602
  }
929
- this.annotateType(def, node.id);
1603
+ this.modelClass(node.id, () => this.annotateType(def, node.id));
930
1604
  this.indent().defineMetadata(node).unindent();
931
1605
  this.writeln();
932
1606
  }
1607
+ this.renderCompiledChecks();
933
1608
  this.writeln("// prettier-ignore-end");
934
1609
  super.post();
935
1610
  }
1611
+ /**
1612
+ * Emits class `name`'s chain; the validation model follows it (its handle stays the current
1613
+ * chain, the target of the class-level annotations emitted next).
1614
+ */ modelClass(name, emit) {
1615
+ if (this.model) this.model.current = void 0;
1616
+ emit();
1617
+ if (this.model?.current) this.modelClasses.push(name);
1618
+ }
1619
+ /**
1620
+ * `compileValidators`: one `$cv(Class, …)` registration per class, after every chain and
1621
+ * mutating annotate of the module ran (the compiled check binds on first use).
1622
+ */ renderCompiledChecks() {
1623
+ if (!this.model) return;
1624
+ const registrations = [];
1625
+ for (const name of this.modelClasses) {
1626
+ const registration = this.model.registration(name);
1627
+ if (registration) registrations.push(registration);
1628
+ }
1629
+ if (registrations.length > 0) {
1630
+ this.writeln("// Compiled validator checks");
1631
+ for (const registration of registrations) for (const line of registration.split("\n")) this.writeln(line);
1632
+ this.writeln();
1633
+ }
1634
+ }
936
1635
  renderClassStatics(node) {
937
1636
  this.writeln("static __is_atscript_annotated_type = true");
938
1637
  this.writeln("static type = {}");
@@ -963,6 +1662,7 @@ var JsRenderer = class extends BaseRenderer {
963
1662
  this.write(exported ? "export " : "");
964
1663
  this.write(`class ${node.id} `);
965
1664
  this.blockln("{}");
1665
+ this.model?.declare(node.id);
966
1666
  this.renderClassStatics(node);
967
1667
  this.popln();
968
1668
  this.postAnnotate.push(node);
@@ -1012,23 +1712,63 @@ var JsRenderer = class extends BaseRenderer {
1012
1712
  if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
1013
1713
  }
1014
1714
  toAnnotatedType(node) {
1015
- return this.toAnnotatedHandle(node).$type;
1715
+ return node?.entity === "interface" || node?.entity === "type" ? this.declType(node) : this.toAnnotatedHandle(node).$type;
1716
+ }
1717
+ /**
1718
+ * The build-time runtime type of an interface / type declaration (see `_declTypes`);
1719
+ * `doc` is the document that declares it (where an alias's target name resolves).
1720
+ */ declType(node, doc = this.doc) {
1721
+ const known = this._declTypes.get(node);
1722
+ if (known) return known;
1723
+ let def = node.getDefinition();
1724
+ if ((0, _atscript_core.isInterface)(node) && node.hasExtends) {
1725
+ const resolved = this.doc.resolveInterfaceExtends(node);
1726
+ if (resolved) def = resolved;
1727
+ }
1728
+ const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
1729
+ let handle;
1730
+ if (def && (0, _atscript_core.isRef)(def)) {
1731
+ const ref = def;
1732
+ const decl = doc.unwindType(ref.id, ref.chain)?.def;
1733
+ const target = this.refTarget(ref, decl, doc);
1734
+ handle = target ? require_json_schema.defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
1735
+ } else {
1736
+ const base = {
1737
+ __is_atscript_annotated_type: true,
1738
+ type: {},
1739
+ metadata: /* @__PURE__ */ new Map(),
1740
+ id: typeId
1741
+ };
1742
+ this._declTypes.set(node, base);
1743
+ if (def) this._declTypes.set(def, base);
1744
+ handle = this.toAnnotatedHandle(def, true, base);
1745
+ }
1746
+ this._declTypes.set(node, handle.$type);
1747
+ if (typeId) handle.id(typeId);
1748
+ this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1749
+ return handle.$type;
1016
1750
  }
1017
- toAnnotatedHandle(node, skipAnnotations = false) {
1018
- if (!node) return require_json_schema.defineAnnotatedType();
1751
+ /**
1752
+ * The declaration type a reference points at (see `declType`), or `undefined` when it is
1753
+ * not a declaration (a chained reference into a prop, an unresolved name). A plain
1754
+ * reference to a type alias points at the alias itself (its own type and id, like the
1755
+ * runtime `$().refTo(Alias)`), not at what the alias unwinds to.
1756
+ */ refTarget(ref, decl, doc = this.doc) {
1757
+ if (!decl) return;
1758
+ const owner = ref.hasChain ? void 0 : this.resolveOwner(doc, ref.id);
1759
+ if (owner?.node?.entity === "type" || owner?.node?.entity === "interface") return this.declType(owner.node, owner.doc);
1760
+ const known = this._declTypes.get(decl);
1761
+ if (known) return known;
1762
+ return (0, _atscript_core.isInterface)(decl) ? this.declType(decl) : void 0;
1763
+ }
1764
+ /**
1765
+ * The build-time runtime type of an expression node; with `base`, built into that object
1766
+ * (a declaration's type, see `declType`).
1767
+ */ toAnnotatedHandle(node, skipAnnotations = false, base) {
1768
+ if (!node) return require_json_schema.defineAnnotatedType(void 0, base);
1019
1769
  switch (node.entity) {
1020
1770
  case "interface":
1021
- case "type": {
1022
- let def = node.getDefinition();
1023
- if ((0, _atscript_core.isInterface)(node) && node.hasExtends) {
1024
- const resolved = this.doc.resolveInterfaceExtends(node);
1025
- if (resolved) def = resolved;
1026
- }
1027
- const handle = this.toAnnotatedHandle(def, true);
1028
- const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
1029
- if (typeId) handle.id(typeId);
1030
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1031
- }
1771
+ case "type": return require_json_schema.defineAnnotatedType().refTo(this.declType(node));
1032
1772
  case "prop": {
1033
1773
  const prop = node;
1034
1774
  const def = prop.getDefinition();
@@ -1042,7 +1782,8 @@ var JsRenderer = class extends BaseRenderer {
1042
1782
  case "ref": {
1043
1783
  const ref = node;
1044
1784
  const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
1045
- const handle = this.toAnnotatedHandle(decl, true);
1785
+ const target = this.refTarget(ref, decl);
1786
+ const handle = target ? require_json_schema.defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
1046
1787
  if (skipAnnotations) return handle;
1047
1788
  const own = this.doc.evalAnnotationsForNode(node);
1048
1789
  const referred = this.refTargetAnnotations(ref, decl);
@@ -1050,14 +1791,14 @@ var JsRenderer = class extends BaseRenderer {
1050
1791
  }
1051
1792
  case "primitive": {
1052
1793
  const prim = node;
1053
- const handle = require_json_schema.defineAnnotatedType();
1794
+ const handle = require_json_schema.defineAnnotatedType(void 0, base);
1054
1795
  handle.designType(prim.id === "never" ? "never" : prim.config.type);
1055
1796
  if (!skipAnnotations) this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1056
1797
  return handle;
1057
1798
  }
1058
1799
  case "const": {
1059
1800
  const c = node;
1060
- const handle = require_json_schema.defineAnnotatedType();
1801
+ const handle = require_json_schema.defineAnnotatedType(void 0, base);
1061
1802
  const t = c.token("identifier")?.type;
1062
1803
  handle.designType(t === "number" ? "number" : "string");
1063
1804
  handle.value(t === "number" ? Number(c.id) : c.id);
@@ -1065,7 +1806,7 @@ var JsRenderer = class extends BaseRenderer {
1065
1806
  }
1066
1807
  case "structure": {
1067
1808
  const struct = node;
1068
- const handle = require_json_schema.defineAnnotatedType("object");
1809
+ const handle = require_json_schema.defineAnnotatedType("object", base);
1069
1810
  for (const prop of Array.from(struct.props.values())) {
1070
1811
  const propHandle = this.toAnnotatedHandle(prop);
1071
1812
  const pattern = prop.token("identifier")?.pattern;
@@ -1076,24 +1817,24 @@ var JsRenderer = class extends BaseRenderer {
1076
1817
  }
1077
1818
  case "group": {
1078
1819
  const group = node;
1079
- const handle = require_json_schema.defineAnnotatedType(group.op === "|" ? "union" : "intersection");
1820
+ const handle = require_json_schema.defineAnnotatedType(group.op === "|" ? "union" : "intersection", base);
1080
1821
  for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1081
1822
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1082
1823
  }
1083
1824
  case "tuple": {
1084
1825
  const group = node;
1085
- const handle = require_json_schema.defineAnnotatedType("tuple");
1826
+ const handle = require_json_schema.defineAnnotatedType("tuple", base);
1086
1827
  for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1087
1828
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1088
1829
  }
1089
1830
  case "array": {
1090
1831
  const arr = node;
1091
- const handle = require_json_schema.defineAnnotatedType("array");
1832
+ const handle = require_json_schema.defineAnnotatedType("array", base);
1092
1833
  handle.of(this.toAnnotatedHandle(arr.getDefinition()).$type);
1093
1834
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1094
1835
  }
1095
1836
  default: {
1096
- const handle = require_json_schema.defineAnnotatedType();
1837
+ const handle = require_json_schema.defineAnnotatedType(void 0, base);
1097
1838
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1098
1839
  }
1099
1840
  }
@@ -1109,14 +1850,11 @@ var JsRenderer = class extends BaseRenderer {
1109
1850
  });
1110
1851
  break;
1111
1852
  case "expect.min":
1112
- if (a.args[0]) handle.annotate(a.name, {
1113
- minValue: Number(a.args[0].text),
1114
- message: a.args[1]?.text
1115
- });
1116
- break;
1117
1853
  case "expect.max":
1854
+ case "expect.exclusiveMin":
1855
+ case "expect.exclusiveMax":
1118
1856
  if (a.args[0]) handle.annotate(a.name, {
1119
- maxValue: Number(a.args[0].text),
1857
+ [NUMBER_BOUND_FIELDS[a.name]]: Number(a.args[0].text),
1120
1858
  message: a.args[1]?.text
1121
1859
  });
1122
1860
  break;
@@ -1168,8 +1906,10 @@ var JsRenderer = class extends BaseRenderer {
1168
1906
  node: synth.ownerNode
1169
1907
  } : this.resolveOwner(this.doc, ref.id);
1170
1908
  const refName = synth?.alias ?? ref.id;
1171
- const refExpr = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false) ? `() => ${refName}` : refName;
1909
+ const isImported = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false);
1910
+ const refExpr = isImported ? `() => ${refName}` : refName;
1172
1911
  this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().writeln(`.refTo(${refExpr}${chain})`);
1912
+ this.model?.refTo(this.modelHandle("", name), refName, isImported, ref.hasChain ? ref.chain.map((c) => c.text) : void 0);
1173
1913
  if (!ref.hasChain) {
1174
1914
  if (ownerDecl?.node) ownerDecl.doc.evalReferredAnnotations(ownerDecl.node)?.forEach((an) => {
1175
1915
  this.resolveAnnotationValue(ownerDecl.node, an);
@@ -1182,29 +1922,63 @@ var JsRenderer = class extends BaseRenderer {
1182
1922
  this.definePrimitive(node, name);
1183
1923
  return this;
1184
1924
  case "const":
1925
+ this.modelHandle("", name);
1185
1926
  this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().defineConst(node).unindent();
1186
1927
  return this;
1187
1928
  case "structure":
1929
+ this.modelHandle("object", name);
1188
1930
  this.writeln(`$("object"${name ? `, ${name}` : ""})`).indent().defineObject(node).unindent();
1189
1931
  return this;
1190
1932
  case "group":
1191
1933
  kind = node.op === "|" ? "union" : "intersection";
1934
+ this.modelHandle(kind, name);
1192
1935
  this.writeln(`$("${kind}"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1193
1936
  return this;
1194
1937
  case "tuple":
1938
+ this.modelHandle("tuple", name);
1195
1939
  this.writeln(`$("tuple"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1196
1940
  return this;
1197
1941
  case "array":
1942
+ this.modelHandle("array", name);
1198
1943
  this.writeln(`$("array"${name ? `, ${name}` : ""})`).indent().defineArray(node).unindent();
1199
1944
  return this;
1200
1945
  default: return this;
1201
1946
  }
1202
1947
  }
1948
+ /** `$(kind, name?)` in the validation model; it becomes the current chain. */ modelHandle(kind, name) {
1949
+ if (!this.model) return;
1950
+ const h = this.model.handle(kind, name);
1951
+ this.model.current = h;
1952
+ return h;
1953
+ }
1954
+ /**
1955
+ * The model handle of a nested chain (`emit` writes it and its annotations): `current`
1956
+ * is cleared first so a chain that emits nothing breaks the model instead of leaving a
1957
+ * stale handle, and restored to the parent chain afterwards.
1958
+ */ modelChild(emit) {
1959
+ if (!this.model) {
1960
+ emit();
1961
+ return;
1962
+ }
1963
+ const parent = this.model.current;
1964
+ this.model.current = void 0;
1965
+ emit();
1966
+ const child = this.model.current;
1967
+ this.model.current = parent;
1968
+ if (!child) this.model.broken = true;
1969
+ return child;
1970
+ }
1203
1971
  defineConst(node) {
1204
1972
  const t = node.token("identifier")?.type;
1205
1973
  const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
1206
1974
  this.writeln(`.designType("${escapeQuotes(designType)}")`);
1207
1975
  this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
1976
+ if (this.model) {
1977
+ const h = this.model.current;
1978
+ this.model.run(() => {
1979
+ h.designType(designType).value(t === "text" ? node.id : rawLiteralValue(node.id));
1980
+ });
1981
+ }
1208
1982
  return this;
1209
1983
  }
1210
1984
  definePrimitive(node, name) {
@@ -1212,66 +1986,82 @@ var JsRenderer = class extends BaseRenderer {
1212
1986
  this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
1213
1987
  return this;
1214
1988
  }
1215
- renderPrimitiveDef(def, name) {
1989
+ /** Emits a primitive's builder chain (and follows it in the validation model). */ renderPrimitiveDef(def, name) {
1216
1990
  const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
1217
- if (!def) return this.writeln(`$(${d()}).designType("any")`);
1218
- if (typeof def === "string") return this.writeln(`$(${d()}).designType("${def === "void" ? "undefined" : def}")`);
1991
+ const final = (designType) => {
1992
+ this.writeln(`$(${d()}).designType("${designType}")`);
1993
+ const h = this.modelHandle("", name);
1994
+ this.model?.run(() => h.designType(designType));
1995
+ };
1996
+ if (!def) return final("any");
1997
+ if (typeof def === "string") return final(def === "void" ? "undefined" : def);
1219
1998
  switch (def.kind) {
1220
- case "final": return this.writeln(`$(${d()}).designType("${def.value === "void" ? "undefined" : def.value}")`);
1999
+ case "final": return final(def.value === "void" ? "undefined" : def.value);
1221
2000
  case "union":
1222
2001
  case "intersection":
1223
2002
  case "tuple":
1224
2003
  this.writeln(`$(${d(def.kind)})`);
2004
+ this.modelHandle(def.kind, name);
1225
2005
  this.indent();
1226
2006
  for (const itemDef of def.items) {
1227
2007
  this.write(`.item(`);
1228
2008
  this.indent();
1229
- this.renderPrimitiveDef(itemDef);
2009
+ const child = this.modelChild(() => this.renderPrimitiveDef(itemDef));
1230
2010
  this.writeln(".$type");
1231
2011
  this.unindent();
1232
2012
  this.write(`)`);
2013
+ this.model?.run(() => this.model.current.item(child.$type));
1233
2014
  }
1234
2015
  this.unindent();
1235
2016
  return;
1236
- case "array":
2017
+ case "array": {
1237
2018
  this.writeln(`$(${d("array")})`);
2019
+ this.modelHandle("array", name);
1238
2020
  this.indent();
1239
2021
  this.write(".of(");
1240
2022
  this.indent();
1241
- this.renderPrimitiveDef(def.of);
2023
+ const child = this.modelChild(() => this.renderPrimitiveDef(def.of));
1242
2024
  this.writeln(`.$type`);
1243
2025
  this.unindent();
1244
2026
  this.writeln(`)`);
1245
2027
  this.unindent();
2028
+ this.model?.run(() => this.model.current.of(child.$type));
1246
2029
  return;
1247
- case "object":
2030
+ }
2031
+ case "object": {
1248
2032
  this.writeln(`$(${d("object")})`);
2033
+ this.modelHandle("object", name);
1249
2034
  this.indent();
1250
- for (const [key, propDef] of Object.entries(def.props)) {
1251
- const optional = typeof propDef === "object" && propDef.optional;
1252
- this.writeln(`.prop(`);
1253
- this.indent();
1254
- this.writeln(`"${escapeQuotes(key)}",`);
1255
- this.renderPrimitiveDef(propDef);
1256
- if (optional) this.writeln(".optional()");
1257
- this.writeln(".$type");
1258
- this.unindent();
1259
- this.write(`)`);
1260
- }
1261
- for (const [key, propDef] of Object.entries(def.propsPatterns)) {
2035
+ const props = [...Object.entries(def.props).map(([k, p]) => [
2036
+ k,
2037
+ p,
2038
+ false
2039
+ ]), ...Object.entries(def.propsPatterns).map(([k, p]) => [
2040
+ k,
2041
+ p,
2042
+ true
2043
+ ])];
2044
+ for (const [key, propDef, isPattern] of props) {
1262
2045
  const optional = typeof propDef === "object" && propDef.optional;
1263
- this.writeln(`.propPattern(`);
2046
+ this.writeln(isPattern ? `.propPattern(` : `.prop(`);
1264
2047
  this.indent();
1265
- this.writeln(`${key},`);
1266
- this.renderPrimitiveDef(propDef);
1267
- if (optional) this.writeln(".optional()");
2048
+ this.writeln(isPattern ? `${key},` : `"${escapeQuotes(key)}",`);
2049
+ const child = this.modelChild(() => {
2050
+ this.renderPrimitiveDef(propDef);
2051
+ if (optional) {
2052
+ this.writeln(".optional()");
2053
+ this.model?.run(() => this.model.current.optional());
2054
+ }
2055
+ });
1268
2056
  this.writeln(".$type");
1269
2057
  this.unindent();
1270
2058
  this.write(`)`);
2059
+ this.model?.run(() => isPattern ? this.model.current.propPattern(/./, child.$type) : this.model.current.prop(key, child.$type));
1271
2060
  }
1272
2061
  this.unindent();
1273
2062
  return;
1274
- default: return this.writeln(`$(${d()}).designType("any")`);
2063
+ }
2064
+ default: return final("any");
1275
2065
  }
1276
2066
  }
1277
2067
  defineObject(node) {
@@ -1289,25 +2079,39 @@ var JsRenderer = class extends BaseRenderer {
1289
2079
  this.indent();
1290
2080
  this.writeln(`"${escapeQuotes(prop.id)}",`);
1291
2081
  }
1292
- this.annotateType(prop.getDefinition());
1293
- this.indent().defineMetadata(prop).unindent();
2082
+ const child = this.modelChild(() => {
2083
+ this.annotateType(prop.getDefinition());
2084
+ this.indent().defineMetadata(prop).unindent();
2085
+ });
1294
2086
  if (optional) this.writeln(" .optional()");
1295
2087
  this.writeln(" .$type");
1296
2088
  this.unindent();
1297
2089
  this.write(`)`);
1298
2090
  this._propPath.pop();
2091
+ this.model?.run(() => {
2092
+ if (optional) child.optional();
2093
+ if (pattern) this.model.current.propPattern(pattern, child.$type);
2094
+ else this.model.current.prop(prop.id, child.$type);
2095
+ });
1299
2096
  }
1300
2097
  this.writeln();
1301
2098
  return this;
1302
2099
  }
1303
2100
  defineGroup(node) {
1304
- const items = node.unwrap();
1305
- for (const item of items) this.write(".item(").indent().annotateType(item).defineInlinePrimitiveMetadata(item).write(" .$type").writeln(`)`).unindent();
2101
+ for (const item of node.unwrap()) {
2102
+ this.write(".item(").indent();
2103
+ const child = this.modelChild(() => this.annotateType(item).defineInlinePrimitiveMetadata(item));
2104
+ this.write(" .$type").writeln(`)`).unindent();
2105
+ this.model?.run(() => this.model.current.item(child.$type));
2106
+ }
1306
2107
  return this;
1307
2108
  }
1308
2109
  defineArray(node) {
1309
2110
  const of = node.getDefinition();
1310
- this.write(".of(").indent().annotateType(of).defineInlinePrimitiveMetadata(of).write(" .$type").writeln(`)`).unindent();
2111
+ this.write(".of(").indent();
2112
+ const child = this.modelChild(() => this.annotateType(of).defineInlinePrimitiveMetadata(of));
2113
+ this.write(" .$type").writeln(`)`).unindent();
2114
+ this.model?.run(() => this.model.current.of(child.$type));
1311
2115
  return this;
1312
2116
  }
1313
2117
  /**
@@ -1378,9 +2182,10 @@ var JsRenderer = class extends BaseRenderer {
1378
2182
  return this;
1379
2183
  }
1380
2184
  resolveAnnotationValue(node, an) {
1381
- const { value, multiple } = this.computeAnnotationValue(node, an);
2185
+ const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
1382
2186
  if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
1383
2187
  else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
2188
+ this.model?.annotate(an.name, runtime, multiple);
1384
2189
  }
1385
2190
  emitRefValue(text, origin) {
1386
2191
  const dotIdx = text.indexOf(".");
@@ -1459,33 +2264,50 @@ var JsRenderer = class extends BaseRenderer {
1459
2264
  default: return token.text;
1460
2265
  }
1461
2266
  }
1462
- computeAnnotationValue(node, an) {
2267
+ /**
2268
+ * The JS source of an annotation's value, and (for the validation model, which only reads
2269
+ * validator annotations: numbers, strings, flags) the runtime value it evaluates to;
2270
+ * other argument kinds are opaque there.
2271
+ */ computeAnnotationValue(node, an) {
1463
2272
  const origin = this.doc.annotationOrigin(an);
1464
2273
  const spec = this.doc.resolveAnnotation(an.name);
1465
2274
  let targetValue = "true";
2275
+ let runtime = true;
1466
2276
  let multiple = false;
1467
2277
  if (spec) {
1468
2278
  multiple = spec.config.multiple;
1469
2279
  const length = spec.arguments.length;
1470
- if (length !== 0) if (Array.isArray(spec.config.argument)) {
1471
- targetValue = "{ ";
1472
- let i = 0;
1473
- for (const aSpec of spec.arguments) {
1474
- if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
1475
- i++;
2280
+ if (length !== 0) {
2281
+ if (Array.isArray(spec.config.argument)) {
2282
+ targetValue = "{ ";
2283
+ const fields = {};
2284
+ let i = 0;
2285
+ for (const aSpec of spec.arguments) {
2286
+ if (an.args[i]) {
2287
+ targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
2288
+ fields[aSpec.name] = runtimeArg(aSpec.type, an.args[i]);
2289
+ }
2290
+ i++;
2291
+ }
2292
+ targetValue += "}";
2293
+ runtime = fields;
2294
+ } else if (an.args[0]) {
2295
+ const aSpec = spec.arguments[0];
2296
+ targetValue = this.emitArgValue(aSpec, an.args[0], origin);
2297
+ runtime = runtimeArg(aSpec.type, an.args[0]);
1476
2298
  }
1477
- targetValue += "}";
1478
- } else {
1479
- const aSpec = spec.arguments[0];
1480
- targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0], origin) : "true";
1481
2299
  }
1482
2300
  } else {
1483
2301
  multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
1484
- if (an.args.length > 0) targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
2302
+ if (an.args.length > 0) {
2303
+ targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
2304
+ runtime = runtimeArg(void 0, an.args[0]);
2305
+ }
1485
2306
  }
1486
2307
  return {
1487
2308
  value: targetValue,
1488
- multiple: !!multiple
2309
+ multiple: !!multiple,
2310
+ runtime
1489
2311
  };
1490
2312
  }
1491
2313
  renderMutatingAnnotateNode(node) {
@@ -1498,7 +2320,7 @@ var JsRenderer = class extends BaseRenderer {
1498
2320
  const anns = entry.annotations;
1499
2321
  if (!anns || anns.length === 0) continue;
1500
2322
  const parts = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)] : [entry.id];
1501
- const { accessors, clones } = this.buildMutatingAccessors(targetName, targetDef, parts);
2323
+ const { accessors, clones } = this.buildMutatingAccessors(targetDef, parts);
1502
2324
  allClones.push(...clones);
1503
2325
  entryAccessors.push({
1504
2326
  entry,
@@ -1507,29 +2329,36 @@ var JsRenderer = class extends BaseRenderer {
1507
2329
  }
1508
2330
  const cloneKeys = /* @__PURE__ */ new Set();
1509
2331
  for (const clone of allClones) {
1510
- const key = `${clone.parentPath}|${clone.propName}`;
2332
+ const parentPath = accessorPath(targetName, clone.parentSteps);
2333
+ const key = `${parentPath}|${clone.propName}`;
1511
2334
  if (!cloneKeys.has(key)) {
1512
2335
  cloneKeys.add(key);
1513
- this.writeln(`$c(${clone.parentPath}, "${escapeQuotes(clone.propName)}")`);
2336
+ this.writeln(`$c(${parentPath}, "${escapeQuotes(clone.propName)}")`);
2337
+ this.model?.cloneProp(targetName, clone.parentSteps, clone.propName);
1514
2338
  }
1515
2339
  }
1516
- for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor);
2340
+ for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor, targetName);
1517
2341
  const topAnnotations = node.annotations;
1518
- if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, targetName);
2342
+ if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, [], targetName);
1519
2343
  this.writeln();
1520
2344
  }
1521
- emitMutatingAnnotations(node, annotations, accessor) {
2345
+ emitMutatingAnnotations(node, annotations, steps, targetName) {
2346
+ const accessor = accessorPath(targetName, steps);
1522
2347
  const cleared = /* @__PURE__ */ new Set();
1523
2348
  for (const an of annotations) {
1524
- const { value, multiple } = this.computeAnnotationValue(node, an);
2349
+ const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
1525
2350
  if (multiple) {
1526
2351
  if (!cleared.has(an.name)) {
1527
2352
  const spec = this.doc.resolveAnnotation(an.name);
1528
- if (!spec || spec.config.mergeStrategy !== "append") this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
2353
+ if (!spec || spec.config.mergeStrategy !== "append") {
2354
+ this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
2355
+ this.model?.deleteAnnotation(targetName, steps, an.name);
2356
+ }
1529
2357
  cleared.add(an.name);
1530
2358
  }
1531
2359
  this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value}, true)`);
1532
2360
  } else this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value})`);
2361
+ this.model?.mutateAnnotation(targetName, steps, an.name, runtime, multiple);
1533
2362
  }
1534
2363
  }
1535
2364
  resolveTargetDef(targetName) {
@@ -1540,51 +2369,48 @@ var JsRenderer = class extends BaseRenderer {
1540
2369
  return def;
1541
2370
  }
1542
2371
  /**
1543
- * Builds the runtime accessor paths for mutating annotate entries.
2372
+ * Builds the accessor paths (as steps, see `accessorPath`) for mutating annotate entries.
1544
2373
  * Computes exact paths at compile time by walking the AST,
1545
2374
  * so the generated JS accesses props directly without runtime search.
1546
2375
  * Returns multiple paths when a property appears in multiple union branches.
1547
- */ buildMutatingAccessors(targetName, targetDef, parts) {
2376
+ */ buildMutatingAccessors(targetDef, parts) {
1548
2377
  let accessors = [{
1549
- prefix: `${targetName}.type`,
2378
+ steps: ["type"],
1550
2379
  def: targetDef
1551
2380
  }];
1552
2381
  const clones = [];
1553
2382
  for (let i = 0; i < parts.length; i++) {
2383
+ const last = i === parts.length - 1;
1554
2384
  const nextAccessors = [];
1555
- for (const { prefix, def } of accessors) {
2385
+ for (const { steps, def } of accessors) {
1556
2386
  const results = this.buildPropPaths(def, parts[i]);
1557
- if (results.length > 0) for (const result of results) if (i < parts.length - 1) {
1558
- if (result.propDef && (0, _atscript_core.isRef)(result.propDef)) clones.push({
1559
- parentPath: prefix,
2387
+ const found = results.length > 0 ? results : [{
2388
+ steps: [["props", parts[i]]],
2389
+ propDef: void 0
2390
+ }];
2391
+ for (const result of found) {
2392
+ if (!last && result.propDef && (0, _atscript_core.isRef)(result.propDef)) clones.push({
2393
+ parentSteps: steps,
1560
2394
  propName: parts[i]
1561
2395
  });
2396
+ const next = [...steps, ...result.steps];
2397
+ if (!last) next.push("type");
1562
2398
  nextAccessors.push({
1563
- prefix: `${prefix}${result.path}?.type`,
2399
+ steps: next,
1564
2400
  def: result.propDef
1565
2401
  });
1566
- } else nextAccessors.push({
1567
- prefix: `${prefix}${result.path}?`,
1568
- def: result.propDef
1569
- });
1570
- else {
1571
- const suffix = `.props.get("${escapeQuotes(parts[i])}")${i < parts.length - 1 ? "?.type" : "?"}`;
1572
- nextAccessors.push({
1573
- prefix: `${prefix}${suffix}`,
1574
- def: void 0
1575
- });
1576
2402
  }
1577
2403
  }
1578
2404
  accessors = nextAccessors;
1579
2405
  }
1580
2406
  return {
1581
- accessors: accessors.map((a) => a.prefix),
2407
+ accessors: accessors.map((a) => a.steps),
1582
2408
  clones
1583
2409
  };
1584
2410
  }
1585
2411
  /**
1586
2412
  * Finds a property in a type tree at compile time, returning all
1587
- * matching runtime path strings and prop definitions for further chaining.
2413
+ * matching accessor steps and prop definitions for further chaining.
1588
2414
  * Returns multiple results when the same property appears in different union branches.
1589
2415
  */ buildPropPaths(def, propName) {
1590
2416
  if (!def) return [];
@@ -1598,7 +2424,7 @@ var JsRenderer = class extends BaseRenderer {
1598
2424
  if ((0, _atscript_core.isStructure)(def)) {
1599
2425
  const prop = def.props.get(propName);
1600
2426
  if (prop) return [{
1601
- path: `.props.get("${escapeQuotes(propName)}")`,
2427
+ steps: [["props", propName]],
1602
2428
  propDef: prop.getDefinition()
1603
2429
  }];
1604
2430
  return [];
@@ -1607,7 +2433,11 @@ var JsRenderer = class extends BaseRenderer {
1607
2433
  const items = def.unwrap();
1608
2434
  const results = [];
1609
2435
  for (let i = 0; i < items.length; i++) for (const result of this.buildPropPaths(items[i], propName)) results.push({
1610
- path: `.items[${i}].type${result.path}`,
2436
+ steps: [
2437
+ ["items", i],
2438
+ "type",
2439
+ ...result.steps
2440
+ ],
1611
2441
  propDef: result.propDef
1612
2442
  });
1613
2443
  return results;
@@ -1615,13 +2445,19 @@ var JsRenderer = class extends BaseRenderer {
1615
2445
  return [];
1616
2446
  }
1617
2447
  constructor(doc, opts) {
1618
- super(doc), _define_property(this, "opts", void 0), _define_property(this, "postAnnotate", void 0), _define_property(this, "_adHocAnnotations", void 0), _define_property(this, "_propPath", void 0), _define_property(this, "typeIds", void 0), _define_property(this, "_unusedJs", void 0), _define_property(this, "_extendsRefs", void 0), _define_property(this, "_refSynthInfo", void 0), _define_property(this, "_synthImports", void 0), _define_property(this, "_synthComputed", void 0), _define_property(this, "_synthTaken", void 0), _define_property(this, "_synthAllocated", void 0), _define_property(this, "_synthPathCache", void 0), _define_property(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();
2448
+ super(doc), _define_property(this, "opts", void 0), _define_property(this, "postAnnotate", void 0), _define_property(this, "_adHocAnnotations", void 0), _define_property(this, "_propPath", void 0), _define_property(this, "typeIds", void 0), _define_property(this, "_unusedJs", void 0), _define_property(this, "_extendsRefs", void 0), _define_property(this, "_refSynthInfo", void 0), _define_property(this, "_synthImports", void 0), _define_property(this, "_synthComputed", void 0), _define_property(this, "_synthTaken", void 0), _define_property(this, "_synthAllocated", void 0), _define_property(this, "_synthPathCache", void 0), _define_property(this, "_ownerCache", void 0), _define_property(this, "model", void 0), _define_property(this, "modelClasses", void 0), _define_property(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();
2449
+ if (opts?.compileValidators) this.model = new ValidationModel();
1619
2450
  }
1620
2451
  };
1621
2452
 
1622
2453
  //#endregion
1623
2454
  //#region packages/typescript/src/plugin.ts
1624
2455
  /**
2456
+ * Render formats of the JS output that override {@link TTsPluginOptions.compileValidators}
2457
+ * (used by `unplugin-atscript`'s `compileValidators` option).
2458
+ */ const JS_COMPILED_FORMAT = "js:compiled";
2459
+ const JS_INTERPRETED_FORMAT = "js:interpreted";
2460
+ /**
1625
2461
  * Resolves the effective JSON schema mode from plugin options.
1626
2462
  */ function resolveJsonSchemaMode(opts) {
1627
2463
  if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
@@ -1635,10 +2471,16 @@ const tsPlugin = (opts) => {
1635
2471
  fileName: `${doc.name}.d.ts`,
1636
2472
  content: new TypeRenderer(doc, opts).render()
1637
2473
  }];
1638
- if (format === "js") return [{
1639
- fileName: `${doc.name}.js`,
1640
- content: new JsRenderer(doc, opts).render()
1641
- }];
2474
+ if (format === "js" || format === JS_COMPILED_FORMAT || format === JS_INTERPRETED_FORMAT) {
2475
+ const jsOpts = format === "js" ? opts : {
2476
+ ...opts,
2477
+ compileValidators: format === JS_COMPILED_FORMAT
2478
+ };
2479
+ return [{
2480
+ fileName: `${doc.name}.js`,
2481
+ content: new JsRenderer(doc, jsOpts).render()
2482
+ }];
2483
+ }
1642
2484
  },
1643
2485
  async buildEnd(output, format, repo) {
1644
2486
  if (format === "dts" || format === _atscript_core.DEFAULT_FORMAT) {
@@ -1666,6 +2508,18 @@ const tsPlugin = (opts) => {
1666
2508
  };
1667
2509
 
1668
2510
  //#endregion
2511
+ Object.defineProperty(exports, 'JS_COMPILED_FORMAT', {
2512
+ enumerable: true,
2513
+ get: function () {
2514
+ return JS_COMPILED_FORMAT;
2515
+ }
2516
+ });
2517
+ Object.defineProperty(exports, 'JS_INTERPRETED_FORMAT', {
2518
+ enumerable: true,
2519
+ get: function () {
2520
+ return JS_INTERPRETED_FORMAT;
2521
+ }
2522
+ });
1669
2523
  Object.defineProperty(exports, '__toESM', {
1670
2524
  enumerable: true,
1671
2525
  get: function () {