@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.
@@ -1,9 +1,9 @@
1
- import { l as defineAnnotatedType, t as buildJsonSchema } from "./json-schema-BtZ_OIcu.mjs";
1
+ import { A as D_UNKNOWN, B as LAYOUT_VERSION, C as D_ARRAY, D as D_OBJECT_PATTERNS, E as D_OBJECT, F as F_PARTIAL_TOP, G as keySlots, H as STRING_BITS, I as F_STRIP, J as siteSlotCount, K as readKeys, L as F_TOP, M as F_ERROR, N as F_IN_UNION, O as D_TUPLE, P as F_PARTIAL_DEEP, R as INTERP, S as B_UNIQUE, T as D_INTERSECTION, U as childSites, V as NUMBER_BITS, W as hasRejectSlot, X as isValidatorKey, _ as getRegex, b as B_INT, d as defineAnnotatedType, j as EXT, k as D_UNION, o as annotate, q as siteBits, s as cloneRefProp, t as buildJsonSchema, w as D_FINAL, x as B_REQUIRED, y as ARRAY_BITS, z as ITEMS_KIND_CODES } from "./json-schema-BG1SEcjI.mjs";
2
2
  import path from "path";
3
3
  import { DEFAULT_FORMAT, flattenInterfaceNode, getRelPath, hasNavPropAnnotation, isArray, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isInterface, isPrimitive, isProp, isQueryLogical, isRef, isStructure } from "@atscript/core";
4
4
 
5
5
  //#region packages/typescript/src/codegen/code-printer.ts
6
- function _define_property$3(obj, key, value) {
6
+ function _define_property$5(obj, key, value) {
7
7
  if (key in obj) Object.defineProperty(obj, key, {
8
8
  value,
9
9
  enumerable: true,
@@ -96,17 +96,17 @@ var CodePrinter = class {
96
96
  return " ".repeat(this.indentLevel * this.indentSize);
97
97
  }
98
98
  constructor() {
99
- _define_property$3(this, "lines", []);
100
- _define_property$3(this, "currentLine", "");
101
- _define_property$3(this, "indentLevel", 0);
102
- _define_property$3(this, "indentSize", 2);
103
- _define_property$3(this, "blockStack", []);
99
+ _define_property$5(this, "lines", []);
100
+ _define_property$5(this, "currentLine", "");
101
+ _define_property$5(this, "indentLevel", 0);
102
+ _define_property$5(this, "indentSize", 2);
103
+ _define_property$5(this, "blockStack", []);
104
104
  }
105
105
  };
106
106
 
107
107
  //#endregion
108
108
  //#region packages/typescript/src/codegen/base-renderer.ts
109
- function _define_property$2(obj, key, value) {
109
+ function _define_property$4(obj, key, value) {
110
110
  if (key in obj) Object.defineProperty(obj, key, {
111
111
  value,
112
112
  enumerable: true,
@@ -169,7 +169,7 @@ var BaseRenderer = class extends CodePrinter {
169
169
  }
170
170
  }
171
171
  constructor(doc) {
172
- super(), _define_property$2(this, "doc", void 0), _define_property$2(this, "_unused", void 0), this.doc = doc;
172
+ super(), _define_property$4(this, "doc", void 0), _define_property$4(this, "_unused", void 0), this.doc = doc;
173
173
  }
174
174
  };
175
175
 
@@ -192,7 +192,7 @@ function escapeQuotes(str) {
192
192
 
193
193
  //#endregion
194
194
  //#region packages/typescript/src/codegen/type-renderer.ts
195
- function _define_property$1(obj, key, value) {
195
+ function _define_property$3(obj, key, value) {
196
196
  if (key in obj) Object.defineProperty(obj, key, {
197
197
  value,
198
198
  enumerable: true,
@@ -616,7 +616,7 @@ var TypeRenderer = class TypeRenderer extends BaseRenderer {
616
616
  this.writeln(` */`);
617
617
  }
618
618
  constructor(doc, opts) {
619
- super(doc), _define_property$1(this, "opts", void 0), this.opts = opts;
619
+ super(doc), _define_property$3(this, "opts", void 0), this.opts = opts;
620
620
  }
621
621
  };
622
622
  function renderPrimitiveTypeDef(def) {
@@ -633,6 +633,662 @@ function renderPrimitiveTypeDef(def) {
633
633
  }
634
634
  }
635
635
 
636
+ //#endregion
637
+ //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
638
+ /**
639
+ * Build-time layout derivation (renderer and tests; not part of the runtime bundle).
640
+ */
641
+ /**
642
+ * Derives the layout of `root` (see layout.ts). Shared / recursive type defs are recorded
643
+ * once and referenced by index.
644
+ */ function buildLayout(root, reader, classify) {
645
+ const defs = [];
646
+ const index = /* @__PURE__ */ new Map();
647
+ let slots = 0;
648
+ function describeDef(type) {
649
+ switch (type.kind) {
650
+ case "": return type.value === void 0 ? [D_FINAL, type.designType] : [
651
+ D_FINAL,
652
+ type.designType,
653
+ type.value
654
+ ];
655
+ case "object": {
656
+ if (type.propsPatterns.length > 0) return [D_OBJECT_PATTERNS];
657
+ const props = [...type.props];
658
+ return [
659
+ D_OBJECT,
660
+ props.map(([key]) => key),
661
+ props.map(([, prop]) => site(prop))
662
+ ];
663
+ }
664
+ case "array": return [D_ARRAY, site(type.of)];
665
+ case "union":
666
+ case "intersection":
667
+ case "tuple": return [ITEMS_KIND_CODES[type.kind], type.items.map(site)];
668
+ default: return [D_UNKNOWN, String(type.kind)];
669
+ }
670
+ }
671
+ function site(node) {
672
+ const type = node.type;
673
+ const marker = classify?.(type);
674
+ const optional = !marker || marker === "ext" ? node.optional ? 1 : 0 : 0;
675
+ let d;
676
+ let keys = {
677
+ mask: 0,
678
+ shape: ""
679
+ };
680
+ if (marker === "interp") d = INTERP;
681
+ else if (marker === "ext") {
682
+ d = EXT;
683
+ keys = readKeys(node.metadata, siteBits(void 0, optional === 1), reader);
684
+ } else {
685
+ d = index.get(type) ?? -1;
686
+ if (d < 0) {
687
+ d = defs.length;
688
+ defs.push([]);
689
+ index.set(type, d);
690
+ defs[d] = describeDef(type);
691
+ }
692
+ keys = readKeys(node.metadata, siteBits(type, optional === 1), reader);
693
+ }
694
+ const result = [
695
+ optional,
696
+ keys.mask,
697
+ d,
698
+ keys.shape,
699
+ slots
700
+ ];
701
+ slots += siteSlotCount(result);
702
+ return result;
703
+ }
704
+ return [
705
+ defs,
706
+ site(root),
707
+ slots
708
+ ];
709
+ }
710
+ /** JS source of a layout literal (plain arrays, strings and numbers incl. NaN / ±Infinity / -0). */ function layoutSource(value) {
711
+ if (Array.isArray(value)) return `[${value.map(layoutSource).join(",")}]`;
712
+ return literalSource(value);
713
+ }
714
+ /** JS source of a primitive literal. */ function literalSource(value) {
715
+ if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
716
+ if (typeof value === "string") return JSON.stringify(value).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
717
+ if (value === void 0) return "undefined";
718
+ return JSON.stringify(value);
719
+ }
720
+
721
+ //#endregion
722
+ //#region packages/typescript/src/runtime/compiled-check/emit.ts
723
+ /**
724
+ * Emits the JS source of a compiled validator check factory from its layout.
725
+ *
726
+ * Build-time only (the renderer, and test code): the runtime never generates code. The
727
+ * emitted factory `(K, H) => check` mirrors the interpreted pre-check
728
+ * (validator-fast-check.ts) node for node — the same checks with the same PASS (1) /
729
+ * FAIL (0) / BAIL (2) contract — specialised to the layout: one function per object type
730
+ * def and per def that closes a reference cycle, everything else inlined.
731
+ *
732
+ * Generated code conventions:
733
+ * - Every function is `(v, f, o)`: the value, the flags (TOP, IN_UNION and option bits —
734
+ * see `optionFlags`) and the validator options (passed on to interpreted sub-checks).
735
+ * - A FAIL statement always leaves the current check: `return 0` outside unions; inside a
736
+ * union (where failures must visit everything the walk would) it records the failure and
737
+ * jumps past the failed node. `q` (`IN_UNION` unset) picks between the two when only the
738
+ * runtime flags tell. BAIL is always `return 2`.
739
+ * - Annotation values are closure constants `k<slot>` read from `K` once per bind.
740
+ */ function _define_property$2(obj, key, value) {
741
+ if (key in obj) Object.defineProperty(obj, key, {
742
+ value,
743
+ enumerable: true,
744
+ configurable: true,
745
+ writable: true
746
+ });
747
+ else obj[key] = value;
748
+ return obj;
749
+ }
750
+ const ROOT_CTX = {
751
+ fail: "return 0",
752
+ inUnionFail: "return 0",
753
+ union: false,
754
+ clearTop: false
755
+ };
756
+ /** Factory-level helpers (see `TCompiledHelpers`), in declaration order. */ const HELPERS = [
757
+ ["pk", /\bpk\./],
758
+ ["ho", /\bho\.call\(/],
759
+ ["dec", /\bdec\.test\(/],
760
+ ["rn", /\brn\(/]
761
+ ];
762
+ /** Source of the check factory `(K, H) => check` of `layout`. */ function emitCheckFactory(layout) {
763
+ return new CheckEmitter(layout).emit();
764
+ }
765
+ let CheckEmitter = class CheckEmitter {
766
+ emit() {
767
+ const body = [];
768
+ for (let d = 0; d < this.defs.length; d++) if (this.fn[d]) body.push(...this.defFunction(d));
769
+ const root = this.layout[1];
770
+ const rootDef = root[2] >= 0 ? this.defs[root[2]][0] : -1;
771
+ 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]}`);
772
+ else {
773
+ body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
774
+ body.push("return r");
775
+ }
776
+ const code = body.join("\n");
777
+ const head = [];
778
+ const helpers = HELPERS.filter(([, use]) => use.test(code)).map(([h]) => `${h} = H.${h}`);
779
+ if (helpers.length > 0) head.push(`const ${helpers.join(", ")}`);
780
+ 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);
781
+ for (let i = 0; i < slots.length; i += 16) head.push(`const ${slots.slice(i, i + 16).map((k) => `k${k} = K[${k}]`).join(", ")}`);
782
+ return [
783
+ "(K, H) => {",
784
+ ...indent([...head, ...body]),
785
+ "}"
786
+ ].join("\n");
787
+ }
788
+ /**
789
+ * Object defs get a function each; so does every def a reference cycle passes through
790
+ * (each back-edge target of a DFS), which keeps inlining finite.
791
+ */ functionDefs() {
792
+ const defs = this.defs;
793
+ const fn = defs.map((def) => def[0] === D_OBJECT || def[0] === D_OBJECT_PATTERNS);
794
+ const state = Array.from({ length: defs.length }).fill(0);
795
+ const dfs = (d) => {
796
+ state[d] = 1;
797
+ for (const site of childSites(defs[d])) {
798
+ const c = site[2];
799
+ if (c < 0) continue;
800
+ if (state[c] === 1) fn[c] = true;
801
+ else if (state[c] === 0) dfs(c);
802
+ }
803
+ state[d] = 2;
804
+ };
805
+ for (let d = 0; d < defs.length; d++) if (state[d] === 0) dfs(d);
806
+ return fn;
807
+ }
808
+ next(prefix) {
809
+ return `${prefix}${this.uid++}`;
810
+ }
811
+ /** A check function `name(v, f, o)` declaring the `q` / `t` locals its body uses. */ fnLines(name, body) {
812
+ const lines = body();
813
+ const code = lines.join("\n");
814
+ const locals = [];
815
+ if (code.includes("if (q) return 0")) locals.push(`const q = (f & ${F_IN_UNION}) === 0`);
816
+ if (/\bt = /.test(code)) locals.push("let t");
817
+ return [
818
+ `function ${name}(v, f, o) {`,
819
+ ...indent([...locals, ...lines]),
820
+ "}"
821
+ ];
822
+ }
823
+ defFunction(d) {
824
+ const def = this.defs[d];
825
+ return this.fnLines(`d${d}`, () => {
826
+ switch (def[0]) {
827
+ case D_OBJECT: return this.objectBody(def);
828
+ case D_OBJECT_PATTERNS: return [`if (${notObject("v")}) return 0`, "return 2"];
829
+ case D_ARRAY: return [...this.items(def[1], "v", ROOT_CTX), "return 1"];
830
+ case D_UNION: return [...this.unionBranches(def[1], "v", false, (item) => [`return ${choose(this.literalExpr(item), "3", "1")}`]), "return 0"];
831
+ case D_TUPLE: return [...this.tuple(def[1], "v", ROOT_CTX), "return 1"];
832
+ case D_INTERSECTION: return [...def[1].flatMap((item) => this.site(item, "v", ROOT_CTX)), "return 1"];
833
+ default: return ["return 2"];
834
+ }
835
+ });
836
+ }
837
+ /** Mirrors `fastCheckObject` (+ `pendStrips` / `hasUnknownKey`). */ objectBody(def) {
838
+ const sites = def[2];
839
+ const props = def[1].map((key, i) => ({
840
+ key,
841
+ site: sites[i]
842
+ })).filter((p) => !this.isPhantom(p.site));
843
+ const lines = [`if (${notObject("v")}) return 0`, "if (pk.length !== 0) return 2"];
844
+ if (props.some((p) => p.site[0] === 0 || p.site[2] === INTERP)) {
845
+ const top = F_PARTIAL_TOP | F_TOP;
846
+ lines.push(`const sk = (f & ${F_PARTIAL_DEEP}) !== 0 || (f & ${top}) === ${top}`);
847
+ }
848
+ if (props.length > 0) lines.push("let r = 1");
849
+ for (const { key, site } of props) {
850
+ const p = this.next("P");
851
+ const x = this.next("x");
852
+ const access = validIdentifier.test(key) ? `v.${key}` : `v[${literalSource(key)}]`;
853
+ lines.push(`${p}: {`, ` const ${x} = ${access}`);
854
+ if (site[0] === 0 || site[2] === INTERP) lines.push(` if (${x} === undefined && sk) break ${p}`);
855
+ const ctx = recordingCtx(`r = 0; break ${p}`, false, true);
856
+ lines.push(...indent(this.site(site, x, ctx)), "}");
857
+ }
858
+ if (props.length > 0) lines.push("if (r === 0) return 0");
859
+ const known = props.map((p) => p.key);
860
+ const onUnknown = `{ if ((f & ${F_ERROR}) !== 0) return 0; if ((f & ${F_TOP}) === 0) return 2; pk.push(k) }`;
861
+ const scan = known.length === 0 ? [`for (const k in v) if (ho.call(v, k)) ${onUnknown}`] : [
862
+ "for (const k in v) {",
863
+ " switch (k) {",
864
+ ...known.map((key) => ` case ${literalSource(key)}:`),
865
+ " break",
866
+ " default:",
867
+ ` if (ho.call(v, k)) ${onUnknown}`,
868
+ " }",
869
+ "}"
870
+ ];
871
+ lines.push(`if ((f & ${F_ERROR | F_STRIP}) !== 0) {`, ...indent(scan), "}", "return 1");
872
+ return lines;
873
+ }
874
+ isPhantom(site) {
875
+ const d = site[2];
876
+ return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "phantom";
877
+ }
878
+ isLiteralDef(d) {
879
+ return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d].length > 2;
880
+ }
881
+ /** A required `never` union branch: it can never match (skipped). */ isNever(site) {
882
+ const d = site[2];
883
+ return site[0] === 0 && d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "never" && !this.isLiteralDef(d);
884
+ }
885
+ /** Expression telling whether the site's type is a literal (`'true'` / `'false'` when known). */ literalExpr(site) {
886
+ const [, , d, , slot] = site;
887
+ if (d >= 0) return this.isLiteralDef(d) ? "true" : "false";
888
+ return `k${d === INTERP ? slot + 1 : slot + (hasRejectSlot(site) ? 1 : 0) + 1}`;
889
+ }
890
+ /** Mirrors `fastCheck` for one node holding `x`. */ site(site, x, ctx) {
891
+ const [optional, mask, d, shape, slot] = site;
892
+ if (d === INTERP) return this.call(`k${slot}`, x, ctx);
893
+ let at = slot;
894
+ const rej = hasRejectSlot(site) ? at++ : -1;
895
+ const body = d === EXT ? this.call(`k${at}`, x, ctx) : this.def(d, mask, shape, at, x, ctx);
896
+ if (!optional) return body;
897
+ if (rej < 0) return body.length > 0 ? [
898
+ `if (${x} !== undefined && ${x} !== null) {`,
899
+ ...indent(body),
900
+ "}"
901
+ ] : [];
902
+ const lines = [`if (${x} === undefined || ${x} === null) {`, ` if (${x} === null && rn(k${rej})) ${ctx.fail}`];
903
+ if (body.length > 0) lines.push("} else {", ...indent(body));
904
+ lines.push("}");
905
+ return lines;
906
+ }
907
+ /** Calls a check function returning 0 / 1 / 2. */ call(fn, x, ctx) {
908
+ this.calls++;
909
+ return [`t = ${fn}(${x}, ${flags(ctx)}, o)`, `if (t !== 1) { if (t === 2) return 2; ${unblock(ctx.fail)} }`];
910
+ }
911
+ def(d, mask, shape, at, x, ctx) {
912
+ const def = this.defs[d];
913
+ const kind = def[0];
914
+ if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) return this.call(`d${d}`, x, ctx);
915
+ switch (kind) {
916
+ case D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
917
+ case D_ARRAY: return [
918
+ `if (!Array.isArray(${x})) ${ctx.fail}`,
919
+ ...this.arrayConstraints(mask, keySlots(mask, shape, at), x, ctx.fail),
920
+ ...this.fn[d] ? this.call(`d${d}`, x, ctx) : this.items(def[1], x, ctx)
921
+ ];
922
+ case D_UNION: {
923
+ const constraints = this.unionConstraints(mask, shape, at, x, ctx.fail);
924
+ if (!this.fn[d]) return this.union(def[1], {
925
+ mask,
926
+ shape,
927
+ at
928
+ }, constraints, x, ctx);
929
+ this.calls++;
930
+ const lines = [
931
+ `t = d${d}(${x}, ${flags(ctx)}, o)`,
932
+ "if (t === 2) return 2",
933
+ `if (t === 0) ${ctx.fail}`
934
+ ];
935
+ if (constraints.length > 0) lines.push("if (t === 1) {", ...indent(constraints), "}");
936
+ return lines;
937
+ }
938
+ case D_INTERSECTION: return def[1].flatMap((item) => this.site(item, x, ctx));
939
+ case D_TUPLE: return this.tuple(def[1], x, ctx);
940
+ default: return ["return 2"];
941
+ }
942
+ }
943
+ /** Mirrors `fastCheckFinal` + the string / number / boolean constraints. */ final(def, mask, shape, at, x, fail) {
944
+ const designType = def[1];
945
+ if (designType === "phantom") return [];
946
+ if (def.length > 2) return [`if (${x} !== ${literalSource(def[2])}) ${fail}`];
947
+ const ks = keySlots(mask, shape, at);
948
+ switch (designType) {
949
+ case "string": return this.stringChecks(mask, shape, ks, x, fail, [`typeof ${x} !== "string"`]);
950
+ case "number": return this.numberChecks(mask, ks, x, fail, [`typeof ${x} !== "number"`, `!Number.isFinite(${x})`]);
951
+ case "boolean": {
952
+ const conds = [`typeof ${x} !== "boolean"`];
953
+ if (mask & B_REQUIRED) conds.push(`${x} !== true`);
954
+ return [`if (${conds.join(" || ")}) ${fail}`];
955
+ }
956
+ case "any": return [];
957
+ case "never": return [fail];
958
+ case "undefined": return [`if (${x} !== undefined) ${fail}`];
959
+ case "null": return [`if (${x} !== null) ${fail}`];
960
+ case "decimal": return [`if (typeof ${x} !== "string" || !dec.test(${x})) ${fail}`];
961
+ default: return ["return 2"];
962
+ }
963
+ }
964
+ stringChecks(mask, shape, ks, x, fail, conds) {
965
+ if (mask & B_REQUIRED) conds.push(`${x}.trim().length === 0`);
966
+ if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
967
+ if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
968
+ const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
969
+ let p = 0;
970
+ for (const c of shape) if (c === "n") lines.push(`if (!k${ks.patterns[p++]}.test(${x})) ${fail}`);
971
+ else if (c === "s") {
972
+ lines.push("return 2");
973
+ break;
974
+ }
975
+ return lines;
976
+ }
977
+ numberChecks(mask, ks, x, fail, conds) {
978
+ if (mask & B_INT) conds.push(`${x} % 1 !== 0`);
979
+ if (ks.min >= 0) conds.push(`${x} < k${ks.min}`);
980
+ if (ks.max >= 0) conds.push(`${x} > k${ks.max}`);
981
+ if (ks.exMin >= 0) conds.push(`${x} <= k${ks.exMin}`);
982
+ if (ks.exMax >= 0) conds.push(`${x} >= k${ks.exMax}`);
983
+ return conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
984
+ }
985
+ /** Array length constraints; `uniqueItems` (duplicate detection) is left to the walk. */ arrayConstraints(mask, ks, x, fail) {
986
+ const conds = [];
987
+ if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
988
+ if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
989
+ const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
990
+ if (mask & B_UNIQUE) lines.push("return 2");
991
+ return lines;
992
+ }
993
+ /** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
994
+ const ks = keySlots(mask, shape, at);
995
+ const branches = [];
996
+ if (mask & STRING_BITS) branches.push([`typeof ${x} === "string"`, this.stringChecks(mask, shape, ks, x, fail, [])]);
997
+ if (mask & NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
998
+ if (mask & B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
999
+ if (mask & ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
1000
+ const lines = [];
1001
+ branches.forEach(([cond, body], i) => {
1002
+ lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
1003
+ });
1004
+ if (lines.length > 0) lines.push("}");
1005
+ return lines;
1006
+ }
1007
+ /**
1008
+ * The union-level constraints after a non-literal branch passed. A required (non-optional)
1009
+ * branch of a known primitive / array type fixes `typeof`: only that part applies.
1010
+ */ branchConstraints(item, { mask, shape, at }, constraints, x, fail) {
1011
+ const [optional, , d] = item;
1012
+ const def = this.defs[d];
1013
+ if (optional) return constraints;
1014
+ const ks = keySlots(mask, shape, at);
1015
+ if (def[0] === D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
1016
+ if (def[0] !== D_FINAL) return constraints;
1017
+ switch (def[1]) {
1018
+ case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
1019
+ case "number": return this.numberChecks(mask, ks, x, fail, []);
1020
+ case "boolean": return mask & B_REQUIRED ? [`if (${x} !== true) ${fail}`] : [];
1021
+ case "null":
1022
+ case "undefined": return [];
1023
+ default: return constraints;
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Mirrors the `fastCheck` union case: branches in declared order, each a labelled block a
1028
+ * FAIL breaks out of; `onMatch` ends a passing branch.
1029
+ */ unionBranches(items, x, clearTop, onMatch) {
1030
+ const lines = [];
1031
+ for (const item of items) {
1032
+ if (this.isNever(item)) continue;
1033
+ const b = this.next("B");
1034
+ const calls = this.calls;
1035
+ const fail = `break ${b}`;
1036
+ const body = this.site(item, x, {
1037
+ fail,
1038
+ inUnionFail: fail,
1039
+ union: true,
1040
+ clearTop
1041
+ });
1042
+ lines.push(`${b}: {`, ...indent([...body, ...onMatch(item)]), "}");
1043
+ if (this.calls !== calls) lines.push("if (pk.length !== 0) return 2");
1044
+ }
1045
+ return lines;
1046
+ }
1047
+ /** An inline union: the first matching branch passes after the union-level constraints. */ union(items, keys, constraints, x, ctx) {
1048
+ const u = this.next("U");
1049
+ const branches = this.unionBranches(items, x, ctx.clearTop, (item) => {
1050
+ const lines = [];
1051
+ const literal = constraints.length > 0 ? this.literalExpr(item) : "true";
1052
+ if (literal === "false") lines.push(...this.branchConstraints(item, keys, constraints, x, ctx.fail));
1053
+ else if (literal !== "true") lines.push(`if (!${literal}) {`, ...indent(constraints), "}");
1054
+ lines.push(`break ${u}`);
1055
+ return lines;
1056
+ });
1057
+ return [
1058
+ `${u}: {`,
1059
+ ...indent([...branches, ctx.fail]),
1060
+ "}"
1061
+ ];
1062
+ }
1063
+ /** Mirrors `checkItems`: every item is visited inside a union (BAIL beats FAIL). */ items(of, x, ctx) {
1064
+ const y = this.next("y");
1065
+ const a = this.next("a");
1066
+ const body = this.site(of, y, recordingCtx(`${a} = 0; continue`, ctx.union, true));
1067
+ if (body.length === 0) return [`for (const ${y} of ${x}) {}`];
1068
+ return [
1069
+ `let ${a} = 1`,
1070
+ `for (const ${y} of ${x}) {`,
1071
+ ...indent(body),
1072
+ "}",
1073
+ `if (${a} === 0) ${ctx.inUnionFail}`
1074
+ ];
1075
+ }
1076
+ /** Mirrors the `fastCheck` tuple case: stops at the first non-passing item. */ tuple(items, x, ctx) {
1077
+ const lines = [`if (!Array.isArray(${x}) || ${x}.length !== ${items.length}) ${ctx.fail}`];
1078
+ items.forEach((item, i) => {
1079
+ const e = this.next("e");
1080
+ lines.push(`const ${e} = ${x}[${i}]`, ...this.site(item, e, {
1081
+ ...ctx,
1082
+ clearTop: true
1083
+ }));
1084
+ });
1085
+ return lines;
1086
+ }
1087
+ constructor(layout) {
1088
+ _define_property$2(this, "layout", void 0);
1089
+ _define_property$2(this, "defs", void 0);
1090
+ /** Def index → emitted as its own function. */ _define_property$2(this, "fn", void 0);
1091
+ _define_property$2(this, "uid", void 0);
1092
+ /** Calls emitted so far (a union branch without calls cannot record strips). */ _define_property$2(this, "calls", void 0);
1093
+ this.layout = layout;
1094
+ this.uid = 0;
1095
+ this.calls = 0;
1096
+ this.defs = layout[0];
1097
+ this.fn = this.functionDefs();
1098
+ }
1099
+ };
1100
+ /**
1101
+ * Context of a node whose failure is recorded (`record`: e.g. `r = 0; break P1`) when
1102
+ * inside a union and leaves the check otherwise.
1103
+ */ function recordingCtx(record, union, clearTop) {
1104
+ const inUnionFail = `{ ${record} }`;
1105
+ return {
1106
+ fail: union ? inUnionFail : `{ if (q) return 0; ${record} }`,
1107
+ inUnionFail,
1108
+ union,
1109
+ clearTop
1110
+ };
1111
+ }
1112
+ /** Flags passed to a callee. */ function flags(ctx) {
1113
+ if (ctx.clearTop) return ctx.union ? `(f & ${~F_TOP}) | ${F_IN_UNION}` : `f & ${~F_TOP}`;
1114
+ return ctx.union ? `f | ${F_IN_UNION}` : "f";
1115
+ }
1116
+ /** The statements of a `{ … }` block statement (other statements as they are). */ function unblock(statement) {
1117
+ return statement.startsWith("{ ") && statement.endsWith(" }") ? statement.slice(2, -2) : statement;
1118
+ }
1119
+ /** `cond ? a : b` folded when `cond` is a constant. */ function choose(cond, a, b) {
1120
+ return cond === "true" ? a : cond === "false" ? b : `${cond} ? ${a} : ${b}`;
1121
+ }
1122
+ function notObject(x) {
1123
+ return `typeof ${x} !== "object" || ${x} === null || Array.isArray(${x})`;
1124
+ }
1125
+ function indent(lines, n = 2) {
1126
+ const pad = " ".repeat(n);
1127
+ return lines.map((l) => pad + l);
1128
+ }
1129
+
1130
+ //#endregion
1131
+ //#region packages/typescript/src/codegen/validation-model.ts
1132
+ function _define_property$1(obj, key, value) {
1133
+ if (key in obj) Object.defineProperty(obj, key, {
1134
+ value,
1135
+ enumerable: true,
1136
+ configurable: true,
1137
+ writable: true
1138
+ });
1139
+ else obj[key] = value;
1140
+ return obj;
1141
+ }
1142
+ /** Kinds of the opaque types standing for another module's types (see {@link classifyType}). */ const EXT_KIND = "#ext";
1143
+ const INTERP_KIND = "#interp";
1144
+ /**
1145
+ * How the layout treats a model type: `'ext'` — another module's type referenced as a
1146
+ * whole (also an alias / prop clone of one: `cloneTypeDef` keeps the kind); `'interp'` — a
1147
+ * chained reference into another module's type, only known at runtime.
1148
+ */ function classifyType(type) {
1149
+ const kind = type?.kind;
1150
+ return kind === EXT_KIND ? "ext" : kind === INTERP_KIND ? "interp" : void 0;
1151
+ }
1152
+ /**
1153
+ * Build-time model of the runtime type trees a generated `.as.js` module builds, used to
1154
+ * compile validator checks (`compileValidators`).
1155
+ *
1156
+ * The renderer drives it in lockstep with the builder chains it emits, through the real
1157
+ * runtime builder (`defineAnnotatedType`, `annotate`, `cloneRefProp`), so the model has
1158
+ * the same structure, the same type-def sharing (by identity) and the same validator
1159
+ * annotations as the module after its initialisation. Only the annotations the validator
1160
+ * pre-check reads are recorded. Types of other modules are opaque markers: a reference to
1161
+ * one (also an alias or a cloned prop of one) compiles to a cross-module site, bound at
1162
+ * runtime to the referenced class's own compiled check (see compiled-check/registry.ts).
1163
+ *
1164
+ * Anything the model cannot follow marks it broken; nothing is compiled then. A model that
1165
+ * nevertheless diverges from the runtime only costs speed: the runtime bind detects it and
1166
+ * the interpreted pre-check runs.
1167
+ */ var ValidationModel = class {
1168
+ /** Runs a model step; a throw marks the model broken. */ run(step) {
1169
+ if (this.broken) return;
1170
+ try {
1171
+ return step();
1172
+ } catch {
1173
+ this.broken = true;
1174
+ return;
1175
+ }
1176
+ }
1177
+ /** Declares a generated class (`static type = {}; static metadata = new Map()`). */ declare(name) {
1178
+ this.classes.set(name, {
1179
+ __is_atscript_annotated_type: true,
1180
+ type: {},
1181
+ metadata: /* @__PURE__ */ new Map(),
1182
+ name
1183
+ });
1184
+ }
1185
+ /** The model of a class declared in this module (anything else: the emitted code throws). */ classBase(name) {
1186
+ const cls = this.classes.get(name);
1187
+ if (!cls) throw new Error(`${name} is not a class of this module`);
1188
+ return cls;
1189
+ }
1190
+ /** `$(kind, name?)`. */ handle(kind, name) {
1191
+ return this.run(() => defineAnnotatedType(kind, name === void 0 ? void 0 : this.classBase(name)));
1192
+ }
1193
+ /** `.refTo(Local)` / `.refTo(() => Imported)` (with an optional chain). */ refTo(handle, name, imported, chain) {
1194
+ this.run(() => {
1195
+ if (!handle) throw new Error("no chain");
1196
+ if (imported) {
1197
+ const marker = this.marker(name, chain ? INTERP_KIND : EXT_KIND);
1198
+ handle.refTo(() => marker, chain);
1199
+ } else handle.refTo(this.classBase(name), chain);
1200
+ });
1201
+ }
1202
+ /** The opaque stand-in of another module's type `name`. */ marker(name, kind) {
1203
+ const key = `${name}${kind}`;
1204
+ let marker = this.markers.get(key);
1205
+ if (!marker) {
1206
+ marker = {
1207
+ __is_atscript_annotated_type: true,
1208
+ type: { kind },
1209
+ metadata: /* @__PURE__ */ new Map()
1210
+ };
1211
+ this.markers.set(key, marker);
1212
+ }
1213
+ return marker;
1214
+ }
1215
+ /** `.annotate(key, value, multiple)` on the current chain (validator keys only). */ annotate(key, value, multiple) {
1216
+ if (!isValidatorKey(key)) return;
1217
+ this.run(() => {
1218
+ if (!this.current) throw new Error("no chain");
1219
+ this.current.annotate(key, value, multiple);
1220
+ });
1221
+ }
1222
+ /** The node a mutating-annotate accessor (`Name.type.props.get("a")?…`) points at. */ resolve(name, steps) {
1223
+ let cur = this.classes.get(name);
1224
+ for (const step of steps) {
1225
+ if (cur === void 0 || cur === null) return;
1226
+ if (step === "type") {
1227
+ cur = cur.type;
1228
+ if (classifyType(cur) !== void 0) return;
1229
+ } else if (step[0] === "props") cur = cur.props?.get(step[1]);
1230
+ else cur = cur.items?.[step[1]];
1231
+ }
1232
+ return cur;
1233
+ }
1234
+ /** `$c(<accessor>, "prop")`. */ cloneProp(name, steps, prop) {
1235
+ this.run(() => {
1236
+ const parent = this.resolve(name, steps);
1237
+ if (parent) cloneRefProp(parent, prop);
1238
+ });
1239
+ }
1240
+ /** `<accessor>.metadata.delete(key)`. */ deleteAnnotation(name, steps, key) {
1241
+ this.run(() => {
1242
+ this.resolve(name, steps)?.metadata?.delete(key);
1243
+ });
1244
+ }
1245
+ /** `$a(<accessor>.metadata, key, value, multiple)`. */ mutateAnnotation(name, steps, key, value, multiple) {
1246
+ if (!isValidatorKey(key)) return;
1247
+ this.run(() => {
1248
+ annotate(this.resolve(name, steps)?.metadata, key, value, multiple);
1249
+ });
1250
+ }
1251
+ /**
1252
+ * `$cv(Name, version, layout, factory)` for class `name`, or `undefined` when it cannot be
1253
+ * compiled (its root type is only known at runtime, or the model is broken).
1254
+ */ registration(name) {
1255
+ if (this.broken) return;
1256
+ const cls = this.classes.get(name);
1257
+ if (!cls) return;
1258
+ let layout;
1259
+ try {
1260
+ layout = buildLayout(cls, { regex: getRegex }, classifyType);
1261
+ } catch {
1262
+ return;
1263
+ }
1264
+ const root = layout[1][2];
1265
+ if (root === INTERP || root >= 0 && layout[0][root][0] === D_UNKNOWN) return;
1266
+ return `$cv(${name}, ${LAYOUT_VERSION}, ${layoutSource(layout)}, ${emitCheckFactory(layout)})`;
1267
+ }
1268
+ constructor() {
1269
+ /** The model could not follow the emitted code: compile nothing. */ _define_property$1(this, "broken", false);
1270
+ /** Handle of the chain being emitted (the target of `.annotate(…)` lines). */ _define_property$1(this, "current", void 0);
1271
+ _define_property$1(this, "classes", /* @__PURE__ */ new Map());
1272
+ _define_property$1(this, "markers", /* @__PURE__ */ new Map());
1273
+ }
1274
+ };
1275
+ /**
1276
+ * Runtime value of an annotation argument the emitted code writes as a raw expression
1277
+ * (`true`, `5`, `-1.5`, …). Anything else is opaque (truthy and not a number): the bind
1278
+ * compares only presence / truthiness and reads the real values at runtime.
1279
+ */ function rawLiteralValue(text) {
1280
+ switch (text) {
1281
+ case "true": return true;
1282
+ case "false": return false;
1283
+ case "null": return null;
1284
+ case "undefined": return;
1285
+ default: {
1286
+ const n = Number(text);
1287
+ return text.trim() !== "" && !Number.isNaN(n) ? n : { opaque: text };
1288
+ }
1289
+ }
1290
+ }
1291
+
636
1292
  //#endregion
637
1293
  //#region packages/typescript/src/codegen/js-renderer.ts
638
1294
  function _define_property(obj, key, value) {
@@ -658,7 +1314,24 @@ const QUERY_OP_MAP = {
658
1314
  "exists": "$exists",
659
1315
  "not exists": "$exists"
660
1316
  };
1317
+ /** Value field of each number-bound annotation's object form. */ const NUMBER_BOUND_FIELDS = {
1318
+ "expect.min": "minValue",
1319
+ "expect.max": "maxValue",
1320
+ "expect.exclusiveMin": "exclusiveMinValue",
1321
+ "expect.exclusiveMax": "exclusiveMaxValue"
1322
+ };
661
1323
  const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
1324
+ /** The runtime value of an annotation argument (see `JsRenderer.computeAnnotationValue`). */ function runtimeArg(type, token) {
1325
+ return type === "string" || type === void 0 && token.type === "text" ? token.text : rawLiteralValue(token.text);
1326
+ }
1327
+ /**
1328
+ * The runtime accessor of a mutating-annotate path: `Name` followed by the steps
1329
+ * (`.type`, `.props.get("a")?`, `.items[0]`).
1330
+ */ function accessorPath(targetName, steps) {
1331
+ let path = targetName;
1332
+ for (const step of steps) path += step === "type" ? ".type" : step[0] === "props" ? `.props.get("${escapeQuotes(step[1])}")?` : `.items[${step[1]}]`;
1333
+ return path;
1334
+ }
662
1335
  var JsRenderer = class extends BaseRenderer {
663
1336
  /**
664
1337
  * Relative imports get the configured `moduleExtension`; bare specifiers
@@ -837,6 +1510,7 @@ var JsRenderer = class extends BaseRenderer {
837
1510
  if (jsonSchemaMode === "lazy") imports.push("buildJsonSchema as $$");
838
1511
  if (this.opts?.exampleData) imports.push("createDataFromAnnotatedType as $e");
839
1512
  if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
1513
+ if (this.model) imports.push("registerCompiledCheck as $cv");
840
1514
  this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
841
1515
  this.computeSynthesizedImports();
842
1516
  this.writeln(SYNTH_IMPORTS_MARKER);
@@ -884,7 +1558,7 @@ var JsRenderer = class extends BaseRenderer {
884
1558
  if (isInterface(def)) if (def.hasExtends) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
885
1559
  else def = def.getDefinition() || def;
886
1560
  this._adHocAnnotations = this.buildAdHocMap([annotateNode]);
887
- this.annotateType(def, node.id);
1561
+ this.modelClass(node.id, () => this.annotateType(def, node.id));
888
1562
  this._adHocAnnotations = null;
889
1563
  this.indent();
890
1564
  this.defineMetadataForAnnotateAlias(annotateNode);
@@ -898,13 +1572,38 @@ var JsRenderer = class extends BaseRenderer {
898
1572
  const resolved = this.doc.resolveInterfaceExtends(node);
899
1573
  if (resolved) def = resolved;
900
1574
  }
901
- this.annotateType(def, node.id);
1575
+ this.modelClass(node.id, () => this.annotateType(def, node.id));
902
1576
  this.indent().defineMetadata(node).unindent();
903
1577
  this.writeln();
904
1578
  }
1579
+ this.renderCompiledChecks();
905
1580
  this.writeln("// prettier-ignore-end");
906
1581
  super.post();
907
1582
  }
1583
+ /**
1584
+ * Emits class `name`'s chain; the validation model follows it (its handle stays the current
1585
+ * chain, the target of the class-level annotations emitted next).
1586
+ */ modelClass(name, emit) {
1587
+ if (this.model) this.model.current = void 0;
1588
+ emit();
1589
+ if (this.model?.current) this.modelClasses.push(name);
1590
+ }
1591
+ /**
1592
+ * `compileValidators`: one `$cv(Class, …)` registration per class, after every chain and
1593
+ * mutating annotate of the module ran (the compiled check binds on first use).
1594
+ */ renderCompiledChecks() {
1595
+ if (!this.model) return;
1596
+ const registrations = [];
1597
+ for (const name of this.modelClasses) {
1598
+ const registration = this.model.registration(name);
1599
+ if (registration) registrations.push(registration);
1600
+ }
1601
+ if (registrations.length > 0) {
1602
+ this.writeln("// Compiled validator checks");
1603
+ for (const registration of registrations) for (const line of registration.split("\n")) this.writeln(line);
1604
+ this.writeln();
1605
+ }
1606
+ }
908
1607
  renderClassStatics(node) {
909
1608
  this.writeln("static __is_atscript_annotated_type = true");
910
1609
  this.writeln("static type = {}");
@@ -935,6 +1634,7 @@ var JsRenderer = class extends BaseRenderer {
935
1634
  this.write(exported ? "export " : "");
936
1635
  this.write(`class ${node.id} `);
937
1636
  this.blockln("{}");
1637
+ this.model?.declare(node.id);
938
1638
  this.renderClassStatics(node);
939
1639
  this.popln();
940
1640
  this.postAnnotate.push(node);
@@ -984,23 +1684,63 @@ var JsRenderer = class extends BaseRenderer {
984
1684
  if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
985
1685
  }
986
1686
  toAnnotatedType(node) {
987
- return this.toAnnotatedHandle(node).$type;
1687
+ return node?.entity === "interface" || node?.entity === "type" ? this.declType(node) : this.toAnnotatedHandle(node).$type;
1688
+ }
1689
+ /**
1690
+ * The build-time runtime type of an interface / type declaration (see `_declTypes`);
1691
+ * `doc` is the document that declares it (where an alias's target name resolves).
1692
+ */ declType(node, doc = this.doc) {
1693
+ const known = this._declTypes.get(node);
1694
+ if (known) return known;
1695
+ let def = node.getDefinition();
1696
+ if (isInterface(node) && node.hasExtends) {
1697
+ const resolved = this.doc.resolveInterfaceExtends(node);
1698
+ if (resolved) def = resolved;
1699
+ }
1700
+ const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
1701
+ let handle;
1702
+ if (def && isRef(def)) {
1703
+ const ref = def;
1704
+ const decl = doc.unwindType(ref.id, ref.chain)?.def;
1705
+ const target = this.refTarget(ref, decl, doc);
1706
+ handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
1707
+ } else {
1708
+ const base = {
1709
+ __is_atscript_annotated_type: true,
1710
+ type: {},
1711
+ metadata: /* @__PURE__ */ new Map(),
1712
+ id: typeId
1713
+ };
1714
+ this._declTypes.set(node, base);
1715
+ if (def) this._declTypes.set(def, base);
1716
+ handle = this.toAnnotatedHandle(def, true, base);
1717
+ }
1718
+ this._declTypes.set(node, handle.$type);
1719
+ if (typeId) handle.id(typeId);
1720
+ this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1721
+ return handle.$type;
988
1722
  }
989
- toAnnotatedHandle(node, skipAnnotations = false) {
990
- if (!node) return defineAnnotatedType();
1723
+ /**
1724
+ * The declaration type a reference points at (see `declType`), or `undefined` when it is
1725
+ * not a declaration (a chained reference into a prop, an unresolved name). A plain
1726
+ * reference to a type alias points at the alias itself (its own type and id, like the
1727
+ * runtime `$().refTo(Alias)`), not at what the alias unwinds to.
1728
+ */ refTarget(ref, decl, doc = this.doc) {
1729
+ if (!decl) return;
1730
+ const owner = ref.hasChain ? void 0 : this.resolveOwner(doc, ref.id);
1731
+ if (owner?.node?.entity === "type" || owner?.node?.entity === "interface") return this.declType(owner.node, owner.doc);
1732
+ const known = this._declTypes.get(decl);
1733
+ if (known) return known;
1734
+ return isInterface(decl) ? this.declType(decl) : void 0;
1735
+ }
1736
+ /**
1737
+ * The build-time runtime type of an expression node; with `base`, built into that object
1738
+ * (a declaration's type, see `declType`).
1739
+ */ toAnnotatedHandle(node, skipAnnotations = false, base) {
1740
+ if (!node) return defineAnnotatedType(void 0, base);
991
1741
  switch (node.entity) {
992
1742
  case "interface":
993
- case "type": {
994
- let def = node.getDefinition();
995
- if (isInterface(node) && node.hasExtends) {
996
- const resolved = this.doc.resolveInterfaceExtends(node);
997
- if (resolved) def = resolved;
998
- }
999
- const handle = this.toAnnotatedHandle(def, true);
1000
- const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
1001
- if (typeId) handle.id(typeId);
1002
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1003
- }
1743
+ case "type": return defineAnnotatedType().refTo(this.declType(node));
1004
1744
  case "prop": {
1005
1745
  const prop = node;
1006
1746
  const def = prop.getDefinition();
@@ -1014,7 +1754,8 @@ var JsRenderer = class extends BaseRenderer {
1014
1754
  case "ref": {
1015
1755
  const ref = node;
1016
1756
  const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
1017
- const handle = this.toAnnotatedHandle(decl, true);
1757
+ const target = this.refTarget(ref, decl);
1758
+ const handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
1018
1759
  if (skipAnnotations) return handle;
1019
1760
  const own = this.doc.evalAnnotationsForNode(node);
1020
1761
  const referred = this.refTargetAnnotations(ref, decl);
@@ -1022,14 +1763,14 @@ var JsRenderer = class extends BaseRenderer {
1022
1763
  }
1023
1764
  case "primitive": {
1024
1765
  const prim = node;
1025
- const handle = defineAnnotatedType();
1766
+ const handle = defineAnnotatedType(void 0, base);
1026
1767
  handle.designType(prim.id === "never" ? "never" : prim.config.type);
1027
1768
  if (!skipAnnotations) this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1028
1769
  return handle;
1029
1770
  }
1030
1771
  case "const": {
1031
1772
  const c = node;
1032
- const handle = defineAnnotatedType();
1773
+ const handle = defineAnnotatedType(void 0, base);
1033
1774
  const t = c.token("identifier")?.type;
1034
1775
  handle.designType(t === "number" ? "number" : "string");
1035
1776
  handle.value(t === "number" ? Number(c.id) : c.id);
@@ -1037,7 +1778,7 @@ var JsRenderer = class extends BaseRenderer {
1037
1778
  }
1038
1779
  case "structure": {
1039
1780
  const struct = node;
1040
- const handle = defineAnnotatedType("object");
1781
+ const handle = defineAnnotatedType("object", base);
1041
1782
  for (const prop of Array.from(struct.props.values())) {
1042
1783
  const propHandle = this.toAnnotatedHandle(prop);
1043
1784
  const pattern = prop.token("identifier")?.pattern;
@@ -1048,24 +1789,24 @@ var JsRenderer = class extends BaseRenderer {
1048
1789
  }
1049
1790
  case "group": {
1050
1791
  const group = node;
1051
- const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection");
1792
+ const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection", base);
1052
1793
  for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1053
1794
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1054
1795
  }
1055
1796
  case "tuple": {
1056
1797
  const group = node;
1057
- const handle = defineAnnotatedType("tuple");
1798
+ const handle = defineAnnotatedType("tuple", base);
1058
1799
  for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1059
1800
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1060
1801
  }
1061
1802
  case "array": {
1062
1803
  const arr = node;
1063
- const handle = defineAnnotatedType("array");
1804
+ const handle = defineAnnotatedType("array", base);
1064
1805
  handle.of(this.toAnnotatedHandle(arr.getDefinition()).$type);
1065
1806
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1066
1807
  }
1067
1808
  default: {
1068
- const handle = defineAnnotatedType();
1809
+ const handle = defineAnnotatedType(void 0, base);
1069
1810
  return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1070
1811
  }
1071
1812
  }
@@ -1081,14 +1822,11 @@ var JsRenderer = class extends BaseRenderer {
1081
1822
  });
1082
1823
  break;
1083
1824
  case "expect.min":
1084
- if (a.args[0]) handle.annotate(a.name, {
1085
- minValue: Number(a.args[0].text),
1086
- message: a.args[1]?.text
1087
- });
1088
- break;
1089
1825
  case "expect.max":
1826
+ case "expect.exclusiveMin":
1827
+ case "expect.exclusiveMax":
1090
1828
  if (a.args[0]) handle.annotate(a.name, {
1091
- maxValue: Number(a.args[0].text),
1829
+ [NUMBER_BOUND_FIELDS[a.name]]: Number(a.args[0].text),
1092
1830
  message: a.args[1]?.text
1093
1831
  });
1094
1832
  break;
@@ -1140,8 +1878,10 @@ var JsRenderer = class extends BaseRenderer {
1140
1878
  node: synth.ownerNode
1141
1879
  } : this.resolveOwner(this.doc, ref.id);
1142
1880
  const refName = synth?.alias ?? ref.id;
1143
- const refExpr = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false) ? `() => ${refName}` : refName;
1881
+ const isImported = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false);
1882
+ const refExpr = isImported ? `() => ${refName}` : refName;
1144
1883
  this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().writeln(`.refTo(${refExpr}${chain})`);
1884
+ this.model?.refTo(this.modelHandle("", name), refName, isImported, ref.hasChain ? ref.chain.map((c) => c.text) : void 0);
1145
1885
  if (!ref.hasChain) {
1146
1886
  if (ownerDecl?.node) ownerDecl.doc.evalReferredAnnotations(ownerDecl.node)?.forEach((an) => {
1147
1887
  this.resolveAnnotationValue(ownerDecl.node, an);
@@ -1154,29 +1894,63 @@ var JsRenderer = class extends BaseRenderer {
1154
1894
  this.definePrimitive(node, name);
1155
1895
  return this;
1156
1896
  case "const":
1897
+ this.modelHandle("", name);
1157
1898
  this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().defineConst(node).unindent();
1158
1899
  return this;
1159
1900
  case "structure":
1901
+ this.modelHandle("object", name);
1160
1902
  this.writeln(`$("object"${name ? `, ${name}` : ""})`).indent().defineObject(node).unindent();
1161
1903
  return this;
1162
1904
  case "group":
1163
1905
  kind = node.op === "|" ? "union" : "intersection";
1906
+ this.modelHandle(kind, name);
1164
1907
  this.writeln(`$("${kind}"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1165
1908
  return this;
1166
1909
  case "tuple":
1910
+ this.modelHandle("tuple", name);
1167
1911
  this.writeln(`$("tuple"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1168
1912
  return this;
1169
1913
  case "array":
1914
+ this.modelHandle("array", name);
1170
1915
  this.writeln(`$("array"${name ? `, ${name}` : ""})`).indent().defineArray(node).unindent();
1171
1916
  return this;
1172
1917
  default: return this;
1173
1918
  }
1174
1919
  }
1920
+ /** `$(kind, name?)` in the validation model; it becomes the current chain. */ modelHandle(kind, name) {
1921
+ if (!this.model) return;
1922
+ const h = this.model.handle(kind, name);
1923
+ this.model.current = h;
1924
+ return h;
1925
+ }
1926
+ /**
1927
+ * The model handle of a nested chain (`emit` writes it and its annotations): `current`
1928
+ * is cleared first so a chain that emits nothing breaks the model instead of leaving a
1929
+ * stale handle, and restored to the parent chain afterwards.
1930
+ */ modelChild(emit) {
1931
+ if (!this.model) {
1932
+ emit();
1933
+ return;
1934
+ }
1935
+ const parent = this.model.current;
1936
+ this.model.current = void 0;
1937
+ emit();
1938
+ const child = this.model.current;
1939
+ this.model.current = parent;
1940
+ if (!child) this.model.broken = true;
1941
+ return child;
1942
+ }
1175
1943
  defineConst(node) {
1176
1944
  const t = node.token("identifier")?.type;
1177
1945
  const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
1178
1946
  this.writeln(`.designType("${escapeQuotes(designType)}")`);
1179
1947
  this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
1948
+ if (this.model) {
1949
+ const h = this.model.current;
1950
+ this.model.run(() => {
1951
+ h.designType(designType).value(t === "text" ? node.id : rawLiteralValue(node.id));
1952
+ });
1953
+ }
1180
1954
  return this;
1181
1955
  }
1182
1956
  definePrimitive(node, name) {
@@ -1184,66 +1958,82 @@ var JsRenderer = class extends BaseRenderer {
1184
1958
  this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
1185
1959
  return this;
1186
1960
  }
1187
- renderPrimitiveDef(def, name) {
1961
+ /** Emits a primitive's builder chain (and follows it in the validation model). */ renderPrimitiveDef(def, name) {
1188
1962
  const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
1189
- if (!def) return this.writeln(`$(${d()}).designType("any")`);
1190
- if (typeof def === "string") return this.writeln(`$(${d()}).designType("${def === "void" ? "undefined" : def}")`);
1963
+ const final = (designType) => {
1964
+ this.writeln(`$(${d()}).designType("${designType}")`);
1965
+ const h = this.modelHandle("", name);
1966
+ this.model?.run(() => h.designType(designType));
1967
+ };
1968
+ if (!def) return final("any");
1969
+ if (typeof def === "string") return final(def === "void" ? "undefined" : def);
1191
1970
  switch (def.kind) {
1192
- case "final": return this.writeln(`$(${d()}).designType("${def.value === "void" ? "undefined" : def.value}")`);
1971
+ case "final": return final(def.value === "void" ? "undefined" : def.value);
1193
1972
  case "union":
1194
1973
  case "intersection":
1195
1974
  case "tuple":
1196
1975
  this.writeln(`$(${d(def.kind)})`);
1976
+ this.modelHandle(def.kind, name);
1197
1977
  this.indent();
1198
1978
  for (const itemDef of def.items) {
1199
1979
  this.write(`.item(`);
1200
1980
  this.indent();
1201
- this.renderPrimitiveDef(itemDef);
1981
+ const child = this.modelChild(() => this.renderPrimitiveDef(itemDef));
1202
1982
  this.writeln(".$type");
1203
1983
  this.unindent();
1204
1984
  this.write(`)`);
1985
+ this.model?.run(() => this.model.current.item(child.$type));
1205
1986
  }
1206
1987
  this.unindent();
1207
1988
  return;
1208
- case "array":
1989
+ case "array": {
1209
1990
  this.writeln(`$(${d("array")})`);
1991
+ this.modelHandle("array", name);
1210
1992
  this.indent();
1211
1993
  this.write(".of(");
1212
1994
  this.indent();
1213
- this.renderPrimitiveDef(def.of);
1995
+ const child = this.modelChild(() => this.renderPrimitiveDef(def.of));
1214
1996
  this.writeln(`.$type`);
1215
1997
  this.unindent();
1216
1998
  this.writeln(`)`);
1217
1999
  this.unindent();
2000
+ this.model?.run(() => this.model.current.of(child.$type));
1218
2001
  return;
1219
- case "object":
2002
+ }
2003
+ case "object": {
1220
2004
  this.writeln(`$(${d("object")})`);
2005
+ this.modelHandle("object", name);
1221
2006
  this.indent();
1222
- for (const [key, propDef] of Object.entries(def.props)) {
1223
- const optional = typeof propDef === "object" && propDef.optional;
1224
- this.writeln(`.prop(`);
1225
- this.indent();
1226
- this.writeln(`"${escapeQuotes(key)}",`);
1227
- this.renderPrimitiveDef(propDef);
1228
- if (optional) this.writeln(".optional()");
1229
- this.writeln(".$type");
1230
- this.unindent();
1231
- this.write(`)`);
1232
- }
1233
- for (const [key, propDef] of Object.entries(def.propsPatterns)) {
2007
+ const props = [...Object.entries(def.props).map(([k, p]) => [
2008
+ k,
2009
+ p,
2010
+ false
2011
+ ]), ...Object.entries(def.propsPatterns).map(([k, p]) => [
2012
+ k,
2013
+ p,
2014
+ true
2015
+ ])];
2016
+ for (const [key, propDef, isPattern] of props) {
1234
2017
  const optional = typeof propDef === "object" && propDef.optional;
1235
- this.writeln(`.propPattern(`);
2018
+ this.writeln(isPattern ? `.propPattern(` : `.prop(`);
1236
2019
  this.indent();
1237
- this.writeln(`${key},`);
1238
- this.renderPrimitiveDef(propDef);
1239
- if (optional) this.writeln(".optional()");
2020
+ this.writeln(isPattern ? `${key},` : `"${escapeQuotes(key)}",`);
2021
+ const child = this.modelChild(() => {
2022
+ this.renderPrimitiveDef(propDef);
2023
+ if (optional) {
2024
+ this.writeln(".optional()");
2025
+ this.model?.run(() => this.model.current.optional());
2026
+ }
2027
+ });
1240
2028
  this.writeln(".$type");
1241
2029
  this.unindent();
1242
2030
  this.write(`)`);
2031
+ this.model?.run(() => isPattern ? this.model.current.propPattern(/./, child.$type) : this.model.current.prop(key, child.$type));
1243
2032
  }
1244
2033
  this.unindent();
1245
2034
  return;
1246
- default: return this.writeln(`$(${d()}).designType("any")`);
2035
+ }
2036
+ default: return final("any");
1247
2037
  }
1248
2038
  }
1249
2039
  defineObject(node) {
@@ -1261,25 +2051,39 @@ var JsRenderer = class extends BaseRenderer {
1261
2051
  this.indent();
1262
2052
  this.writeln(`"${escapeQuotes(prop.id)}",`);
1263
2053
  }
1264
- this.annotateType(prop.getDefinition());
1265
- this.indent().defineMetadata(prop).unindent();
2054
+ const child = this.modelChild(() => {
2055
+ this.annotateType(prop.getDefinition());
2056
+ this.indent().defineMetadata(prop).unindent();
2057
+ });
1266
2058
  if (optional) this.writeln(" .optional()");
1267
2059
  this.writeln(" .$type");
1268
2060
  this.unindent();
1269
2061
  this.write(`)`);
1270
2062
  this._propPath.pop();
2063
+ this.model?.run(() => {
2064
+ if (optional) child.optional();
2065
+ if (pattern) this.model.current.propPattern(pattern, child.$type);
2066
+ else this.model.current.prop(prop.id, child.$type);
2067
+ });
1271
2068
  }
1272
2069
  this.writeln();
1273
2070
  return this;
1274
2071
  }
1275
2072
  defineGroup(node) {
1276
- const items = node.unwrap();
1277
- for (const item of items) this.write(".item(").indent().annotateType(item).defineInlinePrimitiveMetadata(item).write(" .$type").writeln(`)`).unindent();
2073
+ for (const item of node.unwrap()) {
2074
+ this.write(".item(").indent();
2075
+ const child = this.modelChild(() => this.annotateType(item).defineInlinePrimitiveMetadata(item));
2076
+ this.write(" .$type").writeln(`)`).unindent();
2077
+ this.model?.run(() => this.model.current.item(child.$type));
2078
+ }
1278
2079
  return this;
1279
2080
  }
1280
2081
  defineArray(node) {
1281
2082
  const of = node.getDefinition();
1282
- this.write(".of(").indent().annotateType(of).defineInlinePrimitiveMetadata(of).write(" .$type").writeln(`)`).unindent();
2083
+ this.write(".of(").indent();
2084
+ const child = this.modelChild(() => this.annotateType(of).defineInlinePrimitiveMetadata(of));
2085
+ this.write(" .$type").writeln(`)`).unindent();
2086
+ this.model?.run(() => this.model.current.of(child.$type));
1283
2087
  return this;
1284
2088
  }
1285
2089
  /**
@@ -1350,9 +2154,10 @@ var JsRenderer = class extends BaseRenderer {
1350
2154
  return this;
1351
2155
  }
1352
2156
  resolveAnnotationValue(node, an) {
1353
- const { value, multiple } = this.computeAnnotationValue(node, an);
2157
+ const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
1354
2158
  if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
1355
2159
  else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
2160
+ this.model?.annotate(an.name, runtime, multiple);
1356
2161
  }
1357
2162
  emitRefValue(text, origin) {
1358
2163
  const dotIdx = text.indexOf(".");
@@ -1431,33 +2236,50 @@ var JsRenderer = class extends BaseRenderer {
1431
2236
  default: return token.text;
1432
2237
  }
1433
2238
  }
1434
- computeAnnotationValue(node, an) {
2239
+ /**
2240
+ * The JS source of an annotation's value, and (for the validation model, which only reads
2241
+ * validator annotations: numbers, strings, flags) the runtime value it evaluates to;
2242
+ * other argument kinds are opaque there.
2243
+ */ computeAnnotationValue(node, an) {
1435
2244
  const origin = this.doc.annotationOrigin(an);
1436
2245
  const spec = this.doc.resolveAnnotation(an.name);
1437
2246
  let targetValue = "true";
2247
+ let runtime = true;
1438
2248
  let multiple = false;
1439
2249
  if (spec) {
1440
2250
  multiple = spec.config.multiple;
1441
2251
  const length = spec.arguments.length;
1442
- if (length !== 0) if (Array.isArray(spec.config.argument)) {
1443
- targetValue = "{ ";
1444
- let i = 0;
1445
- for (const aSpec of spec.arguments) {
1446
- if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
1447
- i++;
2252
+ if (length !== 0) {
2253
+ if (Array.isArray(spec.config.argument)) {
2254
+ targetValue = "{ ";
2255
+ const fields = {};
2256
+ let i = 0;
2257
+ for (const aSpec of spec.arguments) {
2258
+ if (an.args[i]) {
2259
+ targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
2260
+ fields[aSpec.name] = runtimeArg(aSpec.type, an.args[i]);
2261
+ }
2262
+ i++;
2263
+ }
2264
+ targetValue += "}";
2265
+ runtime = fields;
2266
+ } else if (an.args[0]) {
2267
+ const aSpec = spec.arguments[0];
2268
+ targetValue = this.emitArgValue(aSpec, an.args[0], origin);
2269
+ runtime = runtimeArg(aSpec.type, an.args[0]);
1448
2270
  }
1449
- targetValue += "}";
1450
- } else {
1451
- const aSpec = spec.arguments[0];
1452
- targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0], origin) : "true";
1453
2271
  }
1454
2272
  } else {
1455
2273
  multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
1456
- if (an.args.length > 0) targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
2274
+ if (an.args.length > 0) {
2275
+ targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
2276
+ runtime = runtimeArg(void 0, an.args[0]);
2277
+ }
1457
2278
  }
1458
2279
  return {
1459
2280
  value: targetValue,
1460
- multiple: !!multiple
2281
+ multiple: !!multiple,
2282
+ runtime
1461
2283
  };
1462
2284
  }
1463
2285
  renderMutatingAnnotateNode(node) {
@@ -1470,7 +2292,7 @@ var JsRenderer = class extends BaseRenderer {
1470
2292
  const anns = entry.annotations;
1471
2293
  if (!anns || anns.length === 0) continue;
1472
2294
  const parts = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)] : [entry.id];
1473
- const { accessors, clones } = this.buildMutatingAccessors(targetName, targetDef, parts);
2295
+ const { accessors, clones } = this.buildMutatingAccessors(targetDef, parts);
1474
2296
  allClones.push(...clones);
1475
2297
  entryAccessors.push({
1476
2298
  entry,
@@ -1479,29 +2301,36 @@ var JsRenderer = class extends BaseRenderer {
1479
2301
  }
1480
2302
  const cloneKeys = /* @__PURE__ */ new Set();
1481
2303
  for (const clone of allClones) {
1482
- const key = `${clone.parentPath}|${clone.propName}`;
2304
+ const parentPath = accessorPath(targetName, clone.parentSteps);
2305
+ const key = `${parentPath}|${clone.propName}`;
1483
2306
  if (!cloneKeys.has(key)) {
1484
2307
  cloneKeys.add(key);
1485
- this.writeln(`$c(${clone.parentPath}, "${escapeQuotes(clone.propName)}")`);
2308
+ this.writeln(`$c(${parentPath}, "${escapeQuotes(clone.propName)}")`);
2309
+ this.model?.cloneProp(targetName, clone.parentSteps, clone.propName);
1486
2310
  }
1487
2311
  }
1488
- for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor);
2312
+ for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor, targetName);
1489
2313
  const topAnnotations = node.annotations;
1490
- if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, targetName);
2314
+ if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, [], targetName);
1491
2315
  this.writeln();
1492
2316
  }
1493
- emitMutatingAnnotations(node, annotations, accessor) {
2317
+ emitMutatingAnnotations(node, annotations, steps, targetName) {
2318
+ const accessor = accessorPath(targetName, steps);
1494
2319
  const cleared = /* @__PURE__ */ new Set();
1495
2320
  for (const an of annotations) {
1496
- const { value, multiple } = this.computeAnnotationValue(node, an);
2321
+ const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
1497
2322
  if (multiple) {
1498
2323
  if (!cleared.has(an.name)) {
1499
2324
  const spec = this.doc.resolveAnnotation(an.name);
1500
- if (!spec || spec.config.mergeStrategy !== "append") this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
2325
+ if (!spec || spec.config.mergeStrategy !== "append") {
2326
+ this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
2327
+ this.model?.deleteAnnotation(targetName, steps, an.name);
2328
+ }
1501
2329
  cleared.add(an.name);
1502
2330
  }
1503
2331
  this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value}, true)`);
1504
2332
  } else this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value})`);
2333
+ this.model?.mutateAnnotation(targetName, steps, an.name, runtime, multiple);
1505
2334
  }
1506
2335
  }
1507
2336
  resolveTargetDef(targetName) {
@@ -1512,51 +2341,48 @@ var JsRenderer = class extends BaseRenderer {
1512
2341
  return def;
1513
2342
  }
1514
2343
  /**
1515
- * Builds the runtime accessor paths for mutating annotate entries.
2344
+ * Builds the accessor paths (as steps, see `accessorPath`) for mutating annotate entries.
1516
2345
  * Computes exact paths at compile time by walking the AST,
1517
2346
  * so the generated JS accesses props directly without runtime search.
1518
2347
  * Returns multiple paths when a property appears in multiple union branches.
1519
- */ buildMutatingAccessors(targetName, targetDef, parts) {
2348
+ */ buildMutatingAccessors(targetDef, parts) {
1520
2349
  let accessors = [{
1521
- prefix: `${targetName}.type`,
2350
+ steps: ["type"],
1522
2351
  def: targetDef
1523
2352
  }];
1524
2353
  const clones = [];
1525
2354
  for (let i = 0; i < parts.length; i++) {
2355
+ const last = i === parts.length - 1;
1526
2356
  const nextAccessors = [];
1527
- for (const { prefix, def } of accessors) {
2357
+ for (const { steps, def } of accessors) {
1528
2358
  const results = this.buildPropPaths(def, parts[i]);
1529
- if (results.length > 0) for (const result of results) if (i < parts.length - 1) {
1530
- if (result.propDef && isRef(result.propDef)) clones.push({
1531
- parentPath: prefix,
2359
+ const found = results.length > 0 ? results : [{
2360
+ steps: [["props", parts[i]]],
2361
+ propDef: void 0
2362
+ }];
2363
+ for (const result of found) {
2364
+ if (!last && result.propDef && isRef(result.propDef)) clones.push({
2365
+ parentSteps: steps,
1532
2366
  propName: parts[i]
1533
2367
  });
2368
+ const next = [...steps, ...result.steps];
2369
+ if (!last) next.push("type");
1534
2370
  nextAccessors.push({
1535
- prefix: `${prefix}${result.path}?.type`,
2371
+ steps: next,
1536
2372
  def: result.propDef
1537
2373
  });
1538
- } else nextAccessors.push({
1539
- prefix: `${prefix}${result.path}?`,
1540
- def: result.propDef
1541
- });
1542
- else {
1543
- const suffix = `.props.get("${escapeQuotes(parts[i])}")${i < parts.length - 1 ? "?.type" : "?"}`;
1544
- nextAccessors.push({
1545
- prefix: `${prefix}${suffix}`,
1546
- def: void 0
1547
- });
1548
2374
  }
1549
2375
  }
1550
2376
  accessors = nextAccessors;
1551
2377
  }
1552
2378
  return {
1553
- accessors: accessors.map((a) => a.prefix),
2379
+ accessors: accessors.map((a) => a.steps),
1554
2380
  clones
1555
2381
  };
1556
2382
  }
1557
2383
  /**
1558
2384
  * Finds a property in a type tree at compile time, returning all
1559
- * matching runtime path strings and prop definitions for further chaining.
2385
+ * matching accessor steps and prop definitions for further chaining.
1560
2386
  * Returns multiple results when the same property appears in different union branches.
1561
2387
  */ buildPropPaths(def, propName) {
1562
2388
  if (!def) return [];
@@ -1570,7 +2396,7 @@ var JsRenderer = class extends BaseRenderer {
1570
2396
  if (isStructure(def)) {
1571
2397
  const prop = def.props.get(propName);
1572
2398
  if (prop) return [{
1573
- path: `.props.get("${escapeQuotes(propName)}")`,
2399
+ steps: [["props", propName]],
1574
2400
  propDef: prop.getDefinition()
1575
2401
  }];
1576
2402
  return [];
@@ -1579,7 +2405,11 @@ var JsRenderer = class extends BaseRenderer {
1579
2405
  const items = def.unwrap();
1580
2406
  const results = [];
1581
2407
  for (let i = 0; i < items.length; i++) for (const result of this.buildPropPaths(items[i], propName)) results.push({
1582
- path: `.items[${i}].type${result.path}`,
2408
+ steps: [
2409
+ ["items", i],
2410
+ "type",
2411
+ ...result.steps
2412
+ ],
1583
2413
  propDef: result.propDef
1584
2414
  });
1585
2415
  return results;
@@ -1587,13 +2417,19 @@ var JsRenderer = class extends BaseRenderer {
1587
2417
  return [];
1588
2418
  }
1589
2419
  constructor(doc, opts) {
1590
- 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();
2420
+ 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();
2421
+ if (opts?.compileValidators) this.model = new ValidationModel();
1591
2422
  }
1592
2423
  };
1593
2424
 
1594
2425
  //#endregion
1595
2426
  //#region packages/typescript/src/plugin.ts
1596
2427
  /**
2428
+ * Render formats of the JS output that override {@link TTsPluginOptions.compileValidators}
2429
+ * (used by `unplugin-atscript`'s `compileValidators` option).
2430
+ */ const JS_COMPILED_FORMAT = "js:compiled";
2431
+ const JS_INTERPRETED_FORMAT = "js:interpreted";
2432
+ /**
1597
2433
  * Resolves the effective JSON schema mode from plugin options.
1598
2434
  */ function resolveJsonSchemaMode(opts) {
1599
2435
  if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
@@ -1607,10 +2443,16 @@ const tsPlugin = (opts) => {
1607
2443
  fileName: `${doc.name}.d.ts`,
1608
2444
  content: new TypeRenderer(doc, opts).render()
1609
2445
  }];
1610
- if (format === "js") return [{
1611
- fileName: `${doc.name}.js`,
1612
- content: new JsRenderer(doc, opts).render()
1613
- }];
2446
+ if (format === "js" || format === JS_COMPILED_FORMAT || format === JS_INTERPRETED_FORMAT) {
2447
+ const jsOpts = format === "js" ? opts : {
2448
+ ...opts,
2449
+ compileValidators: format === JS_COMPILED_FORMAT
2450
+ };
2451
+ return [{
2452
+ fileName: `${doc.name}.js`,
2453
+ content: new JsRenderer(doc, jsOpts).render()
2454
+ }];
2455
+ }
1614
2456
  },
1615
2457
  async buildEnd(output, format, repo) {
1616
2458
  if (format === "dts" || format === DEFAULT_FORMAT) {
@@ -1638,4 +2480,4 @@ const tsPlugin = (opts) => {
1638
2480
  };
1639
2481
 
1640
2482
  //#endregion
1641
- export { tsPlugin as t };
2483
+ export { JS_INTERPRETED_FORMAT as n, tsPlugin as r, JS_COMPILED_FORMAT as t };