@atscript/typescript 0.1.110 → 0.2.0

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.
@@ -3,7 +3,8 @@
3
3
  /**
4
4
  * Annotation keys the validator pre-check reads, per kind of checked value — shared by the
5
5
  * interpreted pre-check (validator-fast-check.ts) and the compiled checks (compiled-check/).
6
- */ /** Annotations of a string node, in check order. */ const STRING_KEYS = [
6
+ */ /** The format of a `decimal` value (a string). */ const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
7
+ /** Annotations of a string node, in check order. */ const STRING_KEYS = [
7
8
  "meta.required",
8
9
  "expect.minLength",
9
10
  "expect.maxLength",
@@ -43,11 +44,18 @@
43
44
  */ function boundOf(m, field) {
44
45
  return typeof m === "number" ? m : m[field];
45
46
  }
47
+ /** The props of array item type `of` (an object) marked `@expect.array.key`, in order. */ function arrayKeyProps(of) {
48
+ const out = [];
49
+ if (of?.type.kind === "object") {
50
+ for (const [key, prop] of of.type.props) if (prop.metadata.get("expect.array.key")) out.push(key);
51
+ }
52
+ return out;
53
+ }
46
54
 
47
55
  //#endregion
48
56
  //#region packages/typescript/src/runtime/compiled-check/tracking.ts
49
57
  /**
50
- * Mutation tracking for build-time compiled validator checks.
58
+ * Mutation tracking for build-time compiled validator checks and cached layered metadata reads.
51
59
  *
52
60
  * A compiled check is bound to the live type tree before use (see registry.ts): the bind
53
61
  * verifies that the tree still has the structure the check was compiled for and snapshots
@@ -55,11 +63,17 @@
55
63
  * read bumps one global epoch, which makes every compiled check re-bind on its next use.
56
64
  *
57
65
  * Tracked: `annotate()`, the metadata / props `Map` methods (`set` / `delete` / `clear`),
58
- * the `defineAnnotatedType()` handle methods and `cloneRefProp()`. Raw property writes
59
- * (`node.optional = …`, `type.items.push(…)`, editing a constraint object in place, …)
60
- * cannot be seen: call {@link invalidateCompiledValidators} after them.
66
+ * the `defineAnnotatedType()` handle methods. Raw writes (`node.optional = …`,
67
+ * `node.metadata = …`, `type.items.push(…)`, editing a constraint object in place, …) cannot
68
+ * be seen: call {@link invalidateCompiledValidators} after them, with either validator engine.
61
69
  */ const VALIDATOR_KEY_SET = new Set(VALIDATOR_KEYS);
70
+ const mapSet = Map.prototype.set;
62
71
  /** Global mutation epoch: compiled checks bound in an older epoch re-bind before use. */ let epoch = 0;
72
+ /**
73
+ * Writes of metadata maps so far (any map, any key: `annotate()`, the `Map` methods, a node's map
74
+ * replaced, a layer flag or intrinsic mark registered): a lazy JSON schema or a layered map's
75
+ * flattened view built before the last one is built again (see `lazyJsonSchema`, `LayerMap`).
76
+ */ let metadataWrites = 0;
63
77
  /** Some bind has watched an object (until then no mutation can affect a compiled check). */ let tracking = false;
64
78
  /** Objects (nodes, type defs, metadata / props maps) read by some compiled-check bind. */ const watched = /* @__PURE__ */ new WeakSet();
65
79
  /** The current mutation epoch. */ function currentEpoch() {
@@ -73,27 +87,45 @@
73
87
  if (tracking && watched.has(obj)) epoch++;
74
88
  }
75
89
  /**
76
- * Makes every compiled validator check re-verify the type tree it was compiled for before
77
- * its next use.
90
+ * Makes every compiled validator check re-verify the type tree it was compiled for, and every
91
+ * node that reads metadata through other nodes re-read them, before its next use.
78
92
  *
79
- * Compiled checks (emitted with `tsPlugin({ compileValidators: true })`) see mutations made
80
- * through `annotate()`, the metadata / props `Map` methods, the `defineAnnotatedType()`
81
- * handle methods and `cloneRefProp()` automatically. Call this after changing a type tree
82
- * any other way:
93
+ * Validators (compiled checks emitted with `tsPlugin({ compileValidators: true })` and the
94
+ * interpreted walk alike) see mutations made through `annotate()`, the metadata / props `Map`
95
+ * methods and the `defineAnnotatedType()` handle methods automatically. Call this after
96
+ * changing a type tree any other way:
83
97
  * - a raw property write: `node.optional = …`, `node.type = …`, `node.metadata = …`,
84
98
  * `type.items.push(…)`, `type.of = …`, `type.propsPatterns.push(…)`;
85
99
  * - an in-place edit of an annotation value: mutating a constraint object
86
100
  * (`metadata.get('expect.min').minValue = 5`), editing or pushing onto an
87
101
  * `@expect.pattern` array directly (use `annotate(metadata, key, value, true)` instead).
88
102
  *
89
- * Without it the compiled check may keep validating against the old shape or values.
90
- * Types without compiled checks are always read live and never need it.
103
+ * Without it a compiled check may keep validating against the old shape or values, and a
104
+ * node that reads metadata through other nodes (a reference, a merged field, a path override)
105
+ * may keep reading the old values: the rule is the same for both engines.
91
106
  *
92
107
  * Any mutation of a type a compiled check has bound to (tracked or invalidated) makes every
93
108
  * compiled check re-bind once on its next use: cheap during startup / configuration, but
94
109
  * avoid mutating validated types per request.
95
110
  */ function invalidateCompiledValidators() {
96
111
  epoch++;
112
+ metadataWrites++;
113
+ }
114
+ /** The number of metadata writes so far (see `metadataWrites`). */ function metadataWriteCount() {
115
+ return metadataWrites;
116
+ }
117
+ /** Records a write of a node's metadata the maps do not see: the node's map replaced. */ function metadataReplaced() {
118
+ metadataWrites++;
119
+ }
120
+ /**
121
+ * `annotate(m, key, value, true)` where map `m` holds `own` as its own value of `key`: appended in
122
+ * place to an own list (the map sees no write: tracked here as one), else a list of both.
123
+ */ function appendOwn(m, key, own, value) {
124
+ if (Array.isArray(own)) {
125
+ own.push(value);
126
+ if (VALIDATOR_KEY_SET.has(key)) touched(m);
127
+ metadataWrites++;
128
+ } else m.set(key, [own, value]);
97
129
  }
98
130
  /**
99
131
  * Metadata map of runtime type nodes: a `Map` whose writes to validator annotation keys
@@ -102,16 +134,25 @@
102
134
  set(key, value) {
103
135
  super.set(key, value);
104
136
  if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
137
+ metadataWrites++;
105
138
  return this;
106
139
  }
107
140
  delete(key) {
108
141
  const deleted = super.delete(key);
109
- if (deleted && tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
142
+ if (deleted) {
143
+ if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
144
+ metadataWrites++;
145
+ }
110
146
  return deleted;
111
147
  }
112
148
  clear() {
113
149
  super.clear();
114
150
  touched(this);
151
+ metadataWrites++;
152
+ }
153
+ /** A new map holding `entries`: no write (a new map is in no compiled check nor schema). */ constructor(entries) {
154
+ super();
155
+ if (entries) for (const [key, value] of entries) mapSet.call(this, key, value);
115
156
  }
116
157
  };
117
158
  /** Props map of runtime object types: a `Map` whose writes are tracked. */ var PropsMap = class extends Map {
@@ -129,9 +170,759 @@
129
170
  super.clear();
130
171
  touched(this);
131
172
  }
173
+ /** A new map holding `entries` (untracked: a new map is in no compiled check). */ constructor(entries) {
174
+ super();
175
+ if (entries) for (const [key, value] of entries) mapSet.call(this, key, value);
176
+ }
177
+ };
178
+
179
+ //#endregion
180
+ //#region packages/typescript/src/runtime/layers.ts
181
+ /**
182
+ * Metadata layers: the runtime's one metadata mechanism.
183
+ *
184
+ * A node's metadata is its own map plus an ordered list of base nodes (`b`, priority order:
185
+ * `b[0]` first). A read returns the own value, else the first base that has the key; an append
186
+ * key returns the bases' values (lowest priority first), then the own ones. Writes (`set`,
187
+ * `delete`, `clear`) are the own map's: `delete` lets a base's value show again, and a write on
188
+ * a base shows through every layer over it.
189
+ *
190
+ * Reads go through a flattened view of the effective entries, rebuilt on the first read after any
191
+ * metadata write (one global write counter: `metadataWriteCount`). The view is used only while
192
+ * every map below is tracked (an `AnnotationMap` or a `LayerMap`, whose writes the counter
193
+ * sees); otherwise the reads are live. A raw write the counter does not see (a node's map swapped,
194
+ * `node.metadata = X`, or edited in place) must be followed by `invalidateCompiledValidators()`,
195
+ * as compiled checks require (PERF-2).
196
+ */ function _define_property$2(obj, key, value) {
197
+ if (key in obj) Object.defineProperty(obj, key, {
198
+ value,
199
+ enumerable: true,
200
+ configurable: true,
201
+ writable: true
202
+ });
203
+ else obj[key] = value;
204
+ return obj;
205
+ }
206
+ /** Append keys: concatenated across layers (registered by generated code, `$ak`). */ const APPEND = 1;
207
+ /** `passedWhenReferred: false` keys: never read through a reference layer (`$nr`). */ const NOT_REFERRED = 2;
208
+ /** The flags of the registered keys (one lookup per read). */ const FLAGS = /* @__PURE__ */ new Map();
209
+ function flag(keys, f) {
210
+ for (const key of keys) FLAGS.set(key, (FLAGS.get(key) ?? 0) | f);
211
+ metadataReplaced();
212
+ }
213
+ /** Registers append keys (`mergeStrategy: 'append'`). */ function $ak(...keys) {
214
+ flag(keys, APPEND);
215
+ }
216
+ /** Registers `passedWhenReferred: false` keys. */ function $nr(...keys) {
217
+ flag(keys, NOT_REFERRED);
218
+ }
219
+ /** Whether `key` is an append key (see {@link $ak}). */ function isAppendKey(key) {
220
+ return ((FLAGS.get(key) ?? 0) & APPEND) !== 0;
221
+ }
222
+ const notReferred = (key) => ((FLAGS.get(key) ?? 0) & NOT_REFERRED) !== 0;
223
+ /**
224
+ * Intrinsic entries per metadata map: a primitive extension's own annotations
225
+ * (`string.required` → `meta.required`) are part of the type, so they pass every reference layer
226
+ * although their key is `passedWhenReferred: false` (0.1.110).
227
+ */ const INTRINSIC = /* @__PURE__ */ new WeakMap();
228
+ /** Marks `keys` of map `m` intrinsic (see {@link INTRINSIC}). */ function markIntrinsic(m, keys) {
229
+ let s = INTRINSIC.get(m);
230
+ if (!s) INTRINSIC.set(m, s = /* @__PURE__ */ new Set());
231
+ for (const k of keys) s.add(k);
232
+ metadataReplaced();
233
+ }
234
+ /**
235
+ * A map replacing `from` (layered over its bases now) keeps its intrinsic marks. (No write
236
+ * counted: the callers count the map replaced.)
237
+ */ function moveIntrinsic(from, to) {
238
+ const s = INTRINSIC.get(from);
239
+ if (s) INTRINSIC.set(to, s);
240
+ }
241
+ const MISS = Symbol("miss");
242
+ /** The view of a layered map without effective entries (never written: views stay internal). */ const NO_ENTRIES = new AnnotationMap();
243
+ const mapGet = Map.prototype.get;
244
+ const mapHas = Map.prototype.has;
245
+ const ownSize = Object.getOwnPropertyDescriptor(Map.prototype, "size").get;
246
+ let _Symbol_iterator = Symbol.iterator;
247
+ /**
248
+ * A metadata map that reads through base nodes (see the file comment). `r`: the bases are
249
+ * reference layers (a prop's / element's type, a chain ref, `extends`, merge operands), so
250
+ * `passedWhenReferred: false` keys are not read through them.
251
+ */ var LayerMap = class extends AnnotationMap {
252
+ /**
253
+ * The flattened view (built again after a metadata write), `undefined`: read live. Internal:
254
+ * this module's readers and the validators read it (`readable`, `filledMeta`), never write.
255
+ */ view() {
256
+ return this.w === metadataWriteCount() ? this.f : this.flatten();
257
+ }
258
+ flatten() {
259
+ this.w = -1;
260
+ let f;
261
+ if (tracked(this, /* @__PURE__ */ new Set())) {
262
+ const keys = this.liveKeys();
263
+ f = keys.length === 0 ? NO_ENTRIES : new AnnotationMap(keys.map((k) => [k, this.liveGet(k)]));
264
+ }
265
+ this.f = f;
266
+ this.w = metadataWriteCount();
267
+ return f;
268
+ }
269
+ /** The value of `key` (not concatenated), or `MISS`; `nr`: a `passedWhenReferred:false` key. */ lookup(key, nr) {
270
+ if (ownSize.call(this) !== 0) {
271
+ const v = mapGet.call(this, key);
272
+ if (v !== void 0 || mapHas.call(this, key)) return v;
273
+ }
274
+ if (nr && this.r) {
275
+ for (const n of this.b) {
276
+ const x = intrinsicLookup(n.metadata, key);
277
+ if (x !== MISS) return x;
278
+ }
279
+ return MISS;
280
+ }
281
+ for (const n of this.b) {
282
+ const m = n.metadata;
283
+ let x;
284
+ if (m.b === void 0) {
285
+ x = m.get(key);
286
+ if (x === void 0 && !m.has(key)) x = MISS;
287
+ } else x = m.lookup(key, nr);
288
+ if (x !== MISS) return x;
289
+ }
290
+ return MISS;
291
+ }
292
+ get(key) {
293
+ const view = this.w === metadataWriteCount() ? this.f : this.flatten();
294
+ return view === void 0 ? this.liveGet(key) : mapGet.call(view, key);
295
+ }
296
+ /** `get` read through the layers (see the file comment). */ liveGet(key) {
297
+ const f = FLAGS.get(key);
298
+ if (f !== void 0 && (f & APPEND) !== 0) return this.append(key);
299
+ const v = this.lookup(key, f !== void 0 && (f & NOT_REFERRED) !== 0);
300
+ return v === MISS ? void 0 : v;
301
+ }
302
+ has(key) {
303
+ const view = this.view();
304
+ return view === void 0 ? this.lookup(key, notReferred(key)) !== MISS : mapHas.call(view, key);
305
+ }
306
+ /** An append key: the bases' values (lowest priority first), then the own ones. */ append(key) {
307
+ const own = mapGet.call(this, key);
308
+ if (this.r && notReferred(key)) {
309
+ const parts = [];
310
+ const acc = {
311
+ out: parts,
312
+ seen: /* @__PURE__ */ new Map()
313
+ };
314
+ for (let i = this.b.length - 1; i >= 0; i--) collect(this.b[i].metadata, key, acc, true);
315
+ if (parts.length === 0) return own;
316
+ if (own !== void 0) parts.push(own);
317
+ return parts.length === 1 ? parts[0] : parts.flat();
318
+ }
319
+ let one;
320
+ let count = 0;
321
+ for (const n of this.b) {
322
+ const x = n.metadata.get(key);
323
+ if (x !== void 0 && ++count === 1) one = x;
324
+ }
325
+ if (count === 0) return own;
326
+ if (count === 1 && own === void 0) return one;
327
+ const parts = [];
328
+ collect(this, key, {
329
+ out: parts,
330
+ seen: /* @__PURE__ */ new Map()
331
+ }, false);
332
+ if (parts.length === 1) return parts[0];
333
+ const out = [];
334
+ for (const p of parts) if (Array.isArray(p)) out.push(...p);
335
+ else out.push(p);
336
+ return out;
337
+ }
338
+ /** The effective keys: own first, then the bases' in priority order. */ effectiveKeys() {
339
+ const view = this.view();
340
+ return view === void 0 ? this.liveKeys() : [...view.keys()];
341
+ }
342
+ liveKeys() {
343
+ const out = /* @__PURE__ */ new Set();
344
+ keysOf(this, false, out, /* @__PURE__ */ new Map());
345
+ return [...out];
346
+ }
347
+ keys() {
348
+ return this.effectiveKeys()[Symbol.iterator]();
349
+ }
350
+ values() {
351
+ return this.effectiveKeys().map((k) => this.get(k))[Symbol.iterator]();
352
+ }
353
+ entries() {
354
+ return this.effectiveKeys().map((k) => [k, this.get(k)])[Symbol.iterator]();
355
+ }
356
+ [_Symbol_iterator]() {
357
+ return this.entries();
358
+ }
359
+ forEach(cb, thisArg) {
360
+ for (const k of this.effectiveKeys()) cb.call(thisArg, this.get(k), k, this);
361
+ }
362
+ constructor(bases, reference = false, own) {
363
+ super(own), _define_property$2(this, "b", void 0), _define_property$2(this, "r", void 0), _define_property$2(this, "f", void 0), _define_property$2(this, "w", void 0);
364
+ this.b = bases;
365
+ this.r = reference;
366
+ this.f = void 0;
367
+ this.w = -1;
368
+ }
132
369
  };
133
- /** `true` when `key` is an annotation the validator pre-check reads. */ function isValidatorKey(key) {
134
- return VALIDATOR_KEY_SET.has(key);
370
+ Object.defineProperty(LayerMap.prototype, "size", {
371
+ get() {
372
+ const view = this.view();
373
+ if (view !== void 0) return view.size;
374
+ return metaEmpty(this) ? 0 : this.effectiveKeys().length;
375
+ },
376
+ configurable: true
377
+ });
378
+ /**
379
+ * Every map of `m`'s layers is tracked (an `AnnotationMap` or a `LayerMap`, whose writes count in
380
+ * `metadataWrites`), so a flattened view of `m` stays right until the next write.
381
+ */ function tracked(m, seen) {
382
+ const p = Object.getPrototypeOf(m);
383
+ if (p !== AnnotationMap.prototype && p !== LayerMap.prototype) return false;
384
+ const b = m.b;
385
+ if (b !== void 0 && !seen.has(m)) {
386
+ seen.add(m);
387
+ for (const n of b) if (!tracked(n.metadata, seen)) return false;
388
+ }
389
+ return true;
390
+ }
391
+ /** `key`'s intrinsic value in `m` or its bases (see {@link INTRINSIC}), or `MISS`. */ function intrinsicLookup(m, key) {
392
+ if (INTRINSIC.get(m)?.has(key)) {
393
+ if (m instanceof LayerMap ? mapHas.call(m, key) : m.has(key)) return m instanceof LayerMap ? mapGet.call(m, key) : m.get(key);
394
+ }
395
+ const b = m.b;
396
+ if (b !== void 0) for (const n of b) {
397
+ const x = intrinsicLookup(n.metadata, key);
398
+ if (x !== MISS) return x;
399
+ }
400
+ return MISS;
401
+ }
402
+ /**
403
+ * Whether a layer walk visits `m` (reached `filtered` or not): each map once, except that a map
404
+ * first reached `filtered` (through a reference layer) is visited again when reached unfiltered
405
+ * (a diamond: a direct base over the same node), as the layered `get` reads it. `seen`: the maps
406
+ * visited, `true` while only filtered.
407
+ */ function visit(m, filtered, seen) {
408
+ const was = seen.get(m);
409
+ if (was !== void 0 && (filtered || !was)) return false;
410
+ seen.set(m, filtered);
411
+ return true;
412
+ }
413
+ /**
414
+ * The values of `key` of `m` and its bases (lowest priority first), each map once (see
415
+ * {@link visit}). `filtered`: reached through a reference layer with a `passedWhenReferred: false`
416
+ * key — only intrinsic entries count (see {@link INTRINSIC}), down to the bottom.
417
+ */ function collect(m, key, acc, filtered) {
418
+ const was = acc.seen.get(m);
419
+ if (!visit(m, filtered, acc.seen)) return;
420
+ const layer = m instanceof LayerMap ? m : void 0;
421
+ if (layer) {
422
+ const below = filtered || layer.r && notReferred(key);
423
+ for (let i = layer.b.length - 1; i >= 0; i--) collect(layer.b[i].metadata, key, acc, below);
424
+ }
425
+ const intrinsic = INTRINSIC.get(m)?.has(key) === true;
426
+ if ((filtered ? intrinsic : !(was === true && intrinsic)) && (layer ? mapHas.call(m, key) : m.has(key))) acc.out.push(layer ? mapGet.call(m, key) : m.get(key));
427
+ }
428
+ /**
429
+ * The keys of `m` (own first, then its bases'), each map once (see {@link visit}). `filtered`:
430
+ * reached through a reference layer.
431
+ */ function keysOf(m, filtered, out, seen) {
432
+ if (!visit(m, filtered, seen)) return;
433
+ const layer = m instanceof LayerMap ? m : void 0;
434
+ const own = layer ? Map.prototype.keys.call(m) : m.keys();
435
+ const intrinsic = INTRINSIC.get(m);
436
+ for (const k of own) if (!filtered || !notReferred(k) || intrinsic?.has(k)) out.add(k);
437
+ if (layer) for (const n of layer.b) keysOf(n.metadata, filtered || layer.r, out, seen);
438
+ }
439
+ /**
440
+ * `m` has no entry (own or through its bases): the validators' `metadata.size === 0` fast path,
441
+ * without computing a layered map's effective size. May answer `false` for a map whose only base
442
+ * entries are filtered out (`passedWhenReferred: false`): the slow path then finds nothing.
443
+ */ function metaEmpty(m) {
444
+ const b = m.b;
445
+ if (b === void 0) return m.size === 0;
446
+ const view = m.view();
447
+ if (view !== void 0) return view.size === 0;
448
+ if (ownSize.call(m) !== 0) return false;
449
+ for (const n of b) if (!metaEmpty(n.metadata)) return false;
450
+ return true;
451
+ }
452
+ /**
453
+ * `m` for reading: a layered map's flattened view (see `LayerMap.view`), else `m` itself.
454
+ * The validators read builtin maps this way (never write: a view is shared).
455
+ */ function readable(m) {
456
+ return m.b === void 0 ? m : m.view() ?? m;
457
+ }
458
+ /**
459
+ * {@link readable}`(m)`, or `undefined` when `m` has no entry: the validators' "no constraint"
460
+ * fast path and their reads in one (a plain map costs what `metaEmpty` did).
461
+ */ function filledMeta(m) {
462
+ if (m.b === void 0) return m.size === 0 ? void 0 : m;
463
+ const view = m.view();
464
+ if (view !== void 0) return view.size === 0 ? void 0 : view;
465
+ return metaEmpty(m) ? void 0 : m;
466
+ }
467
+ /**
468
+ * Watches `m` and every base (node and map, transitively) for a compiled check's bind (see
469
+ * `compiled-check/tracking.ts`): a tracked write to any of them re-binds the check. `false` when
470
+ * one of the maps is untracked (a plain `Map`): such a tree stays interpreted.
471
+ */ function watchLayer(m, seen) {
472
+ watch(m);
473
+ const b = m.b;
474
+ if (b === void 0) return m instanceof AnnotationMap;
475
+ let ok = true;
476
+ for (const n of b) {
477
+ const nm = n.metadata;
478
+ if (seen?.has(nm)) continue;
479
+ (seen ?? (seen = /* @__PURE__ */ new Set())).add(nm);
480
+ watch(n);
481
+ ok = watchLayer(nm, seen) && ok;
482
+ }
483
+ return ok;
484
+ }
485
+ /** The own entries of `m` (a layered map's, not read through its bases). */ function ownEntries(m) {
486
+ return m instanceof LayerMap ? [...Map.prototype.entries.call(m)] : m;
487
+ }
488
+ /** The own value of `key` of `m` (not read through its bases). */ function ownValue(m, key) {
489
+ return m instanceof LayerMap ? mapGet.call(m, key) : m.get(key);
490
+ }
491
+ /**
492
+ * `annotate(map, key, value, true)` on a layered map: appends to the own list. For an append
493
+ * key that is the own part of the concatenation; for another list key the own list starts as
494
+ * the value read (as when the node held a copy).
495
+ */ function annotateLayer(m, key, value) {
496
+ if (mapHas.call(m, key)) {
497
+ appendOwn(m, key, mapGet.call(m, key), value);
498
+ return;
499
+ }
500
+ const read = isAppendKey(key) ? void 0 : m.get(key);
501
+ m.set(key, read === void 0 ? [value] : Array.isArray(read) ? [...read, value] : [read, value]);
502
+ }
503
+
504
+ //#endregion
505
+ //#region packages/typescript/src/runtime/stateless-regex.ts
506
+ /**
507
+ * The regex a validator tests with: one whose `test` keeps no state between calls.
508
+ *
509
+ * With the `g` or `y` flag, `RegExp.prototype.test` starts at `lastIndex` and moves it
510
+ * (past a match, or back to 0 after a miss), so one regex object shared by every check of a
511
+ * pattern would accept and reject the same value on alternate calls. The flags are dropped
512
+ * when the regex is compiled, which costs nothing per test: `g` does not change what `test`
513
+ * finds from `lastIndex` 0, and `y` matches only at `lastIndex` 0 — at the start of the
514
+ * value — so it becomes an anchor at the start of the input (`^`, or a look-behind under
515
+ * `m`, where `^` also matches after a line break). Other regexes are returned as they are.
516
+ */ function statelessRegExp(re) {
517
+ if (!re.global && !re.sticky) return re;
518
+ const flags = re.flags.replace(/[gy]/g, "");
519
+ if (!re.sticky) return new RegExp(re.source, flags);
520
+ return new RegExp(`${re.multiline ? "(?<![\\s\\S])" : "^"}(?:${re.source})`, flags);
521
+ }
522
+ /**
523
+ * The source of a pattern written with `flags` as a JSON Schema `pattern` (which has no flags),
524
+ * matching the same strings as the validator's regex:
525
+ *
526
+ * - `s`: every `.` outside a character class becomes `[\s\S]`;
527
+ * - `i`: every character that has case variants becomes a class of them (`a` → `[aA]`,
528
+ * `[a-f]` → `[a-fA-F]`, with `u` also `s` → `[sSſ]`, `\w` → `[\wſK]`); a pattern
529
+ * using what has no flag-free form — a backreference, a Unicode property escape or (with `u`)
530
+ * `\b` / `\B` / `\W` in a class, a range of more than 1024 characters with non-ASCII ones — is
531
+ * also wrapped in a modifier group `(?i:…)`;
532
+ * - `m`: the pattern is wrapped in a modifier group `(?m:…)` (`^` / `$` at line breaks have no
533
+ * flag-free form without look-behinds);
534
+ * - `y`: matches at the start of the value only (see {@link statelessRegExp}): `^(?:…)`;
535
+ * - `g` changes nothing; `u` is the dialect of the pattern (JSON Schema validators commonly compile
536
+ * patterns with it — ajv does).
537
+ *
538
+ * Modifier groups (ES2025) are understood by JavaScript engines from 2024 on (Node.js 23+, V8 12.5+)
539
+ * and by some other regex dialects (.NET, PCRE2, Python 3.6+), not by all.
540
+ */ function jsonSchemaPattern(pattern, flags) {
541
+ if (!flags) return pattern;
542
+ const unicode = flags.includes("u");
543
+ const modifiers = /* @__PURE__ */ new Set();
544
+ let body = pattern;
545
+ if (flags.includes("i") || flags.includes("s")) {
546
+ const translated = translateFlags(pattern, unicode, flags.includes("i"), flags.includes("s"));
547
+ if (translated) {
548
+ body = translated.source;
549
+ if (translated.modifier) modifiers.add("i");
550
+ } else for (const flag of "is") if (flags.includes(flag)) modifiers.add(flag);
551
+ }
552
+ if (flags.includes("m")) modifiers.add("m");
553
+ if (modifiers.size > 0) body = `(?${[...modifiers].sort().join("")}:${body})`;
554
+ return flags.includes("y") ? `^(?:${body})` : body;
555
+ }
556
+ /**
557
+ * Characters case-insensitive matching relates to characters that case mapping does not lead to
558
+ * from them (`k` → `K`, but `K` (U+212A) only folds to `k`): groups closing the search of
559
+ * {@link caseVariants} (the regex engine then keeps those that match).
560
+ */ const FOLD_GROUPS = [
561
+ "kKK",
562
+ "sSſ",
563
+ "ÅåÅ",
564
+ "ßẞ",
565
+ "DŽDždž",
566
+ "LJLjlj",
567
+ "NJNjnj",
568
+ "DZDzdz",
569
+ "ͅΙιι",
570
+ "ΐΐ",
571
+ "Ββϐ",
572
+ "Εεϵ",
573
+ "Θθϑϴ",
574
+ "Κκϰ",
575
+ "µΜμ",
576
+ "Ππϖ",
577
+ "Ρρϱ",
578
+ "Σςσ",
579
+ "Φφϕ",
580
+ "ΩωΩ",
581
+ "ΰΰ",
582
+ "Ввᲀ",
583
+ "Ддᲁ",
584
+ "Ооᲂ",
585
+ "Ссᲃ",
586
+ "Ттᲄᲅ",
587
+ "Ъъᲆ",
588
+ "Ѣѣᲇ",
589
+ "Ṡṡẛ",
590
+ "ᲈꙊꙋ",
591
+ "ſtst",
592
+ ...[
593
+ 8064,
594
+ 8080,
595
+ 8096
596
+ ].flatMap((base) => Array.from({ length: 8 }, (_, k) => String.fromCodePoint(base + k, base + k + 8))),
597
+ "ᾳᾼ",
598
+ "ῃῌ",
599
+ "ῳῼ"
600
+ ];
601
+ let foldGroupOf;
602
+ /** The characters matching `ch` under `i` (with `u`: case folding), `ch` first. */ const variantCache = /* @__PURE__ */ new Map();
603
+ function caseVariants(ch, unicode) {
604
+ const key = `${unicode ? "u" : ""}${ch}`;
605
+ let out = variantCache.get(key);
606
+ if (!out) {
607
+ if (!foldGroupOf) {
608
+ foldGroupOf = /* @__PURE__ */ new Map();
609
+ for (const group of FOLD_GROUPS) for (const member of group) foldGroupOf.set(member, group);
610
+ }
611
+ const single = (x) => unicode ? x.length === String.fromCodePoint(x.codePointAt(0)).length : x.length === 1;
612
+ const found = new Set([ch]);
613
+ const queue = [ch];
614
+ while (queue.length > 0) {
615
+ const x = queue.pop();
616
+ for (const y of [
617
+ x.toLowerCase(),
618
+ x.toUpperCase(),
619
+ ...foldGroupOf.get(x) ?? ""
620
+ ]) if (single(y) && !found.has(y)) {
621
+ found.add(y);
622
+ queue.push(y);
623
+ }
624
+ }
625
+ const re = new RegExp(`^${escapeChar(ch, unicode)}$`, unicode ? "iu" : "i");
626
+ out = [...found].filter((x) => x === ch || re.test(x));
627
+ variantCache.set(key, out);
628
+ }
629
+ return out;
630
+ }
631
+ /** A character as a regex escape (`\uXXXX`, or `\u{…}` with `u` outside the BMP). */ function escapeChar(ch, unicode) {
632
+ const cp = ch.codePointAt(0);
633
+ return cp > 65535 && unicode ? `\\u{${cp.toString(16).toUpperCase()}}` : `\\u${cp.toString(16).toUpperCase().padStart(4, "0")}`;
634
+ }
635
+ /** A character as a member of a character class (escaped where needed). */ function classChar(ch, unicode) {
636
+ const cp = ch.codePointAt(0);
637
+ if (/[\\\][\-^]/.test(ch)) return `\\${ch}`;
638
+ if (cp < 32 || cp > 126) return escapeChar(ch, unicode);
639
+ return ch;
640
+ }
641
+ /** `ch` outside a class, as it matches under `i` (a class of its case variants). */ function caseLiteral(ch, raw, unicode) {
642
+ const variants = caseVariants(ch, unicode);
643
+ return variants.length === 1 ? raw : `[${variants.map((v) => classChar(v, unicode)).join("")}]`;
644
+ }
645
+ /** The ranges of a sorted list of code points, as class members. */ function classRanges(points, unicode) {
646
+ let out = "";
647
+ for (let k = 0; k < points.length;) {
648
+ let end = k;
649
+ while (end + 1 < points.length && points[end + 1] === points[end] + 1) end++;
650
+ const lo = String.fromCodePoint(points[k]);
651
+ const hi = String.fromCodePoint(points[end]);
652
+ out += end === k ? classChar(lo, unicode) : `${classChar(lo, unicode)}-${classChar(hi, unicode)}`;
653
+ k = end + 1;
654
+ }
655
+ return out;
656
+ }
657
+ /** The largest range of non-ASCII characters whose case variants are spelled out. */ const MAX_RANGE = 1024;
658
+ /** What `\w` also matches under `iu` (characters folding to a word character). */ const WORD_FOLDS = "\\u017F\\u212A";
659
+ /**
660
+ * `pattern` with `i` (characters → classes of their case variants) and `s` (`.` → `[\s\S]`)
661
+ * applied (`modifier`: what has no flag-free form, see {@link jsonSchemaPattern}), or
662
+ * `undefined` when it is not parsed.
663
+ */ function translateFlags(pattern, unicode, ignoreCase, dotAll) {
664
+ let out = "";
665
+ let i = 0;
666
+ let modifier = false;
667
+ const n = pattern.length;
668
+ /** The character at `i` (a code point with `u`). */ const charAt = (at) => unicode ? String.fromCodePoint(pattern.codePointAt(at)) : pattern[at];
669
+ /**
670
+ * Reads an escape at `i` (after the backslash): its character (`ch`), or as written (`raw`)
671
+ * with what it needs (`modifier`: no flag-free form under `i`), or `undefined` (not parsed).
672
+ */ const readEscape = (inClass) => {
673
+ const start = i - 1;
674
+ const c = pattern[i];
675
+ if (c === void 0) return;
676
+ i++;
677
+ const raw = () => pattern.slice(start, i);
678
+ switch (c) {
679
+ case "d":
680
+ case "D":
681
+ case "s":
682
+ case "S": return { raw: raw() };
683
+ case "w": return {
684
+ raw: raw(),
685
+ word: true
686
+ };
687
+ case "W": return {
688
+ raw: raw(),
689
+ word: true,
690
+ modifier: inClass && unicode
691
+ };
692
+ case "b": return inClass ? {
693
+ ch: "\b",
694
+ raw: raw()
695
+ } : {
696
+ raw: raw(),
697
+ modifier: unicode
698
+ };
699
+ case "B": return inClass ? void 0 : {
700
+ raw: raw(),
701
+ modifier: unicode
702
+ };
703
+ case "p":
704
+ case "P": {
705
+ if (!unicode) return {
706
+ ch: c,
707
+ raw: raw()
708
+ };
709
+ const end = pattern.indexOf("}", i);
710
+ if (pattern[i] !== "{" || end < 0) return;
711
+ i = end + 1;
712
+ return {
713
+ raw: raw(),
714
+ modifier: true
715
+ };
716
+ }
717
+ case "k": {
718
+ const name = /^<[^>]*>/.exec(pattern.slice(i));
719
+ if (name) {
720
+ i += name[0].length;
721
+ return {
722
+ raw: raw(),
723
+ modifier: true
724
+ };
725
+ }
726
+ return unicode ? void 0 : {
727
+ ch: "k",
728
+ raw: raw()
729
+ };
730
+ }
731
+ case "c": {
732
+ const next = pattern[i];
733
+ if (next && /[A-Za-z]/.test(next)) {
734
+ i++;
735
+ return {
736
+ ch: String.fromCodePoint(next.codePointAt(0) % 32),
737
+ raw: raw()
738
+ };
739
+ }
740
+ return;
741
+ }
742
+ case "x": {
743
+ const hex = pattern.slice(i, i + 2);
744
+ if (!/^[\da-fA-F]{2}$/.test(hex)) return;
745
+ i += 2;
746
+ return {
747
+ ch: String.fromCodePoint(Number.parseInt(hex, 16)),
748
+ raw: raw()
749
+ };
750
+ }
751
+ case "u": {
752
+ if (unicode && pattern[i] === "{") {
753
+ const end = pattern.indexOf("}", i);
754
+ if (end < 0) return;
755
+ const cp = Number.parseInt(pattern.slice(i + 1, end), 16);
756
+ i = end + 1;
757
+ return {
758
+ ch: String.fromCodePoint(cp),
759
+ raw: raw()
760
+ };
761
+ }
762
+ const hex = pattern.slice(i, i + 4);
763
+ if (!/^[\da-fA-F]{4}$/.test(hex)) return;
764
+ i += 4;
765
+ let code = Number.parseInt(hex, 16);
766
+ if (unicode && code >= 55296 && code <= 56319) {
767
+ const low = /^\\u([dD][c-fC-F][\da-fA-F]{2})/.exec(pattern.slice(i));
768
+ if (low) {
769
+ i += 6;
770
+ code = 65536 + (code - 55296 << 10) + (Number.parseInt(low[1], 16) - 56320);
771
+ }
772
+ }
773
+ return {
774
+ ch: String.fromCodePoint(code),
775
+ raw: raw()
776
+ };
777
+ }
778
+ case "0": return /\d/.test(pattern[i] ?? "") ? void 0 : {
779
+ ch: "\0",
780
+ raw: raw()
781
+ };
782
+ case "f":
783
+ case "n":
784
+ case "r":
785
+ case "t":
786
+ case "v": return {
787
+ ch: {
788
+ f: "\f",
789
+ n: "\n",
790
+ r: "\r",
791
+ t: " ",
792
+ v: "\v"
793
+ }[c],
794
+ raw: raw()
795
+ };
796
+ default: {
797
+ if (/[1-9]/.test(c)) {
798
+ if (unicode || !inClass) {
799
+ while (/\d/.test(pattern[i] ?? "")) i++;
800
+ return inClass ? void 0 : {
801
+ raw: raw(),
802
+ modifier: true
803
+ };
804
+ }
805
+ return;
806
+ }
807
+ i = start + 1;
808
+ const ch = charAt(i);
809
+ i += ch.length;
810
+ return {
811
+ ch,
812
+ raw: raw()
813
+ };
814
+ }
815
+ }
816
+ };
817
+ /** Reads a character class at `i` (`[…]`), its characters with their case variants. */ const readClass = () => {
818
+ const start = i;
819
+ i++;
820
+ let negated = "";
821
+ if (pattern[i] === "^") {
822
+ negated = "^";
823
+ i++;
824
+ }
825
+ const items = [];
826
+ while (i < n && pattern[i] !== "]") {
827
+ if (pattern[i] === "\\") {
828
+ i++;
829
+ const esc = readEscape(true);
830
+ if (!esc) return;
831
+ modifier || (modifier = !!esc.modifier && ignoreCase);
832
+ items.push(esc.ch === void 0 ? {
833
+ raw: esc.raw,
834
+ word: esc.word
835
+ } : { ch: esc.ch });
836
+ continue;
837
+ }
838
+ const ch = charAt(i);
839
+ i += ch.length;
840
+ items.push(ch === "-" ? { dash: true } : { ch });
841
+ }
842
+ if (i >= n) return;
843
+ i++;
844
+ if (!ignoreCase) return pattern.slice(start, i);
845
+ const points = /* @__PURE__ */ new Set();
846
+ let body = "";
847
+ const addChar = (ch) => {
848
+ for (const v of caseVariants(ch, unicode)) points.add(v.codePointAt(0));
849
+ };
850
+ for (let k = 0; k < items.length; k++) {
851
+ const item = items[k];
852
+ const dash = items[k + 1];
853
+ const hi = items[k + 2];
854
+ if ("ch" in item && dash && "dash" in dash && hi && "ch" in hi) {
855
+ const lo = item.ch.codePointAt(0);
856
+ const top = hi.ch.codePointAt(0);
857
+ if (top > 127 && top - lo >= MAX_RANGE) {
858
+ modifier = true;
859
+ body += `${classChar(item.ch, unicode)}-${classChar(hi.ch, unicode)}`;
860
+ } else for (let cp = lo; cp <= top; cp++) addChar(String.fromCodePoint(cp));
861
+ k += 2;
862
+ continue;
863
+ }
864
+ if ("dash" in item) points.add(45);
865
+ else if ("raw" in item) {
866
+ body += item.raw;
867
+ if (item.word && unicode && item.raw === "\\w") body += WORD_FOLDS;
868
+ } else addChar(item.ch);
869
+ }
870
+ body += classRanges([...points].sort((a, b) => a - b), unicode);
871
+ return `[${negated}${body}]`;
872
+ };
873
+ while (i < n) {
874
+ const c = pattern[i];
875
+ if (c === "\\") {
876
+ i++;
877
+ const esc = readEscape(false);
878
+ if (!esc) return;
879
+ if (!ignoreCase) out += esc.raw;
880
+ else if (esc.ch !== void 0) out += caseLiteral(esc.ch, esc.raw, unicode);
881
+ else {
882
+ modifier || (modifier = !!esc.modifier);
883
+ out += esc.word && unicode ? esc.raw === "\\w" ? `[\\w${WORD_FOLDS}]` : `[^\\w${WORD_FOLDS}]` : esc.raw;
884
+ }
885
+ continue;
886
+ }
887
+ if (c === "[") {
888
+ const cls = readClass();
889
+ if (cls === void 0) return;
890
+ out += cls;
891
+ continue;
892
+ }
893
+ if (c === "(") {
894
+ if (pattern[i + 1] === "?") {
895
+ const header = /^\(\?(?::|=|!|<=|<!|<[^>]+>)/.exec(pattern.slice(i));
896
+ if (!header) return;
897
+ out += header[0];
898
+ i += header[0].length;
899
+ continue;
900
+ }
901
+ out += c;
902
+ i++;
903
+ continue;
904
+ }
905
+ if (c === "{") {
906
+ const quantifier = /^\{\d+(?:,\d*)?\}/.exec(pattern.slice(i));
907
+ if (quantifier) {
908
+ out += quantifier[0];
909
+ i += quantifier[0].length;
910
+ continue;
911
+ }
912
+ }
913
+ if (c === "." && dotAll) {
914
+ out += "[\\s\\S]";
915
+ i++;
916
+ continue;
917
+ }
918
+ const ch = charAt(i);
919
+ i += ch.length;
920
+ out += ignoreCase && !"^$|)*+?.]}{".includes(ch) ? caseLiteral(ch, ch, unicode) : ch;
921
+ }
922
+ return {
923
+ source: out,
924
+ modifier
925
+ };
135
926
  }
136
927
 
137
928
  //#endregion
@@ -157,7 +948,7 @@
157
948
  * - `keyMask` has a bit (by {@link VALIDATOR_KEYS} index) per validator annotation that is
158
949
  * *effective* on the node and relevant to its def (present; flags: truthy).
159
950
  * `patternShape` has one char per `@expect.pattern` entry: `e` (empty, skipped),
160
- * `n` (checked), `s` (stateful `g` / `y` regex: the check bails to the walk there).
951
+ * `n` (checked).
161
952
  * - `slot`: the site's first K slot (see {@link siteSlotCount}); `slotCount` is the total.
162
953
  * - `EXT`: an anonymous reference into another module's type; bound to that type's own
163
954
  * compiled check (as a template, against the referring node) when it has one, else
@@ -165,7 +956,11 @@
165
956
  * - `INTERP`: a node only known at runtime (e.g. a chained reference into another module's
166
957
  * type): always checked by the interpreted pre-check.
167
958
  */
168
- /** Layout format version; checks of another version are ignored (interpreted). */ const LAYOUT_VERSION = 2;
959
+ /**
960
+ * Layout format version, also of the emitted checks' contract with the runtime (5: 'strip'
961
+ * records `object, key` pairs at every depth); checks of another version are ignored
962
+ * (interpreted).
963
+ */ const LAYOUT_VERSION = 5;
169
964
  const EXT = -1;
170
965
  const INTERP = -2;
171
966
  const D_FINAL = 0;
@@ -176,18 +971,11 @@ const D_INTERSECTION = 4;
176
971
  const D_TUPLE = 5;
177
972
  const D_UNKNOWN = 6;
178
973
  const D_OBJECT_PATTERNS = 7;
179
- /** Def codes of the kinds with `items`, by kind name. */ const ITEMS_KIND_CODES = {
180
- union: D_UNION,
181
- intersection: D_INTERSECTION,
182
- tuple: D_TUPLE
183
- };
184
974
  /** Kind names of the def codes with `items`. */ const ITEMS_KIND_NAMES = {
185
975
  [D_UNION]: "union",
186
976
  [D_INTERSECTION]: "intersection",
187
977
  [D_TUPLE]: "tuple"
188
978
  };
189
- /** Bits of a compiled check's `flags` argument: the pre-check's TOP / IN_UNION, then options. */ const F_TOP = 1;
190
- const F_IN_UNION = 2;
191
979
  const F_ERROR = 4;
192
980
  const F_STRIP = 8;
193
981
  const F_PARTIAL_DEEP = 16;
@@ -249,53 +1037,9 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
249
1037
  */ function siteBits(type, optional) {
250
1038
  return (type === void 0 ? 0 : relevantBits(type)) | (optional ? B_REQUIRED : 0);
251
1039
  }
252
- /**
253
- * Number of K slots a site takes, from its first slot on:
254
- * - INTERP: its interpreted check, then whether its type is a literal;
255
- * - otherwise, for an optional `@meta.required` node ({@link hasRejectSlot}): the node
256
- * (its `null` is rejected unless its type accepts `null`, decided live);
257
- * - then EXT: the bound check of the referenced type, and whether that type is a literal;
258
- * any other site: its annotation values (see {@link keySlots}).
259
- */ function siteSlotCount(site) {
260
- const [, mask, def, shape] = site;
261
- if (def === INTERP) return 2;
262
- let n = (hasRejectSlot(site) ? 1 : 0) + (def === EXT ? 2 : 0);
263
- if (def !== EXT) {
264
- for (let bits = mask & VALUE_BITS; bits !== 0; bits &= bits - 1) n++;
265
- for (const c of shape) if (c === "n") n++;
266
- }
267
- return n;
268
- }
269
1040
  /** An optional node with `@meta.required`: `null` fails unless its type accepts `null`. */ function hasRejectSlot(site) {
270
1041
  return site[0] === 1 && (site[1] & B_REQUIRED) !== 0;
271
1042
  }
272
- /** The K slot of each annotation value of a site whose values start at slot `at`. */ function keySlots(mask, shape, at) {
273
- let k = at;
274
- const next = (b) => (mask & b) === 0 ? -1 : k++;
275
- const minLength = next(B_MIN_LENGTH);
276
- const maxLength = next(B_MAX_LENGTH);
277
- const patterns = [];
278
- for (const c of shape) if (c === "n") patterns.push(k++);
279
- return {
280
- minLength,
281
- maxLength,
282
- patterns,
283
- min: next(B_MIN),
284
- max: next(B_MAX),
285
- exMin: next(B_EX_MIN),
286
- exMax: next(B_EX_MAX)
287
- };
288
- }
289
- /** The child sites of a def. */ function childSites(def) {
290
- switch (def[0]) {
291
- case D_OBJECT: return def[2];
292
- case D_ARRAY: return [def[1]];
293
- case D_UNION:
294
- case D_INTERSECTION:
295
- case D_TUPLE: return def[1];
296
- default: return [];
297
- }
298
- }
299
1043
  /**
300
1044
  * Computes a node's key mask and pattern shape over `relevant` bits, and — when `out` is
301
1045
  * given — writes the normalised annotation values from `out[at]` on (the K slots).
@@ -305,14 +1049,15 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
305
1049
  let mask = 0;
306
1050
  let shape = "";
307
1051
  let k = at;
308
- if (metadata.size === 0) return {
1052
+ const meta = filledMeta(metadata);
1053
+ if (meta === void 0) return {
309
1054
  mask,
310
1055
  shape
311
1056
  };
312
1057
  for (let i = 0; i < VALIDATOR_KEYS.length; i++) {
313
1058
  const b = 1 << i;
314
1059
  if ((relevant & b) === 0) continue;
315
- const raw = metadata.get(VALIDATOR_KEYS[i]);
1060
+ const raw = meta.get(VALIDATOR_KEYS[i]);
316
1061
  if ((b & FLAG_BITS) !== 0) {
317
1062
  if (raw) mask |= b;
318
1063
  continue;
@@ -328,10 +1073,6 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
328
1073
  continue;
329
1074
  }
330
1075
  const re = reader.regex(pattern, flags);
331
- if (re.global || re.sticky) {
332
- shape += "s";
333
- break;
334
- }
335
1076
  shape += "n";
336
1077
  if (out) out[k] = re;
337
1078
  k++;
@@ -364,7 +1105,7 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
364
1105
  *
365
1106
  * A registered entry is also a template: a node referencing a class of another module
366
1107
  * (an `EXT` site) binds that class's layout against itself — its own annotations feed `K`
367
- * — so cross-module references, aliases of imported types and cloned imported props run
1108
+ * — so cross-module references, aliases of imported types and their derived props run
368
1109
  * compiled code whenever their tree matches the referenced type's structure.
369
1110
  *
370
1111
  * The registry is module-local: classes registered with another copy of this runtime
@@ -443,7 +1184,7 @@ let autoCompile = null;
443
1184
  watch(n);
444
1185
  const metadata = n.metadata;
445
1186
  if (!(metadata instanceof AnnotationMap)) return false;
446
- watch(metadata);
1187
+ if (!watchLayer(metadata)) return false;
447
1188
  let k = at;
448
1189
  if (hasRejectSlot(site)) K[k++] = n;
449
1190
  if (d === EXT) return readKeys(metadata, siteBits(void 0, optional === 1), env).mask === mask && bindRuntimeSite(n, k, true);
@@ -499,6 +1240,16 @@ let autoCompile = null;
499
1240
  * when the node is optional; the referring site handles `optional`): the referenced class's
500
1241
  * layout bound against the node when it matches, else the interpreted pre-check.
501
1242
  */ function externalCheck(node, env) {
1243
+ const own = entries.get(node);
1244
+ if (own !== void 0) {
1245
+ if (own.binding) {
1246
+ const fallback = interpreted(node, env);
1247
+ return (value, flags, opts) => (own.fn ?? fallback)(value, flags, opts);
1248
+ }
1249
+ const fn = own.epoch === currentEpoch() ? own.fn : bind(own, own, node, env, false);
1250
+ if (fn !== null) return fn;
1251
+ return interpreted(node, env);
1252
+ }
502
1253
  const entry = templateOf(node);
503
1254
  if (entry !== void 0) {
504
1255
  let binding = templates.get(node);
@@ -526,7 +1277,8 @@ let autoCompile = null;
526
1277
  * (unchained) reference, through aliases of other modules' types.
527
1278
  */ function templateOf(node) {
528
1279
  let ref = node.ref;
529
- for (let hops = 0; hops < 16 && ref !== void 0 && ref.field === ""; hops++) {
1280
+ for (const seen = /* @__PURE__ */ new Set(); ref !== void 0 && ref.field === "" && !seen.has(ref);) {
1281
+ seen.add(ref);
530
1282
  let target;
531
1283
  try {
532
1284
  target = ref.type();
@@ -565,37 +1317,38 @@ function _define_property$1(obj, key, value) {
565
1317
  * after a validator was created are always honoured — the same as the full walk.
566
1318
  *
567
1319
  * Result contract (relative to the full walk over the same node and value):
568
- * - `PASS` — the walk returns `true`, collects no errors and has no side effects other
569
- * than the strips recorded here (see below).
1320
+ * - `PASS` — the walk returns `true`, collects no errors and records the strips recorded
1321
+ * here (see below).
570
1322
  * - `FAIL` — the walk returns `false`. Inside a union, every node the walk would visit
571
- * was visited here too (so a walk that would throw makes this throw first) and the
572
- * walk's only side effects for this node are the strips recorded here. Outside unions
1323
+ * was visited here too (so a walk that would throw makes this throw first). Outside unions
573
1324
  * a `FAIL` always ends in the walk, so it may be returned early.
574
1325
  * - `BAIL` — not decidable here; the caller must run the full walk.
575
1326
  *
576
1327
  * Union branches are tried in declared order, continuing past `FAIL` and stopping
577
1328
  * at `BAIL`, which keeps union results identical to the walk.
578
1329
  *
579
- * `unknownProps: 'strip'`: the walk deletes an object's unknown keys right after the object
580
- * passes (even when an ancestor fails later). This check records those deletions only for
581
- * the top-level object (`pendingKeys`), whose strip is the walk's last read of the input:
582
- * deferring an earlier strip past later reads could be observed by them (a prototype, a
583
- * proxy or an accessor over the stripped object), so a nested object with unknown keys
584
- * bails, as does any object visit once a strip is pending (a later intersection member).
585
- * The recorded keys are deleted, in the walk's order, only when the whole value passes —
586
- * so a `PASS` result still has exactly the walk's side effects, and `FAIL` / `BAIL` leave
1330
+ * `unknownProps: 'strip'`: like the walk, this check records the unknown keys of each object
1331
+ * that passes (`pendingStrips`, in the order the objects complete), drops what a rejected union
1332
+ * branch recorded, and deletes the keys only when the whole value passes. Neither reads a
1333
+ * stripped input, so a `PASS` performs exactly the walk's deletions and `FAIL` / `BAIL` leave
587
1334
  * the value untouched for the walk.
588
1335
  */ const FAIL = 0;
589
1336
  const PASS = 1;
590
1337
  const BAIL = 2;
591
1338
  /** Node is at walk depth 0 (only object props / array & tuple items increase depth). */ const TOP = 1;
592
1339
  /** Node is inside a union branch — failures must be exhaustive (see contract). */ const IN_UNION = 2;
1340
+ /**
1341
+ * Wasted union branches (see {@link unionWaste}) after which a call memoizes nested unions: a
1342
+ * union nested in its own branches, many branches each, is checked again from every branch of
1343
+ * every union above it — (branches)^(depth) work. Ordinary unions waste a few branches at most;
1344
+ * the memo would cost them more than it saves.
1345
+ */ const WASTE_BEFORE_MEMO = 16;
593
1346
  /** Incremented per {@link fastCheckPasses} call; snapshots verified in older calls re-verify. */ let stamp = 0;
594
1347
  /** A 'strip' {@link fastCheckPasses} call is in progress (the pending strips below are its own). */ let stripping = false;
595
1348
  /**
596
- * Unknown keys of the top-level object the walk would delete (`unknownProps: 'strip'`), in
597
- * the walk's deletion order. Deleted when the call passes, dropped otherwise.
598
- */ const pendingKeys = [];
1349
+ * The unknown keys the walk would delete (`unknownProps: 'strip'`): `object, key, …` in the
1350
+ * walk's deletion order. Deleted when the call passes, dropped otherwise.
1351
+ */ const pendingStrips = [];
599
1352
  /**
600
1353
  * `true` only when the full walk over `value` is guaranteed to pass with no errors and
601
1354
  * no side effects other than its 'strip' deletions, which are then performed here, as the
@@ -604,16 +1357,21 @@ const BAIL = 2;
604
1357
  */ function fastCheckPasses(def, value, opts) {
605
1358
  if (opts.unknownProps === "strip") return fastCheckStripping(def, value, opts);
606
1359
  stamp++;
1360
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
1361
+ let passed;
607
1362
  try {
608
- return check(def, value, opts) === PASS;
1363
+ passed = check(def, value, opts) === PASS;
609
1364
  } catch {
610
- return false;
1365
+ passed = false;
611
1366
  }
1367
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
1368
+ return passed;
612
1369
  }
613
1370
  /** {@link fastCheckPasses} for `unknownProps: 'strip'`: performs the recorded strips on a pass. */ function fastCheckStripping(def, value, opts) {
614
1371
  if (stripping) return false;
615
1372
  stamp++;
616
1373
  stripping = true;
1374
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
617
1375
  let passed;
618
1376
  try {
619
1377
  passed = check(def, value, opts) === PASS;
@@ -622,12 +1380,27 @@ const BAIL = 2;
622
1380
  } finally {
623
1381
  stripping = false;
624
1382
  }
1383
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
1384
+ performStrips(pendingStrips, passed);
1385
+ return passed;
1386
+ }
1387
+ /**
1388
+ * Deletes the recorded unknown keys (`unknownProps: 'strip'`; `object, key, …` in deletion order)
1389
+ * when the call `passed`, and empties the list either way. Shared by the walk and the pre-check:
1390
+ * the same deletes in the same order (a failing `delete`, e.g. of a frozen object's key, throws
1391
+ * at the same key).
1392
+ */ function performStrips(strips, passed) {
625
1393
  try {
626
- if (passed) for (const key of pendingKeys) delete value[key];
1394
+ if (passed) for (let i = 0; i < strips.length; i += 2) delete strips[i][strips[i + 1]];
627
1395
  } finally {
628
- pendingKeys.length = 0;
1396
+ strips.length = 0;
629
1397
  }
630
- return passed;
1398
+ }
1399
+ /** The strips `list` recorded after its first `kept` entries (a union's own), or `undefined`. */ function stripsSince(list, kept) {
1400
+ return list.length > kept ? list.slice(kept) : void 0;
1401
+ }
1402
+ /** Records in `target` again the strips a memoized union recorded (see {@link stripsSince}). */ function stripAgain(target, strips) {
1403
+ if (strips !== void 0) for (const entry of strips) target.push(entry);
631
1404
  }
632
1405
  /**
633
1406
  * The pre-check of the root: the type's build-time compiled check when it has one bound to
@@ -637,9 +1410,12 @@ const BAIL = 2;
637
1410
  const compiled = compiledCheckFor(def, COMPILED_ENV);
638
1411
  return compiled === null ? fastCheck(def, value, TOP, opts) : compiled(value, TOP | optionFlags(opts), opts);
639
1412
  }
640
- const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
641
1413
  const regexCache = /* @__PURE__ */ new Map();
642
- /** Compiled `@expect.pattern` regex, cached per (pattern, flags). */ function getRegex(pattern, flags) {
1414
+ /**
1415
+ * Compiled `@expect.pattern` regex, cached per (pattern, flags). Compiled without the
1416
+ * stateful `g` / `y` flags (see {@link statelessRegExp}): every engine tests with it, and
1417
+ * gets the same result on every call.
1418
+ */ function getRegex(pattern, flags) {
643
1419
  let byFlags = regexCache.get(pattern);
644
1420
  if (!byFlags) {
645
1421
  byFlags = /* @__PURE__ */ new Map();
@@ -648,7 +1424,7 @@ const regexCache = /* @__PURE__ */ new Map();
648
1424
  const flagsKey = flags || "";
649
1425
  let regex = byFlags.get(flagsKey);
650
1426
  if (!regex) {
651
- regex = new RegExp(pattern, flags);
1427
+ regex = statelessRegExp(new RegExp(pattern, flags));
652
1428
  byFlags.set(flagsKey, regex);
653
1429
  }
654
1430
  return regex;
@@ -657,7 +1433,8 @@ const regexCache = /* @__PURE__ */ new Map();
657
1433
  * `true` when `def` (an optional field holding `null`) carries `@meta.required` and its
658
1434
  * type does not itself accept `null`. Shared by the walk and the fast pre-check.
659
1435
  */ function rejectsNullAsRequired(def) {
660
- return def.metadata.size > 0 && !!def.metadata.get("meta.required") && !acceptsNull(def);
1436
+ const metadata = filledMeta(def.metadata);
1437
+ return metadata !== void 0 && !!metadata.get("meta.required") && !acceptsNull(def);
661
1438
  }
662
1439
  function acceptsNull(def) {
663
1440
  const type = def.type;
@@ -671,13 +1448,136 @@ function acceptsNull(def) {
671
1448
  return false;
672
1449
  }
673
1450
  /** What compiled checks share with the interpreted pre-check. */ const COMPILED_ENV = {
674
- pk: pendingKeys,
1451
+ pk: pendingStrips,
675
1452
  ho: Object.prototype.hasOwnProperty,
676
1453
  dec: DECIMAL_RE,
677
1454
  regex: getRegex,
678
1455
  interp: fastCheck,
679
- rn: rejectsNullAsRequired
1456
+ rn: rejectsNullAsRequired,
1457
+ m: void 0,
1458
+ n: 0,
1459
+ w: 0,
1460
+ wa: unionWaste,
1461
+ mg: memoGet,
1462
+ ms: memoSet
680
1463
  };
1464
+ /**
1465
+ * A union branch failed after branches of nested unions over objects did (`COMPILED_ENV.n`, the
1466
+ * failed branches of unions over objects inside union branches, moved): work
1467
+ * a later branch of the same outermost union may do again. Past {@link WASTE_BEFORE_MEMO} wasted
1468
+ * branches since the outermost union was entered, the call memoizes the unions over objects it
1469
+ * checks inside union branches (`memoGet` / `memoSet`): each such union is then decided once per
1470
+ * value, flags and options — the same result (a pre-check outcome depends on nothing else: the
1471
+ * input is not changed during the call, see the contract above) and the same strips, recorded
1472
+ * again on a reuse.
1473
+ */ function unionWaste() {
1474
+ if (++COMPILED_ENV.w === WASTE_BEFORE_MEMO && COMPILED_ENV.m === void 0) COMPILED_ENV.m = /* @__PURE__ */ new Map();
1475
+ }
1476
+ /**
1477
+ * The outcome memoized for union `key` (a node, or a compiled union's key) over `value`, or -1;
1478
+ * records the strips the union recorded when it was decided.
1479
+ */ function memoGet(key, value, flags, opts) {
1480
+ const entries = COMPILED_ENV.m.get(value);
1481
+ if (entries !== void 0) {
1482
+ for (let i = 0; i < entries.length; i += 5) if (entries[i] === key && entries[i + 1] === flags && entries[i + 2] === opts) {
1483
+ stripAgain(pendingStrips, entries[i + 4]);
1484
+ return entries[i + 3];
1485
+ }
1486
+ }
1487
+ return -1;
1488
+ }
1489
+ /**
1490
+ * Memoizes the outcome of union `key` over `value` (see {@link memoGet}), entered with `kept`
1491
+ * pending strips (the ones after them are its own).
1492
+ */ function memoSet(key, value, flags, opts, result, kept) {
1493
+ const memo = COMPILED_ENV.m;
1494
+ const strips = stripsSince(pendingStrips, kept);
1495
+ const entries = memo.get(value);
1496
+ if (entries === void 0) memo.set(value, [
1497
+ key,
1498
+ flags,
1499
+ opts,
1500
+ result,
1501
+ strips
1502
+ ]);
1503
+ else entries.push(key, flags, opts, result, strips);
1504
+ }
1505
+ /**
1506
+ * The `fastCheck` union case: branches in declared order (see the contract above). A union over
1507
+ * an object inside a union branch counts its failed branches and, once the call made the memo,
1508
+ * is decided once (see `unionWaste`).
1509
+ */ function fastCheckUnion(def, value, flags, opts) {
1510
+ let nested = false;
1511
+ if ((flags & IN_UNION) === 0) COMPILED_ENV.w = 0;
1512
+ else if (typeof value === "object" && value !== null) {
1513
+ if (COMPILED_ENV.m !== void 0) return memoizedUnion(def, value, flags, opts);
1514
+ nested = true;
1515
+ }
1516
+ const branchFlags = flags | IN_UNION;
1517
+ const kept = pendingStrips.length;
1518
+ for (const item of def.type.items) {
1519
+ const failures = COMPILED_ENV.n;
1520
+ const result = fastCheck(item, value, branchFlags, opts);
1521
+ if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
1522
+ if (COMPILED_ENV.n !== failures) unionWaste();
1523
+ if (nested) COMPILED_ENV.n++;
1524
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1525
+ }
1526
+ return FAIL;
1527
+ }
1528
+ /** {@link fastCheckUnion} of a union plan (the same memo entries: keyed by the node). */ function checkPlanUnion(plan, value, flags, opts) {
1529
+ let nested = false;
1530
+ if ((flags & IN_UNION) === 0) COMPILED_ENV.w = 0;
1531
+ else if (typeof value === "object" && value !== null) {
1532
+ if (COMPILED_ENV.m !== void 0) return memoizedUnion(plan.def, value, flags, opts, plan);
1533
+ nested = true;
1534
+ }
1535
+ const branchFlags = flags | IN_UNION;
1536
+ const kept = pendingStrips.length;
1537
+ for (const child of plan.children) {
1538
+ const failures = COMPILED_ENV.n;
1539
+ const result = checkPlan(child, value, branchFlags, opts);
1540
+ if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
1541
+ if (COMPILED_ENV.n !== failures) unionWaste();
1542
+ if (nested) COMPILED_ENV.n++;
1543
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1544
+ }
1545
+ return FAIL;
1546
+ }
1547
+ /** The branches of a union (see {@link fastCheckUnion}); `nested`: its failed branches count. */ function unionBranches(def, value, flags, opts, nested) {
1548
+ const branchFlags = flags | IN_UNION;
1549
+ const kept = pendingStrips.length;
1550
+ for (const item of def.type.items) {
1551
+ const failures = COMPILED_ENV.n;
1552
+ const result = fastCheck(item, value, branchFlags, opts);
1553
+ if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
1554
+ if (COMPILED_ENV.n !== failures) unionWaste();
1555
+ if (nested) COMPILED_ENV.n++;
1556
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1557
+ }
1558
+ return FAIL;
1559
+ }
1560
+ /** {@link unionBranches} of a union plan. */ function planUnionBranches(plan, value, flags, opts, nested) {
1561
+ const branchFlags = flags | IN_UNION;
1562
+ const kept = pendingStrips.length;
1563
+ for (const child of plan.children) {
1564
+ const failures = COMPILED_ENV.n;
1565
+ const result = checkPlan(child, value, branchFlags, opts);
1566
+ if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
1567
+ if (COMPILED_ENV.n !== failures) unionWaste();
1568
+ if (nested) COMPILED_ENV.n++;
1569
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1570
+ }
1571
+ return FAIL;
1572
+ }
1573
+ /** A union over object `value` inside a union branch, once the call made the memo. */ function memoizedUnion(def, value, flags, opts, plan) {
1574
+ const known = memoGet(def, value, flags, opts);
1575
+ if (known >= 0) return known;
1576
+ const kept = pendingStrips.length;
1577
+ const result = plan === void 0 ? unionBranches(def, value, flags, opts, true) : planUnionBranches(plan, value, flags, opts, true);
1578
+ if (result !== BAIL) memoSet(def, value, flags, opts, result, kept);
1579
+ return result;
1580
+ }
681
1581
  function fastCheck(def, value, flags, opts) {
682
1582
  if (def.optional && (value === void 0 || value === null)) return value === null && rejectsNullAsRequired(def) ? FAIL : PASS;
683
1583
  const type = def.type;
@@ -685,21 +1585,8 @@ function fastCheck(def, value, flags, opts) {
685
1585
  case "": return fastCheckFinal(def, value);
686
1586
  case "object": return fastCheckObject(def, value, flags, opts);
687
1587
  case "array": return fastCheckArray(def, value, flags, opts);
688
- case "union": {
689
- const branchFlags = flags | IN_UNION;
690
- for (const item of type.items) {
691
- const result = fastCheck(item, value, branchFlags, opts);
692
- if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
693
- if (pendingKeys.length > 0) return BAIL;
694
- }
695
- return FAIL;
696
- }
697
- case "intersection":
698
- for (const item of type.items) {
699
- const result = fastCheck(item, value, flags, opts);
700
- if (result !== PASS) return result;
701
- }
702
- return PASS;
1588
+ case "union": return fastCheckUnion(def, value, flags, opts);
1589
+ case "intersection": return fastCheckIntersection(type, value, flags, opts);
703
1590
  case "tuple": {
704
1591
  const items = type.items;
705
1592
  if (!Array.isArray(value) || value.length !== items.length) return FAIL;
@@ -736,8 +1623,9 @@ function fastCheckFinal(def, value) {
736
1623
  /**
737
1624
  * Mirrors Validator.validateUnionConstraints: union-level constraints on the matched value
738
1625
  * (`null` / objects pass; the caller skips literal branches).
739
- */ function fastCheckUnionConstraints(metadata, value) {
740
- if (metadata.size === 0) return PASS;
1626
+ */ function fastCheckUnionConstraints(meta, value) {
1627
+ const metadata = filledMeta(meta);
1628
+ if (metadata === void 0) return PASS;
741
1629
  switch (typeof value) {
742
1630
  case "string": return fastCheckString(metadata, value);
743
1631
  case "number": return fastCheckNumber(metadata, value);
@@ -746,11 +1634,13 @@ function fastCheckFinal(def, value) {
746
1634
  default: return PASS;
747
1635
  }
748
1636
  }
749
- function fastCheckBoolean(metadata, value) {
750
- return metadata.size === 0 ? PASS : booleanConstraints(value, metadata.get("meta.required"));
1637
+ function fastCheckBoolean(meta, value) {
1638
+ const metadata = filledMeta(meta);
1639
+ return metadata === void 0 ? PASS : booleanConstraints(value, metadata.get("meta.required"));
751
1640
  }
752
- function fastCheckString(metadata, value) {
753
- if (metadata.size === 0) return PASS;
1641
+ function fastCheckString(meta, value) {
1642
+ const metadata = filledMeta(meta);
1643
+ if (metadata === void 0) return PASS;
754
1644
  if (metadata.get("meta.required") && value.trim().length === 0) return FAIL;
755
1645
  const minLength = metadata.get("expect.minLength");
756
1646
  if (minLength !== void 0 && value.length < (typeof minLength === "number" ? minLength : minLength.length)) return FAIL;
@@ -759,14 +1649,13 @@ function fastCheckString(metadata, value) {
759
1649
  const patterns = metadata.get("expect.pattern");
760
1650
  if (patterns) for (const { pattern, flags } of patterns) {
761
1651
  if (!pattern) continue;
762
- const regex = getRegex(pattern, flags);
763
- if (regex.global || regex.sticky) return BAIL;
764
- if (!regex.test(value)) return FAIL;
1652
+ if (!getRegex(pattern, flags).test(value)) return FAIL;
765
1653
  }
766
1654
  return PASS;
767
1655
  }
768
- function fastCheckNumber(metadata, value) {
769
- if (metadata.size === 0) return PASS;
1656
+ function fastCheckNumber(meta, value) {
1657
+ const metadata = filledMeta(meta);
1658
+ if (metadata === void 0) return PASS;
770
1659
  return numberConstraints(value, metadata.get("expect.int"), metadata.get("expect.min"), metadata.get("expect.max"), metadata.get("expect.exclusiveMin"), metadata.get("expect.exclusiveMax"));
771
1660
  }
772
1661
  function booleanConstraints(value, required) {
@@ -783,6 +1672,16 @@ function numberConstraints(value, int, min, max, exMin, exMax) {
783
1672
  /** `@expect.minLength` / `@expect.maxLength` (strings and arrays). */ function lengthFails(length, minLength, maxLength) {
784
1673
  return minLength !== void 0 && length < (typeof minLength === "number" ? minLength : minLength.length) || maxLength !== void 0 && length > (typeof maxLength === "number" ? maxLength : maxLength.length);
785
1674
  }
1675
+ /**
1676
+ * {@link fastCheck} of an intersection (a function of its own: `fastCheck` stays small, so the
1677
+ * engine inlines it in the hot object and prop checks).
1678
+ */ function fastCheckIntersection(type, value, flags, opts) {
1679
+ for (const item of type.items) {
1680
+ const result = fastCheck(item, value, flags, opts);
1681
+ if (result !== PASS) return result;
1682
+ }
1683
+ return PASS;
1684
+ }
786
1685
  /** Array constraints; duplicate detection (`uniqueItems`) is left to the walk. */ function arrayConstraints(length, minLength, maxLength, uniqueItems) {
787
1686
  if (lengthFails(length, minLength, maxLength)) return FAIL;
788
1687
  return uniqueItems ? BAIL : PASS;
@@ -791,7 +1690,6 @@ function fastCheckObject(def, value, flags, opts) {
791
1690
  if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
792
1691
  const type = def.type;
793
1692
  if (type.propsPatterns.length > 0) return BAIL;
794
- if (pendingKeys.length > 0) return BAIL;
795
1693
  const unknownProps = opts.unknownProps;
796
1694
  const inUnion = (flags & IN_UNION) !== 0;
797
1695
  if (unknownProps === "error" && !inUnion && hasUnknownKey(type.props, value)) return FAIL;
@@ -810,19 +1708,14 @@ function fastCheckObject(def, value, flags, opts) {
810
1708
  }
811
1709
  }
812
1710
  if (result !== PASS) return result;
813
- if (unknownProps === "strip") return pendStrips(type.props, value, flags);
1711
+ if (unknownProps === "strip") {
1712
+ pendStrips(type.props, value);
1713
+ return PASS;
1714
+ }
814
1715
  return unknownProps === "error" && inUnion && hasUnknownKey(type.props, value) ? FAIL : PASS;
815
1716
  }
816
- /**
817
- * Records the unknown keys of a passing top-level object: the walk deletes them at this
818
- * point, after its last read of the input. A nested object's strip would be followed by
819
- * more reads, so it is left to the walk.
820
- */ function pendStrips(props, value, flags) {
821
- for (const key of Object.keys(value)) if (isUnknownKey(props, key)) {
822
- if ((flags & TOP) === 0) return BAIL;
823
- pendingKeys.push(key);
824
- }
825
- return PASS;
1717
+ /** Records the unknown keys of a passing object (see `pendingStrips`). */ function pendStrips(props, value) {
1718
+ for (const key of Object.keys(value)) if (isUnknownKey(props, key)) pendingStrips.push(value, key);
826
1719
  }
827
1720
  /** `true` when `value` has a key the walk treats as unknown. */ function hasUnknownKey(props, value) {
828
1721
  for (const key of Object.keys(value)) if (isUnknownKey(props, key)) return true;
@@ -834,8 +1727,8 @@ function fastCheckObject(def, value, flags, opts) {
834
1727
  }
835
1728
  function fastCheckArray(def, value, flags, opts) {
836
1729
  if (!Array.isArray(value)) return FAIL;
837
- const metadata = def.metadata;
838
- if (metadata.size > 0) {
1730
+ const metadata = filledMeta(def.metadata);
1731
+ if (metadata !== void 0) {
839
1732
  const result = fastCheckArrayConstraints(metadata, value);
840
1733
  if (result !== PASS) return result;
841
1734
  }
@@ -977,12 +1870,12 @@ function planFor(def) {
977
1870
  }
978
1871
  }
979
1872
  /** Brings the annotation values up to date (once per call, when a constraint is read). */ function refreshMeta(plan) {
980
- const metadata = plan.metadata;
981
- if (!(metadata.size === 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === void 0 && plan.m4 === void 0 : metadata.get(plan.k0) === plan.m0 && (plan.k1 === void 0 || metadata.get(plan.k1) === plan.m1) && (plan.k2 === void 0 || metadata.get(plan.k2) === plan.m2) && (plan.k3 === void 0 || metadata.get(plan.k3) === plan.m3) && (plan.k4 === void 0 || metadata.get(plan.k4) === plan.m4))) snapshotMeta(plan);
1873
+ const metadata = filledMeta(plan.metadata);
1874
+ if (!(metadata === void 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === void 0 && plan.m4 === void 0 : metadata.get(plan.k0) === plan.m0 && (plan.k1 === void 0 || metadata.get(plan.k1) === plan.m1) && (plan.k2 === void 0 || metadata.get(plan.k2) === plan.m2) && (plan.k3 === void 0 || metadata.get(plan.k3) === plan.m3) && (plan.k4 === void 0 || metadata.get(plan.k4) === plan.m4))) snapshotMeta(plan);
982
1875
  plan.metaStamp = stamp;
983
1876
  }
984
1877
  function snapshotMeta(plan) {
985
- const metadata = plan.metadata;
1878
+ const metadata = readable(plan.metadata);
986
1879
  plan.m0 = metadata.get(plan.k0);
987
1880
  plan.m1 = metadata.get(plan.k1);
988
1881
  plan.m2 = metadata.get(plan.k2);
@@ -1085,14 +1978,7 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
1085
1978
  case OP_NUMBER: return typeof value === "number" && Number.isFinite(value) ? checkNumber(plan, value) : FAIL;
1086
1979
  case OP_OBJECT: return checkObject(plan, value, flags, opts);
1087
1980
  case OP_ARRAY: return checkArray(plan, value, flags, opts);
1088
- case OP_UNION: {
1089
- const branchFlags = flags | IN_UNION;
1090
- for (const child of plan.children) {
1091
- const result = checkPlan(child, value, branchFlags, opts);
1092
- if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
1093
- }
1094
- return FAIL;
1095
- }
1981
+ case OP_UNION: return checkPlanUnion(plan, value, flags, opts);
1096
1982
  case OP_BOOLEAN:
1097
1983
  if (typeof value !== "boolean") return FAIL;
1098
1984
  if (plan.metaStamp !== stamp) refreshMeta(plan);
@@ -1114,16 +2000,13 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
1114
2000
  if (!pattern) continue;
1115
2001
  let entry = plan.regexes[i];
1116
2002
  if (entry === void 0 || entry.pattern !== pattern || entry.flags !== flags) {
1117
- const re = getRegex(pattern, flags);
1118
2003
  entry = {
1119
2004
  pattern,
1120
2005
  flags,
1121
- re,
1122
- stateful: re.global || re.sticky
2006
+ re: getRegex(pattern, flags)
1123
2007
  };
1124
2008
  plan.regexes[i] = entry;
1125
2009
  }
1126
- if (entry.stateful) return BAIL;
1127
2010
  if (!entry.re.test(value)) return FAIL;
1128
2011
  }
1129
2012
  }
@@ -1182,7 +2065,9 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
1182
2065
  const byKey = plan.byKey;
1183
2066
  for (const key of Object.keys(value)) {
1184
2067
  const known = byKey.get(key);
1185
- if (known === void 0 || known.op === OP_PHANTOM) return unknownProps === "error" ? FAIL : BAIL;
2068
+ if (known !== void 0 && known.op !== OP_PHANTOM) continue;
2069
+ if (unknownProps === "error") return FAIL;
2070
+ pendingStrips.push(value, key);
1186
2071
  }
1187
2072
  }
1188
2073
  return PASS;
@@ -1262,6 +2147,16 @@ function _define_property(obj, key, value) {
1262
2147
  if (details?.length) error.details = details;
1263
2148
  errors.push(error);
1264
2149
  if (errors.length >= this.opts.errorLimit) this.limitExceeded = true;
2150
+ return error;
2151
+ }
2152
+ /** Adds `error`, already made, to the errors of the current level (as {@link error} does). */ report(error) {
2153
+ let errors = this.stackErrors[this.stackErrors.length - 1];
2154
+ if (!errors) if (this.stackErrors.length > 0) {
2155
+ errors = [];
2156
+ this.stackErrors[this.stackErrors.length - 1] = errors;
2157
+ } else errors = this.errors;
2158
+ errors.push(error);
2159
+ if (errors.length >= this.opts.errorLimit) this.limitExceeded = true;
1265
2160
  }
1266
2161
  throw() {
1267
2162
  throw new ValidatorError(this.errors);
@@ -1283,8 +2178,13 @@ function _define_property(obj, key, value) {
1283
2178
  this.limitExceeded = false;
1284
2179
  if (this.shortcuts && !this.opts.skipList && typeof this.opts.partial !== "function" && fastCheckPasses(this.def, value, this.opts)) return true;
1285
2180
  this.context = context;
2181
+ this.unionDepth = 0;
2182
+ this.unionMemo = void 0;
2183
+ if (this.strips.length > 0) this.strips.length = 0;
1286
2184
  const passed = this.validateSafe(this.def, value);
1287
2185
  this.context = void 0;
2186
+ if (this.unionMemo !== void 0) this.unionMemo = void 0;
2187
+ if (this.strips.length > 0) performStrips(this.strips, passed);
1288
2188
  if (!passed) {
1289
2189
  if (safe) return false;
1290
2190
  this.throw();
@@ -1299,16 +2199,26 @@ function _define_property(obj, key, value) {
1299
2199
  */ get shortcuts() {
1300
2200
  return this.constructor === Validator && !this.hasPlugins && !this.hasReplace;
1301
2201
  }
1302
- validateSafe(def, value) {
2202
+ /** Validates `value` against `def` (after `replace`, `optional` and the plugins). */ validateSafe(def, value) {
1303
2203
  if (this.limitExceeded) return false;
1304
- if (this.hasReplace) {
1305
- let replaced = this.replaceCache.get(def);
1306
- if (replaced === void 0) {
1307
- replaced = this.opts.replace(def, this.buildPath());
1308
- this.replaceCache.set(def, replaced);
2204
+ if (this.hasReplace) def = this.replaced(def);
2205
+ if (def.optional && (value === void 0 || value === null)) {
2206
+ if (value === null && rejectsNullAsRequired(def)) {
2207
+ this.error(requiredMessage(def));
2208
+ return false;
1309
2209
  }
1310
- def = replaced;
2210
+ return true;
1311
2211
  }
2212
+ if (this.hasPlugins) {
2213
+ const decided = this.preCheck(def, value);
2214
+ if (decided !== void 0) return decided;
2215
+ }
2216
+ return this.validateAnnotatedType(def, value);
2217
+ }
2218
+ /**
2219
+ * What {@link validateSafe} decides of `def` (replaced) before its own validation: an
2220
+ * optional `def` passes `undefined` / `null`, a plugin may decide — `undefined` to go on.
2221
+ */ preCheck(def, value) {
1312
2222
  if (def.optional && (value === void 0 || value === null)) {
1313
2223
  if (value === null && rejectsNullAsRequired(def)) {
1314
2224
  this.error(requiredMessage(def));
@@ -1316,11 +2226,55 @@ function _define_property(obj, key, value) {
1316
2226
  }
1317
2227
  return true;
1318
2228
  }
1319
- if (this.hasPlugins) for (const plugin of this.opts.plugins) {
1320
- const result = plugin(this, def, value);
1321
- if (result === false || result === true) return result;
2229
+ if (this.hasPlugins) {
2230
+ const ctx = this.pluginCtx ?? (this.pluginCtx = this.pluginContext());
2231
+ for (const plugin of this.opts.plugins) {
2232
+ const result = plugin(ctx, def, value);
2233
+ if (result === false || result === true) return result;
2234
+ }
2235
+ }
2236
+ }
2237
+ /**
2238
+ * The plugins' view of this validator: its state read live; `validateAnnotatedType` drops the
2239
+ * strips a failed call recorded (a failed validation at any level strips nothing).
2240
+ */ pluginContext() {
2241
+ return Object.defineProperties({
2242
+ validateAnnotatedType: (def, value) => {
2243
+ const kept = this.strips.length;
2244
+ const passed = this.validateAnnotatedType(def, value);
2245
+ if (!passed && this.strips.length !== kept) this.strips.length = kept;
2246
+ return passed;
2247
+ },
2248
+ error: (message, path, details) => this.error(message, path, details)
2249
+ }, {
2250
+ opts: {
2251
+ get: () => this.opts,
2252
+ enumerable: true
2253
+ },
2254
+ path: {
2255
+ get: () => this.path,
2256
+ enumerable: true
2257
+ },
2258
+ root: {
2259
+ get: () => this.root,
2260
+ enumerable: true
2261
+ },
2262
+ context: {
2263
+ get: () => this.context,
2264
+ set: (context) => {
2265
+ this.context = context;
2266
+ },
2267
+ enumerable: true
2268
+ }
2269
+ });
2270
+ }
2271
+ /** `def` as the `replace` option replaces it at the current path (memoized per node). */ replaced(def) {
2272
+ let replaced = this.replaceCache.get(def);
2273
+ if (replaced === void 0) {
2274
+ replaced = this.opts.replace(def, this.buildPath());
2275
+ this.replaceCache.set(def, replaced);
1322
2276
  }
1323
- return this.validateAnnotatedType(def, value);
2277
+ return replaced;
1324
2278
  }
1325
2279
  get path() {
1326
2280
  return this.buildPath();
@@ -1348,29 +2302,84 @@ function _define_property(obj, key, value) {
1348
2302
  if (item.optional || type.kind !== "" || type.value === void 0 || type.designType === "phantom") break;
1349
2303
  if (type.value === value) return true;
1350
2304
  }
2305
+ let nested = false;
2306
+ let path;
2307
+ if (this.unionDepth > 0) {
2308
+ if (typeof value === "object" && value !== null) {
2309
+ if (this.unionMemo !== void 0) {
2310
+ path = this.buildPath();
2311
+ const known = this.decided(def, value, path);
2312
+ if (known !== void 0) {
2313
+ if (known.error === void 0) {
2314
+ stripAgain(this.strips, known.strips);
2315
+ return this.validateUnionConstraints(def, known.item, value);
2316
+ }
2317
+ this.report(known.error);
2318
+ return false;
2319
+ }
2320
+ }
2321
+ nested = true;
2322
+ }
2323
+ } else this.wasted = 0;
2324
+ const kept = this.strips.length;
1351
2325
  let details;
1352
2326
  for (const item of items) {
1353
2327
  this.stackErrors.push(null);
1354
- if (this.validateSafe(item, value)) {
2328
+ const failures = this.nestedFailures;
2329
+ this.unionDepth++;
2330
+ const passed = this.validateSafe(item, value);
2331
+ this.unionDepth--;
2332
+ if (passed) {
1355
2333
  this.stackErrors.pop();
2334
+ if (path !== void 0) this.decide(def, value, path, kept, item, void 0);
1356
2335
  return this.validateUnionConstraints(def, item, value);
1357
2336
  }
2337
+ if (this.strips.length !== kept) this.strips.length = kept;
1358
2338
  const branchErrors = this.stackErrors.pop();
1359
2339
  if (this.limitExceeded) this.limitExceeded = false;
2340
+ if (this.nestedFailures !== failures) this.wasteBranch();
2341
+ if (nested) this.nestedFailures++;
1360
2342
  if (branchErrors) if (details) for (const err of branchErrors) details.push(err);
1361
2343
  else details = branchErrors;
1362
2344
  }
1363
2345
  const expected = items.map((item, i) => `[${item.type.kind || item.type.designType}(${i})]`).join(", ");
1364
- this.error(`Value does not match any of the allowed types: ${expected}`, void 0, details);
2346
+ const error = this.error(`Value does not match any of the allowed types: ${expected}`, void 0, details);
2347
+ if (path !== void 0) this.decide(def, value, path, kept, void 0, error);
1365
2348
  return false;
1366
2349
  }
2350
+ /** A union branch failed after branches of nested unions over objects did (see `unionMemo`). */ wasteBranch() {
2351
+ if (++this.wasted === WASTE_BEFORE_MEMO && this.unionMemo === void 0) this.unionMemo = /* @__PURE__ */ new Map();
2352
+ }
2353
+ /** The outcome this call recorded for union `def` over `value` at `path` (see `unionMemo`). */ decided(def, value, path) {
2354
+ const outcomes = this.unionMemo.get(value);
2355
+ if (outcomes !== void 0) {
2356
+ const { unknownProps } = this.opts;
2357
+ for (const outcome of outcomes) if (outcome.def === def && outcome.path === path && outcome.unknownProps === unknownProps) return outcome;
2358
+ }
2359
+ }
2360
+ /**
2361
+ * Records the outcome of union `def` over `value` at `path`, entered with `kept` strips (the
2362
+ * ones after them are its own).
2363
+ */ decide(def, value, path, kept, item, error) {
2364
+ const outcome = {
2365
+ def,
2366
+ path,
2367
+ unknownProps: this.opts.unknownProps,
2368
+ item,
2369
+ error,
2370
+ strips: stripsSince(this.strips, kept)
2371
+ };
2372
+ const outcomes = this.unionMemo.get(value);
2373
+ if (outcomes === void 0) this.unionMemo.set(value, [outcome]);
2374
+ else outcomes.push(outcome);
2375
+ }
1367
2376
  /**
1368
2377
  * Constraints annotated on the union itself (`@expect.min 0` on `number | null`)
1369
2378
  * apply to the non-null value that matched `branch`, on top of the branch's own.
1370
2379
  * A literal branch (an enum value) is exempt: its value is fixed.
1371
2380
  */ validateUnionConstraints(def, branch, value) {
1372
2381
  const metadata = def.metadata;
1373
- if (metadata.size === 0 || branch.type.value !== void 0) return true;
2382
+ if (metaEmpty(metadata) || branch.type.value !== void 0) return true;
1374
2383
  switch (typeof value) {
1375
2384
  case "string": return this.validateStringConstraints(metadata, value);
1376
2385
  case "number": return this.validateNumberConstraints(metadata, value);
@@ -1381,10 +2390,28 @@ function _define_property(obj, key, value) {
1381
2390
  default: return true;
1382
2391
  }
1383
2392
  }
1384
- validateIntersection(def, value) {
2393
+ /** Every member must pass, each on its own (JSON Schema `allOf`). */ validateIntersection(def, value) {
1385
2394
  for (const item of def.type.items) if (!this.validateSafe(item, value)) return false;
1386
2395
  return true;
1387
2396
  }
2397
+ /**
2398
+ * An unknown key (`unknownProps`): 'error' reports it, 'strip' adds it to the keys to strip
2399
+ * (returned; recorded in `strips` once the object passed).
2400
+ */ unknownKey(key, keysToStrip) {
2401
+ if (this.opts.unknownProps === "error") {
2402
+ this.push(key);
2403
+ this.error(`Unexpected property`);
2404
+ this.pop(true);
2405
+ } else if (this.opts.unknownProps === "strip") (keysToStrip ?? (keysToStrip = [])).push(key);
2406
+ return keysToStrip;
2407
+ }
2408
+ /** The `skipList` keys of the object at the current path. */ skipListHere() {
2409
+ if (!this.opts.skipList) return;
2410
+ let skipList;
2411
+ const path = this.depth > 0 ? `${this.buildPath()}.` : "";
2412
+ for (const item of this.opts.skipList) if (item.startsWith(path)) (skipList ?? (skipList = /* @__PURE__ */ new Set())).add(item.slice(path.length));
2413
+ return skipList;
2414
+ }
1388
2415
  validateTuple(def, value) {
1389
2416
  if (!Array.isArray(value) || value.length !== def.type.items.length) {
1390
2417
  this.error(`Expected array of length ${def.type.items.length}`);
@@ -1407,7 +2434,7 @@ function _define_property(obj, key, value) {
1407
2434
  this.error("Expected array");
1408
2435
  return false;
1409
2436
  }
1410
- if (def.metadata.size > 0 && !this.validateArrayConstraints(def.metadata, value, def.type.of)) return false;
2437
+ if (!metaEmpty(def.metadata) && !this.validateArrayConstraints(def.metadata, value, def.type.of)) return false;
1411
2438
  let i = 0;
1412
2439
  let passed = true;
1413
2440
  for (const item of value) {
@@ -1421,7 +2448,8 @@ function _define_property(obj, key, value) {
1421
2448
  }
1422
2449
  return passed;
1423
2450
  }
1424
- /** `@expect.minLength` / `maxLength` / `array.uniqueItems` checks for an array value. */ validateArrayConstraints(metadata, value, of) {
2451
+ /** `@expect.minLength` / `maxLength` / `array.uniqueItems` checks for an array value. */ validateArrayConstraints(meta, value, of) {
2452
+ const metadata = readable(meta);
1425
2453
  const minLength = metadata.get("expect.minLength");
1426
2454
  if (minLength !== void 0) {
1427
2455
  const length = typeof minLength === "number" ? minLength : minLength.length;
@@ -1444,14 +2472,11 @@ function _define_property(obj, key, value) {
1444
2472
  if (uniqueItems) {
1445
2473
  const separator = "▼↩";
1446
2474
  const seen = /* @__PURE__ */ new Set();
1447
- const keyProps = /* @__PURE__ */ new Set();
1448
- if (of?.type.kind === "object") {
1449
- for (const [key, val] of of.type.props.entries()) if (val.metadata.get("expect.array.key")) keyProps.add(key);
1450
- }
2475
+ const keyProps = arrayKeyProps(of);
1451
2476
  for (let idx = 0; idx < value.length; idx++) {
1452
2477
  const item = value[idx];
1453
2478
  let key;
1454
- if (keyProps.size > 0) {
2479
+ if (keyProps.length > 0) {
1455
2480
  key = "";
1456
2481
  for (const prop of keyProps) key += JSON.stringify(item[prop]) + separator;
1457
2482
  } else key = JSON.stringify(item);
@@ -1473,15 +2498,7 @@ function _define_property(obj, key, value) {
1473
2498
  }
1474
2499
  let passed = true;
1475
2500
  let keysToStrip;
1476
- let skipList;
1477
- if (this.opts.skipList) {
1478
- const path = this.depth > 0 ? `${this.buildPath()}.` : "";
1479
- for (const item of this.opts.skipList) if (item.startsWith(path)) {
1480
- const key = item.slice(path.length);
1481
- if (!skipList) skipList = /* @__PURE__ */ new Set();
1482
- skipList.add(key);
1483
- }
1484
- }
2501
+ const skipList = this.opts.skipList ? this.skipListHere() : void 0;
1485
2502
  let partialFunctionMatched = false;
1486
2503
  if (typeof this.opts.partial === "function") partialFunctionMatched = this.opts.partial(def, this.buildPath());
1487
2504
  for (const [key, item] of def.type.props.entries()) {
@@ -1512,11 +2529,13 @@ function _define_property(obj, key, value) {
1512
2529
  if (matched.length > 0) {
1513
2530
  this.push(key);
1514
2531
  let keyPassed = false;
2532
+ const kept = this.strips.length;
1515
2533
  for (const { def: propDef } of matched) {
1516
2534
  if (this.validateSafe(propDef, value[key])) {
1517
2535
  keyPassed = true;
1518
2536
  break;
1519
2537
  }
2538
+ if (this.strips.length !== kept) this.strips.length = kept;
1520
2539
  this.clear();
1521
2540
  }
1522
2541
  if (!keyPassed) {
@@ -1525,19 +2544,16 @@ function _define_property(obj, key, value) {
1525
2544
  passed = false;
1526
2545
  if (this.limitExceeded) return false;
1527
2546
  } else this.pop(false);
1528
- } else if (this.opts.unknownProps === "error") {
1529
- this.push(key);
1530
- this.error(`Unexpected property`);
1531
- this.pop(true);
1532
- if (this.limitExceeded) return false;
1533
- passed = false;
1534
- } else if (this.opts.unknownProps === "strip") {
1535
- if (!keysToStrip) keysToStrip = [];
1536
- keysToStrip.push(key);
2547
+ } else {
2548
+ keysToStrip = this.unknownKey(key, keysToStrip);
2549
+ if (this.opts.unknownProps === "error") {
2550
+ if (this.limitExceeded) return false;
2551
+ passed = false;
2552
+ }
1537
2553
  }
1538
2554
  }
1539
2555
  }
1540
- if (passed && keysToStrip) for (const key of keysToStrip) delete value[key];
2556
+ if (passed && keysToStrip !== void 0) for (const key of keysToStrip) this.strips.push(value, key);
1541
2557
  return passed;
1542
2558
  }
1543
2559
  validatePrimitive(def, value) {
@@ -1604,8 +2620,9 @@ function _define_property(obj, key, value) {
1604
2620
  validateString(def, value) {
1605
2621
  return this.validateStringConstraints(def.metadata, value);
1606
2622
  }
1607
- /** `@meta.required` / `@expect.minLength` / `maxLength` / `pattern` checks for a string value. */ validateStringConstraints(metadata, value) {
1608
- if (metadata.size === 0) return true;
2623
+ /** `@meta.required` / `@expect.minLength` / `maxLength` / `pattern` checks for a string value. */ validateStringConstraints(meta, value) {
2624
+ const metadata = filledMeta(meta);
2625
+ if (metadata === void 0) return true;
1609
2626
  const filled = metadata.get("meta.required");
1610
2627
  if (filled) {
1611
2628
  if (value.trim().length === 0) {
@@ -1645,8 +2662,9 @@ function _define_property(obj, key, value) {
1645
2662
  validateNumber(def, value) {
1646
2663
  return this.validateNumberConstraints(def.metadata, value);
1647
2664
  }
1648
- /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */ validateNumberConstraints(metadata, value) {
1649
- if (metadata.size === 0) return true;
2665
+ /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */ validateNumberConstraints(meta, value) {
2666
+ const metadata = filledMeta(meta);
2667
+ if (metadata === void 0) return true;
1650
2668
  const int = metadata.get("expect.int");
1651
2669
  if (int && value % 1 !== 0) {
1652
2670
  const message = typeof int === "object" && int.message ? int.message : `Expected integer, got ${value}`;
@@ -1683,8 +2701,9 @@ function _define_property(obj, key, value) {
1683
2701
  validateBoolean(def, value) {
1684
2702
  return this.validateBooleanConstraints(def.metadata, value);
1685
2703
  }
1686
- /** `@meta.required` check for a boolean value (must be `true`). */ validateBooleanConstraints(metadata, value) {
1687
- if (metadata.size === 0) return true;
2704
+ /** `@meta.required` check for a boolean value (must be `true`). */ validateBooleanConstraints(meta, value) {
2705
+ const metadata = filledMeta(meta);
2706
+ if (metadata === void 0) return true;
1688
2707
  const filled = metadata.get("meta.required");
1689
2708
  if (filled) {
1690
2709
  if (value !== true) {
@@ -1707,12 +2726,36 @@ function _define_property(obj, key, value) {
1707
2726
  _define_property(this, "depth", void 0);
1708
2727
  _define_property(this, "limitExceeded", void 0);
1709
2728
  _define_property(this, "context", void 0);
2729
+ /**
2730
+ * The unions over objects this call decided inside union branches (value → outcomes). A union
2731
+ * nested in its own branches, many branches each, is reached again with the same value and path
2732
+ * from every branch of every union above it — (branches)^(depth) work. The memo is made once
2733
+ * the call has wasted {@link WASTE_BEFORE_MEMO} union branches (failed after branches of nested
2734
+ * unions over objects failed) since the outermost union, as in the pre-check — ordinary walks
2735
+ * never make it. It decides each such union once, with the same result and the same error object
2736
+ * (both depend only on these, the options and the input, which the walk never changes), and
2737
+ * records the same strips again.
2738
+ */ _define_property(this, "unionMemo", void 0);
2739
+ /** Union branches being checked (`> 0`: inside a union branch). */ _define_property(this, "unionDepth", void 0);
2740
+ /** Failed branches of unions over objects inside union branches (see `unionMemo`). */ _define_property(this, "nestedFailures", void 0);
2741
+ /** Wasted union branches since the outermost union was entered (see `unionMemo`). */ _define_property(this, "wasted", void 0);
2742
+ /**
2743
+ * `unknownProps: 'strip'`: the unknown keys of the objects that passed (`object, key, …`), in the
2744
+ * order the objects completed, then in key order. A rejected union branch, pattern property
2745
+ * attempt or plugin sub-validation drops what it recorded; the keys are deleted once the whole
2746
+ * call passes (`performStrips`).
2747
+ */ _define_property(this, "strips", void 0);
2748
+ /** The context the plugins get (see {@link pluginContext}), made on the first plugin call. */ _define_property(this, "pluginCtx", void 0);
1710
2749
  this.def = def;
1711
2750
  this.errors = [];
1712
2751
  this.stackErrors = [];
1713
2752
  this.pathSegments = [];
1714
2753
  this.depth = 0;
1715
2754
  this.limitExceeded = false;
2755
+ this.unionDepth = 0;
2756
+ this.nestedFailures = 0;
2757
+ this.wasted = 0;
2758
+ this.strips = [];
1716
2759
  this.opts = {
1717
2760
  partial: false,
1718
2761
  unknownProps: "error",
@@ -1777,12 +2820,12 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1777
2820
  */ function createAnnotatedTypeNode(type, metadata = new AnnotationMap(), opts) {
1778
2821
  return {
1779
2822
  __is_atscript_annotated_type: true,
1780
- type,
1781
2823
  metadata,
2824
+ type,
1782
2825
  validator: validatorMethod,
2826
+ ref: opts?.ref,
1783
2827
  id: opts?.id,
1784
- optional: opts?.optional,
1785
- ref: opts?.ref
2828
+ optional: opts?.optional
1786
2829
  };
1787
2830
  }
1788
2831
  /** A new tracked metadata map holding `entries` (see {@link createAnnotatedTypeNode}). */ function createMetadataMap(entries) {
@@ -1813,61 +2856,23 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1813
2856
  /**
1814
2857
  * Standalone annotate function that handles both replace and append (array) strategies.
1815
2858
  * Used by the handle's .annotate() method and by generated mutation statements.
2859
+ *
2860
+ * A layered map (a reference, an override, a merged field: see `layers.ts`) appends after the
2861
+ * values its bases give.
1816
2862
  */ function annotate(metadata, key, value, asArray) {
1817
2863
  if (!metadata) return;
1818
- if (asArray) if (metadata.has(key)) {
1819
- const a = metadata.get(key);
1820
- if (Array.isArray(a)) {
1821
- a.push(value);
1822
- if (isValidatorKey(key)) touched(metadata);
1823
- } else metadata.set(key, [a, value]);
1824
- } else metadata.set(key, [value]);
2864
+ if (asArray && metadata instanceof LayerMap) {
2865
+ annotateLayer(metadata, key, value);
2866
+ return;
2867
+ }
2868
+ if (asArray) if (metadata.has(key)) appendOwn(metadata, key, metadata.get(key), value);
2869
+ else metadata.set(key, [value]);
1825
2870
  else metadata.set(key, value);
1826
2871
  }
1827
- /**
1828
- * Clones a property's type tree in-place so mutations don't leak to shared refs.
1829
- * Used by mutating annotate codegen when paths cross ref boundaries.
1830
- */ function cloneRefProp(parentType, propName) {
1831
- if (parentType.kind !== "object") return;
1832
- const objType = parentType;
1833
- const existing = objType.props.get(propName);
1834
- if (!existing) return;
1835
- objType.props.set(propName, cloneNode(existing, cloneTypeDef(existing.type)));
1836
- }
1837
- /** A copy of `node` (own metadata map) over `type`. */ function cloneNode(node, type) {
1838
- return createAnnotatedTypeNode(type, createMetadataMap(node.metadata), {
1839
- id: node.id,
1840
- optional: node.optional,
1841
- ref: node.ref
1842
- });
1843
- }
1844
- function cloneTypeDef(type) {
1845
- if (type.kind === "object") {
1846
- const obj = type;
1847
- const clone = createObjectTypeDef(new Set(obj.tags), [...obj.propsPatterns]);
1848
- for (const [k, v] of obj.props) clone.props.set(k, cloneNode(v, v.type));
1849
- return clone;
1850
- }
1851
- if (type.kind === "array") {
1852
- const arr = type;
1853
- return {
1854
- kind: "array",
1855
- of: arr.of,
1856
- tags: new Set(arr.tags)
1857
- };
1858
- }
1859
- if (type.kind === "union" || type.kind === "intersection" || type.kind === "tuple") {
1860
- const complex = type;
1861
- return {
1862
- kind: type.kind,
1863
- items: [...complex.items],
1864
- tags: new Set(complex.tags)
1865
- };
1866
- }
1867
- return {
1868
- ...type,
1869
- tags: new Set(type.tags)
1870
- };
2872
+ /** The node at prop path `chain` below `type` (through objects), `undefined` when none. */ function propAtChain(type, chain) {
2873
+ let node = type;
2874
+ for (const key of chain) node = node?.type?.kind === "object" ? node.type.props.get(key) : void 0;
2875
+ return node;
1871
2876
  }
1872
2877
  /**
1873
2878
  * Creates a builder handle for constructing a {@link TAtscriptAnnotatedType} at runtime.
@@ -1889,24 +2894,23 @@ function cloneTypeDef(type) {
1889
2894
  * @returns A builder handle for fluent type construction.
1890
2895
  */ function defineAnnotatedType(_kind, base) {
1891
2896
  const kind = _kind || "";
1892
- const baseProvided = base !== void 0;
1893
2897
  const type = base?.type || {};
1894
2898
  touched(type);
1895
2899
  type.kind = kind;
2900
+ type.tags = /* @__PURE__ */ new Set();
1896
2901
  if (COMPLEX_KINDS.has(kind)) type.items = [];
1897
2902
  if (kind === "object") {
1898
2903
  type.props = new PropsMap();
1899
2904
  type.propsPatterns = [];
1900
2905
  }
1901
- type.tags = /* @__PURE__ */ new Set();
1902
2906
  const metadata = baseMetadata(base?.metadata);
1903
- const payload = {
2907
+ if (base && base.metadata !== metadata) metadataReplaced();
2908
+ base = base ? Object.assign(base, {
1904
2909
  __is_atscript_annotated_type: true,
1905
2910
  metadata,
1906
2911
  type,
1907
2912
  validator: validatorMethod
1908
- };
1909
- base = base ? Object.assign(base, payload) : payload;
2913
+ }) : createAnnotatedTypeNode(type, metadata);
1910
2914
  return {
1911
2915
  $type: base,
1912
2916
  $def: type,
@@ -1941,7 +2945,7 @@ function cloneTypeDef(type) {
1941
2945
  },
1942
2946
  propPattern(pattern, def) {
1943
2947
  this.$def.propsPatterns.push({
1944
- pattern,
2948
+ pattern: statelessRegExp(pattern),
1945
2949
  def
1946
2950
  });
1947
2951
  touched(this.$def);
@@ -1956,67 +2960,44 @@ function cloneTypeDef(type) {
1956
2960
  for (const [key, value] of fromMetadata.entries()) if (!ignore || !ignore.has(key)) this.$metadata.set(key, value);
1957
2961
  return this;
1958
2962
  },
1959
- refTo(type, chain) {
2963
+ ref(target, chain) {
2964
+ var _node;
2965
+ const at = $ft(target, ...chain ?? []);
1960
2966
  const node = this.$type;
1961
2967
  touched(node);
1962
- const field = chain ? chain.join(".") : "";
1963
- if (isAnnotatedType(type)) {
1964
- let newBase = type;
1965
- const typeName = type.name || "Unknown";
1966
- if (chain) for (let i = 0; i < chain.length; i++) {
1967
- const c = chain[i];
1968
- if (newBase.type.kind === "object" && newBase.type.props.has(c)) newBase = newBase.type.props.get(c);
1969
- else {
1970
- const keys = chain.slice(0, i + 1).map((k) => `["${k}"]`).join("");
1971
- throw new Error(`Can't find prop ${typeName}${keys}`);
1972
- }
1973
- }
1974
- node.type = baseProvided ? cloneTypeDef(newBase.type) : newBase.type;
1975
- node.id = node.id ?? newBase.id;
1976
- node.ref = {
1977
- type: () => type,
1978
- field
1979
- };
1980
- } else if (typeof type === "function") {
1981
- const lazyType = type;
1982
- const ownId = node.id;
1983
- node.ref = {
1984
- type: lazyType,
1985
- field
1986
- };
1987
- const placeholder = node.type;
1988
- Object.defineProperty(node, "type", {
1989
- get() {
1990
- const t = lazyType();
1991
- if (!isAnnotatedType(t)) {
1992
- Object.defineProperty(node, "type", {
1993
- value: placeholder,
1994
- writable: false,
1995
- configurable: true
1996
- });
1997
- return placeholder;
1998
- }
1999
- let target = t;
2000
- if (chain) for (const c of chain) if (target.type.kind === "object" && target.type.props.has(c)) target = target.type.props.get(c);
2001
- else return t.type;
2002
- node.id = ownId ?? target.id;
2003
- const resolved = baseProvided ? cloneTypeDef(target.type) : target.type;
2004
- Object.defineProperty(node, "type", {
2005
- value: resolved,
2006
- writable: false,
2007
- configurable: true
2008
- });
2009
- return resolved;
2010
- },
2011
- configurable: true
2012
- });
2013
- } else throw new TypeError(`${type} is not annotated type`);
2968
+ node.type = at.type;
2969
+ node.ref = {
2970
+ type: () => target,
2971
+ field: chain ? fieldOf(chain) : ""
2972
+ };
2973
+ (_node = node).id ?? (_node.id = at.id);
2974
+ return this.over([at], true);
2975
+ },
2976
+ over(bases, reference) {
2977
+ for (const b of bases) readyNode(b);
2978
+ const node = this.$type;
2979
+ touched(node);
2980
+ const metadata = new LayerMap(bases, reference, ownEntries(this.$metadata));
2981
+ moveIntrinsic(this.$metadata, metadata);
2982
+ node.metadata = metadata;
2983
+ this.$metadata = metadata;
2984
+ metadataReplaced();
2985
+ return this;
2986
+ },
2987
+ type(of) {
2988
+ const node = this.$type;
2989
+ touched(node);
2990
+ node.type = readyNode(of).type;
2014
2991
  return this;
2015
2992
  },
2016
2993
  annotate(key, value, asArray) {
2017
2994
  annotate(this.$metadata, key, value, asArray);
2018
2995
  return this;
2019
2996
  },
2997
+ intrinsic(...keys) {
2998
+ markIntrinsic(this.$metadata, keys);
2999
+ return this;
3000
+ },
2020
3001
  id(value) {
2021
3002
  this.$type.id = value;
2022
3003
  return this;
@@ -2047,561 +3028,509 @@ function cloneTypeDef(type) {
2047
3028
  }
2048
3029
 
2049
3030
  //#endregion
2050
- //#region packages/typescript/src/runtime/traverse.ts
3031
+ //#region packages/typescript/src/runtime/cut.ts
3032
+ var _globalThis, _Symbol_for;
2051
3033
  /**
2052
- * Type-safe dispatch over `TAtscriptAnnotatedType` by its `type.kind`.
2053
- *
2054
- * Provides the common `switch (def.type.kind)` pattern used by
2055
- * the validator, JSON-schema builder, and serializer.
2056
- * Each caller supplies its own handlers that control recursion.
2057
- *
2058
- * When a `phantom` handler is provided, phantom types (`designType === 'phantom'`)
2059
- * are dispatched to it instead of `final`. This allows consumers to skip or
2060
- * handle phantom props without polluting their `final` handler.
2061
- */ function forAnnotatedType(def, handlers) {
2062
- switch (def.type.kind) {
2063
- case "": {
2064
- const typed = def;
2065
- if (handlers.phantom && typed.type.designType === "phantom") return handlers.phantom(typed);
2066
- return handlers.final(typed);
2067
- }
2068
- case "object": return handlers.object(def);
2069
- case "array": return handlers.array(def);
2070
- case "union": return handlers.union(def);
2071
- case "intersection": return handlers.intersection(def);
2072
- case "tuple": return handlers.tuple(def);
2073
- default: throw new Error(`Unknown type kind "${def.type.kind}"`);
2074
- }
3034
+ * Defs standing for another one to the cut (a shell's def → the def it shells; a deserialized
3035
+ * def → its payload tag's token). Shared by every copy of the runtime (types built by one, read
3036
+ * by another).
3037
+ */ const origins = (_globalThis = globalThis)[_Symbol_for = Symbol.for("@atscript/typescript:cut-origins:1")] ?? (_globalThis[_Symbol_for] = /* @__PURE__ */ new WeakMap());
3038
+ /** Def `copy` stands for def `of` to the cut (for what `of` stands for). */ function cutAs(copy, of) {
3039
+ origins.set(copy, typeof of === "object" && of !== null && origins.get(of) || of);
3040
+ }
3041
+ /** The cut key of `node` (see above). */ function cutKey(node) {
3042
+ const def = node.type;
3043
+ return node.id ?? origins.get(def) ?? def;
3044
+ }
3045
+ /** Whether `key` is expanded on `path`. */ function onPath(path, key) {
3046
+ for (let p = path; p; p = p.up) if (p.key === key) return true;
3047
+ return false;
3048
+ }
3049
+ /** The path below `node` reached on `path`; `false` where `node` is cut. */ function enterCut(path, node) {
3050
+ if (node.type.kind === "") return path;
3051
+ const key = cutKey(node);
3052
+ return onPath(path, key) ? false : {
3053
+ key,
3054
+ up: path
3055
+ };
2075
3056
  }
2076
3057
 
2077
3058
  //#endregion
2078
- //#region packages/typescript/src/runtime/json-schema.ts
3059
+ //#region packages/typescript/src/runtime/blocks.ts
2079
3060
  /**
2080
- * Detects a discriminator property across union items.
2081
- *
2082
- * Scans all items for object-typed members that share a common property
2083
- * with distinct const/literal values. If exactly one such property exists,
2084
- * it is returned as the discriminator. Returns `null` when no qualifying
2085
- * property exists, or when more than one does (ambiguous).
2086
- */ function detectDiscriminator(items) {
2087
- if (items.length < 2) return null;
2088
- for (const item of items) if (item.type.kind !== "object") return null;
2089
- const firstObj = items[0].type;
2090
- const candidates = [];
2091
- for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
2092
- let result = null;
2093
- for (const candidate of candidates) {
2094
- const values = /* @__PURE__ */ new Set();
2095
- const indexMapping = {};
2096
- let valid = true;
2097
- for (let i = 0; i < items.length; i++) {
2098
- const prop = items[i].type.props.get(candidate);
2099
- if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
2100
- valid = false;
2101
- break;
2102
- }
2103
- const val = prop.type.value;
2104
- if (values.has(val)) {
2105
- valid = false;
2106
- break;
2107
- }
2108
- values.add(val);
2109
- indexMapping[String(val)] = i;
2110
- }
2111
- if (valid) {
2112
- if (result) return null;
2113
- result = {
2114
- propertyName: candidate,
2115
- indexMapping
2116
- };
2117
- }
2118
- }
2119
- return result;
3061
+ * The runtime helpers of the generated structure: node lookup (`$f`),
3062
+ * annotated aliases and `as` copies (`$alias`), shells (`$sh`), blocks with static ranks
3063
+ * (`$blk`) and the import-cycle queue (`$q` / `$end`). Merges are not computed here: the
3064
+ * generated code prints their final structure (hidden classes, `.over` layers).
3065
+ */
3066
+ /**
3067
+ * Thrown when a statement reads what is not built yet (a class of an import cycle's module still
3068
+ * evaluating, a CommonJS cycle's `undefined` import, a def without its props): `$q` queues it.
3069
+ */ const NOT_READY = /* @__PURE__ */ new Error("atscript: type not built yet");
3070
+ /**
3071
+ * `x` as an annotated type whose def can be read, else `NOT_READY`: a class of an import cycle's
3072
+ * module not evaluated yet (CommonJS: `undefined`), or an alias class (declared with
3073
+ * `type = null`) before its `$alias` ran.
3074
+ */ function readyNode(x) {
3075
+ if (!isAnnotatedType(x) || x.type === null || x.type === void 0) throw NOT_READY;
3076
+ return x;
3077
+ }
3078
+ /** `x` as a built class (its builder ran: its def has a kind), else `NOT_READY`. */ function builtNode(x) {
3079
+ const n = readyNode(x);
3080
+ if (n.type.kind === void 0) throw NOT_READY;
3081
+ return n;
3082
+ }
3083
+ /** The child of `n` at step `s`: a prop, `[]` (array element) or `|i` (union / tuple item i). */ function child(n, s) {
3084
+ const t = n.type;
3085
+ if (!t?.kind) return;
3086
+ if (s === "[]") return t.of;
3087
+ if (s[0] === "|") return t.items?.[Number(s.slice(1))];
3088
+ return t.props?.get(s) ?? t.propsPatterns?.find((p) => patternStep(p.pattern) === s)?.def;
3089
+ }
3090
+ /** The step naming prop pattern `re` (`*` is `/./`). */ function patternStep(re) {
3091
+ return re.source === "." && re.flags === "" ? "*" : `/${re.source}/${re.flags}`;
3092
+ }
3093
+ /** A chain's `ref.field`: its props (`a.b`), without the union steps a nullable one takes. */ function fieldOf(chain) {
3094
+ return chain.filter((s) => s[0] !== "|").join(".");
2120
3095
  }
2121
3096
  /**
2122
- * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
2123
- *
2124
- * Translates the atscript type structure and validation metadata
2125
- * (min/max, patterns, integer constraints, etc.) into a standard JSON Schema.
2126
- *
2127
- * @example
2128
- * ```ts
2129
- * import { buildJsonSchema } from '@atscript/typescript'
2130
- *
2131
- * const schema = buildJsonSchema(MyInterface)
2132
- * // { type: 'object', properties: { ... }, required: [...] }
2133
- * ```
2134
- *
2135
- * @param type - The annotated type to convert.
2136
- * @returns A JSON Schema object.
2137
- */ function buildJsonSchema(type) {
2138
- const defs = {};
2139
- let hasDefs = false;
2140
- const buildObject = (d) => {
2141
- const properties = {};
2142
- const required = [];
2143
- for (const [key, val] of d.type.props.entries()) {
2144
- if (isPhantomType(val)) continue;
2145
- properties[key] = build(val);
2146
- if (!val.optional) required.push(key);
2147
- }
2148
- const schema = {
2149
- type: "object",
2150
- properties
2151
- };
2152
- if (required.length > 0) schema.required = required;
2153
- return schema;
2154
- };
2155
- const build = (def) => {
2156
- if (def.id && def.type.kind === "object" && def !== type) {
2157
- const name = def.id;
2158
- if (!defs[name]) {
2159
- hasDefs = true;
2160
- defs[name] = {};
2161
- defs[name] = buildObject(def);
2162
- }
2163
- return { $ref: `#/$defs/${name}` };
2164
- }
2165
- const meta = def.metadata;
2166
- return forAnnotatedType(def, {
2167
- phantom() {
2168
- return {};
2169
- },
2170
- object(d) {
2171
- return buildObject(d);
2172
- },
2173
- array(d) {
2174
- const schema = {
2175
- type: "array",
2176
- items: build(d.type.of)
2177
- };
2178
- applyArrayConstraints(schema, meta);
2179
- return schema;
2180
- },
2181
- union(d) {
2182
- const disc = detectDiscriminator(d.type.items);
2183
- if (disc) {
2184
- const oneOf = d.type.items.map(build);
2185
- const mapping = {};
2186
- for (const [val, idx] of Object.entries(disc.indexMapping)) {
2187
- const item = d.type.items[idx];
2188
- mapping[val] = item.id && defs[item.id] ? `#/$defs/${item.id}` : `#/oneOf/${idx}`;
2189
- }
2190
- return {
2191
- oneOf,
2192
- discriminator: {
2193
- propertyName: disc.propertyName,
2194
- mapping
2195
- }
2196
- };
2197
- }
2198
- const anyOf = d.type.items.map(build);
2199
- if (meta.size > 0) applyUnionConstraints(anyOf, meta);
2200
- return { anyOf };
2201
- },
2202
- intersection(d) {
2203
- return { allOf: d.type.items.map(build) };
2204
- },
2205
- tuple(d) {
2206
- return {
2207
- type: "array",
2208
- items: d.type.items.map(build),
2209
- additionalItems: false
2210
- };
2211
- },
2212
- final(d) {
2213
- const schema = {};
2214
- if (d.type.value !== void 0) schema.const = d.type.value;
2215
- if (d.type.designType && d.type.designType !== "any") {
2216
- const dt = d.type.designType;
2217
- schema.type = dt === "undefined" ? "null" : dt === "decimal" ? "string" : dt;
2218
- }
2219
- applyScalarConstraints(schema, meta);
2220
- return schema;
2221
- }
2222
- });
3097
+ * The node at `path` below `root` (see {@link child}); `NOT_READY` while it is not built, or
3098
+ * while a pending shell (an import cycle's, see {@link $ps}) would replace it.
3099
+ */ function $f(root, ...path) {
3100
+ return nodeAt(root, path, PLAIN);
3101
+ }
3102
+ /** {@link $f} for a reader of the node's def (`.ref(T, chain)`, `$alias`): its final def. */ function $ft(root, ...path) {
3103
+ return nodeAt(root, path, TYPED);
3104
+ }
3105
+ /** {@link $f} for a shell that clones the node's def: once every shell put into it (a guard). */ function $fc(root, ...path) {
3106
+ return nodeAt(root, path, CLONED);
3107
+ }
3108
+ /** How a read uses the node (see {@link changedBy}). */ const PLAIN = 0;
3109
+ const TYPED = 1;
3110
+ const CLONED = 2;
3111
+ function nodeAt(root, path, typed) {
3112
+ let n = readyNode(root);
3113
+ const shells = pendingShells.get(n);
3114
+ if (shells && changedBy(shells, path, typed)) throw NOT_READY;
3115
+ for (const s of path) {
3116
+ const c = child(n, s);
3117
+ if (!c) throw NOT_READY;
3118
+ n = c;
3119
+ }
3120
+ const t = n.type;
3121
+ if (typed !== PLAIN && t.kind === "" && t.designType === void 0) throw NOT_READY;
3122
+ return n;
3123
+ }
3124
+ /**
3125
+ * Class `P` is `T` with annotations of its own (an annotated alias, an `annotate T as P` copy;
3126
+ * `chain`: `type P = T.a.b`, a chain ref): T's def (at `chain`), and metadata layered over it
3127
+ * (P's own entries kept; a chain ref is a reference layer).
3128
+ */ function $alias(P, T, chain) {
3129
+ var _node, _node1;
3130
+ const root = readyNode(T);
3131
+ const target = readyNode($ft(root, ...chain ?? []));
3132
+ const node = P;
3133
+ touched(node);
3134
+ node.type = target.type;
3135
+ const own = node.metadata;
3136
+ node.metadata = new LayerMap([target], !!chain, ownEntries(node.metadata));
3137
+ moveIntrinsic(own, node.metadata);
3138
+ metadataReplaced();
3139
+ const recs = records.get(own);
3140
+ if (recs) records.set(node.metadata, recs);
3141
+ node.ref = {
3142
+ type: () => root,
3143
+ field: chain ? fieldOf(chain) : ""
2223
3144
  };
2224
- const schema = build(type);
2225
- if (hasDefs) return {
2226
- ...schema,
2227
- $defs: defs
3145
+ (_node = node).id ?? (_node.id = target.id);
3146
+ (_node1 = node).validator ?? (_node1.validator = validatorMethod);
3147
+ return node;
3148
+ }
3149
+ /** Shell nodes → the def they were put in (a shell is its position's: the exact path). */ const shellIn = /* @__PURE__ */ new WeakMap();
3150
+ /**
3151
+ * Shell defs → the node they were made for: a shell node over a node with a shell def starts
3152
+ * with that def, and gets its own on its first step of kind 2 (the exact path).
3153
+ */ const shellDefOf = /* @__PURE__ */ new WeakMap();
3154
+ /**
3155
+ * A shell node over `base`: metadata layered over base; its def IS base's def (a reference, read
3156
+ * when used: a def base gets later — a clone a shell of another class puts in — is the shell's
3157
+ * too) until a step below it gives the shell a def of its own (kind 2: `type` is assigned).
3158
+ */ function shellNode(base) {
3159
+ const node = {
3160
+ __is_atscript_annotated_type: true,
3161
+ metadata: new LayerMap([base])
2228
3162
  };
2229
- return schema;
2230
- }
2231
- /** `@expect.minLength` / `maxLength` → `minItems` / `maxItems` on an array schema. */ function applyArrayConstraints(schema, meta) {
2232
- const minLength = meta.get("expect.minLength");
2233
- if (minLength !== void 0) schema.minItems = boundOf(minLength, "length");
2234
- const maxLength = meta.get("expect.maxLength");
2235
- if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
2236
- }
2237
- /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
2238
- if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
2239
- if (schema.type === "string") {
2240
- if (meta.get("meta.required")) schema.minLength = 1;
2241
- const minLength = meta.get("expect.minLength");
2242
- if (minLength !== void 0) schema.minLength = boundOf(minLength, "length");
2243
- const maxLength = meta.get("expect.maxLength");
2244
- if (maxLength !== void 0) schema.maxLength = boundOf(maxLength, "length");
2245
- const patterns = meta.get("expect.pattern");
2246
- if (patterns?.length) if (patterns.length === 1) schema.pattern = patterns[0].pattern;
2247
- else schema.allOf = (schema.allOf || []).concat(patterns.map((p) => ({ pattern: p.pattern })));
2248
- }
2249
- if (schema.type === "number" || schema.type === "integer") {
2250
- const min = meta.get("expect.min");
2251
- if (min !== void 0) schema.minimum = boundOf(min, "minValue");
2252
- const max = meta.get("expect.max");
2253
- if (max !== void 0) schema.maximum = boundOf(max, "maxValue");
2254
- const exMin = meta.get("expect.exclusiveMin");
2255
- if (exMin !== void 0) schema.exclusiveMinimum = boundOf(exMin, "exclusiveMinValue");
2256
- const exMax = meta.get("expect.exclusiveMax");
2257
- if (exMax !== void 0) schema.exclusiveMaximum = boundOf(exMax, "exclusiveMaxValue");
2258
- }
2259
- }
2260
- const LOWER_BOUNDS = new Set([
2261
- "minimum",
2262
- "exclusiveMinimum",
2263
- "minLength",
2264
- "minItems"
2265
- ]);
2266
- const UPPER_BOUNDS = new Set([
2267
- "maximum",
2268
- "exclusiveMaximum",
2269
- "maxLength",
2270
- "maxItems"
2271
- ]);
3163
+ Object.defineProperty(node, SHELL, { value: {
3164
+ b: base,
3165
+ t: void 0,
3166
+ id: void 0,
3167
+ ref: void 0
3168
+ } });
3169
+ Object.defineProperty(node, "type", SHELL_TYPE);
3170
+ node.validator = validatorMethod;
3171
+ Object.defineProperty(node, "ref", SHELL_REF);
3172
+ Object.defineProperty(node, "id", SHELL_ID);
3173
+ node.optional = base.optional;
3174
+ return node;
3175
+ }
3176
+ /** A shell node's own state: its base, and the def / ref / id it was given (`undefined`: base's). */ const SHELL = Symbol("shell");
3177
+ const SHELL_TYPE = {
3178
+ get() {
3179
+ const s = this[SHELL];
3180
+ return s.t ?? s.b.type;
3181
+ },
3182
+ set(d) {
3183
+ this[SHELL].t = d;
3184
+ },
3185
+ enumerable: true,
3186
+ configurable: true
3187
+ };
3188
+ const SHELL_REF = {
3189
+ get() {
3190
+ const s = this[SHELL];
3191
+ return s.ref ? s.ref.v : s.b.ref;
3192
+ },
3193
+ set(v) {
3194
+ this[SHELL].ref = { v };
3195
+ },
3196
+ enumerable: true,
3197
+ configurable: true
3198
+ };
3199
+ const SHELL_ID = {
3200
+ get() {
3201
+ const s = this[SHELL];
3202
+ return s.id ? s.id.v : s.b.id;
3203
+ },
3204
+ set(v) {
3205
+ this[SHELL].id = { v };
3206
+ },
3207
+ enumerable: true,
3208
+ configurable: true
3209
+ };
3210
+ /** A def of node `holder`'s with the same entries as `d` (its children replaceable by shells). */ function shellDef(d, holder) {
3211
+ const c = { ...d };
3212
+ if (d.tags) c.tags = new Set(d.tags);
3213
+ if (d.props) {
3214
+ c.props = new PropsMap(d.props);
3215
+ c.propsPatterns = [...d.propsPatterns ?? []];
3216
+ }
3217
+ if (d.items) c.items = [...d.items];
3218
+ shellDefOf.set(c, holder);
3219
+ cutAs(c, d);
3220
+ return c;
3221
+ }
3222
+ /** Puts `node` at step `s` of def `d`. */ function put(d, s, node) {
3223
+ if (s === "[]") {
3224
+ d.of = node;
3225
+ touched(d);
3226
+ } else if (s[0] === "|") {
3227
+ d.items[Number(s.slice(1))] = node;
3228
+ touched(d);
3229
+ } else d.props.set(s, node);
3230
+ }
2272
3231
  /**
2273
- * Puts union-level constraints onto the matching `anyOf` members (numbers, strings,
2274
- * arrays; nested `anyOf` members recursively). When a member already has the same
2275
- * bound, the stricter one wins; patterns accumulate.
2276
- */ function applyUnionConstraints(members, meta) {
2277
- for (const member of members) {
2278
- if (Array.isArray(member.anyOf)) {
2279
- applyUnionConstraints(member.anyOf, meta);
2280
- continue;
2281
- }
2282
- if (member.const !== void 0) continue;
2283
- const type = member.type;
2284
- const extra = { type };
2285
- if (type === "array") applyArrayConstraints(extra, meta);
2286
- else if (type === "string" || type === "number" || type === "integer") applyScalarConstraints(extra, meta);
2287
- else continue;
2288
- if (extra.type === "integer") member.type = "integer";
2289
- for (const [key, value] of Object.entries(extra)) {
2290
- if (key === "type") continue;
2291
- if (key === "pattern" || key === "allOf") {
2292
- const patterns = key === "pattern" ? [{ pattern: value }] : value;
2293
- if (member.pattern === void 0 && key === "pattern" && !member.allOf) member.pattern = value;
2294
- else member.allOf = (member.allOf || []).concat(patterns);
2295
- } else if (member[key] === void 0) member[key] = value;
2296
- else if (LOWER_BOUNDS.has(key)) member[key] = Math.max(member[key], value);
2297
- else if (UPPER_BOUNDS.has(key)) member[key] = Math.min(member[key], value);
2298
- }
3232
+ * The node of `T` at `path`, with T's own shells along it (idempotent). Step kinds:
3233
+ * 0 — the def and the child are T's own (descend); 1 — the def is T's, the child is not (a shell
3234
+ * node replaces it); 2 — the def is not T's (the node gets a shell def first, then as 1).
3235
+ */ function ensure(T, path) {
3236
+ let cur = T;
3237
+ for (const [s, kind] of path) {
3238
+ let c = child(cur, s);
3239
+ if (!c) throw NOT_READY;
3240
+ if (kind === 2 && shellDefOf.get(cur.type) !== cur) {
3241
+ touched(cur);
3242
+ cur.type = shellDef(cur.type, cur);
3243
+ }
3244
+ if (kind !== 0 && shellIn.get(c) !== cur.type) {
3245
+ c = shellNode(c);
3246
+ put(cur.type, s, c);
3247
+ shellIn.set(c, cur.type);
3248
+ }
3249
+ cur = c;
3250
+ }
3251
+ return cur;
3252
+ }
3253
+ /** Ensures T's shells along each path (see {@link ensure}). */ function $sh(T, paths) {
3254
+ const target = builtNode(T);
3255
+ for (const path of paths) ensure(target, path);
3256
+ const pending = pendingShells.get(target);
3257
+ if (pending) {
3258
+ const done = new Set(paths.flatMap(stagesOf).map((p) => JSON.stringify(p)));
3259
+ const rest = pending.filter((p) => !done.has(JSON.stringify(p)));
3260
+ if (rest.length > 0) pendingShells.set(target, rest);
3261
+ else pendingShells.delete(target);
2299
3262
  }
2300
3263
  }
2301
3264
  /**
2302
- * Converts a JSON Schema object into a {@link TAtscriptAnnotatedType}.
2303
- *
2304
- * This is the inverse of {@link buildJsonSchema}. A round-trip
2305
- * `buildJsonSchema(fromJsonSchema(schema))` preserves structure and constraints.
2306
- *
2307
- * Supports the JSON Schema subset produced by `buildJsonSchema` plus
2308
- * common extensions like `oneOf` (treated as union) and `enum` (union of literals).
2309
- *
2310
- * @example
2311
- * ```ts
2312
- * import { fromJsonSchema } from '@atscript/typescript'
2313
- *
2314
- * const type = fromJsonSchema({ type: 'object', properties: { name: { type: 'string' } }, required: ['name'] })
2315
- * type.validator().validate({ name: 'Alice' }) // passes
2316
- * ```
2317
- *
2318
- * @param schema - A JSON Schema object.
2319
- * @returns An annotated type with full validator support.
2320
- */ function fromJsonSchema(schema) {
2321
- const defsSource = schema.$defs || schema.definitions || {};
2322
- const resolved = /* @__PURE__ */ new Map();
2323
- const convert = (s) => {
2324
- if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
2325
- if (s.$ref) {
2326
- const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
2327
- if (resolved.has(refName)) return resolved.get(refName);
2328
- if (defsSource[refName]) {
2329
- const placeholder = defineAnnotatedType().designType("any").$type;
2330
- resolved.set(refName, placeholder);
2331
- const type = convert(defsSource[refName]);
2332
- resolved.set(refName, type);
2333
- return type;
2334
- }
2335
- throw new Error(`Unresolvable $ref: ${s.$ref}`);
2336
- }
2337
- if ("const" in s) {
2338
- const val = s.const;
2339
- const dt = val === null ? "null" : typeof val;
2340
- return defineAnnotatedType().designType(dt).value(val).$type;
2341
- }
2342
- if (s.enum) {
2343
- const handle = defineAnnotatedType("union");
2344
- for (const val of s.enum) {
2345
- const dt = val === null ? "null" : typeof val;
2346
- handle.item(defineAnnotatedType().designType(dt).value(val).$type);
2347
- }
2348
- return handle.$type;
2349
- }
2350
- if (s.anyOf) {
2351
- const handle = defineAnnotatedType("union");
2352
- for (const item of s.anyOf) handle.item(convert(item));
2353
- return handle.$type;
2354
- }
2355
- if (s.oneOf) {
2356
- const handle = defineAnnotatedType("union");
2357
- for (const item of s.oneOf) handle.item(convert(item));
2358
- return handle.$type;
2359
- }
2360
- if (s.allOf && !s.type) {
2361
- const handle = defineAnnotatedType("intersection");
2362
- for (const item of s.allOf) handle.item(convert(item));
2363
- return handle.$type;
2364
- }
2365
- if (Array.isArray(s.type)) {
2366
- const handle = defineAnnotatedType("union");
2367
- for (const t of s.type) handle.item(convert({
2368
- ...s,
2369
- type: t
2370
- }));
2371
- return handle.$type;
2372
- }
2373
- if (s.type === "object") {
2374
- const handle = defineAnnotatedType("object");
2375
- const required = new Set(s.required || []);
2376
- if (s.properties) for (const [key, propSchema] of Object.entries(s.properties)) {
2377
- const propType = convert(propSchema);
2378
- if (!required.has(key)) propType.optional = true;
2379
- handle.prop(key, propType);
2380
- }
2381
- return handle.$type;
2382
- }
2383
- if (s.type === "array") {
2384
- if (Array.isArray(s.items)) {
2385
- const handle = defineAnnotatedType("tuple");
2386
- for (const item of s.items) handle.item(convert(item));
2387
- return handle.$type;
2388
- }
2389
- const itemType = s.items ? convert(s.items) : defineAnnotatedType().designType("any").$type;
2390
- const handle = defineAnnotatedType("array").of(itemType);
2391
- if (typeof s.minItems === "number") handle.annotate("expect.minLength", { length: s.minItems });
2392
- if (typeof s.maxItems === "number") handle.annotate("expect.maxLength", { length: s.maxItems });
2393
- return handle.$type;
2394
- }
2395
- if (s.type === "string") {
2396
- const handle = defineAnnotatedType().designType("string").tags("string");
2397
- if (typeof s.minLength === "number") handle.annotate("expect.minLength", { length: s.minLength });
2398
- if (typeof s.maxLength === "number") handle.annotate("expect.maxLength", { length: s.maxLength });
2399
- if (s.pattern) handle.annotate("expect.pattern", { pattern: s.pattern }, true);
2400
- if (s.allOf) {
2401
- for (const item of s.allOf) if (item.pattern) handle.annotate("expect.pattern", { pattern: item.pattern }, true);
2402
- }
2403
- return handle.$type;
2404
- }
2405
- if (s.type === "integer") {
2406
- const handle = defineAnnotatedType().designType("number").tags("number");
2407
- handle.annotate("expect.int", true);
2408
- annotateNumberBounds(handle, s);
2409
- return handle.$type;
2410
- }
2411
- if (s.type === "number") {
2412
- const handle = defineAnnotatedType().designType("number").tags("number");
2413
- annotateNumberBounds(handle, s);
2414
- return handle.$type;
2415
- }
2416
- if (s.type === "boolean") return defineAnnotatedType().designType("boolean").tags("boolean").$type;
2417
- if (s.type === "null") return defineAnnotatedType().designType("null").tags("null").$type;
2418
- return defineAnnotatedType().designType("any").$type;
2419
- };
2420
- return convert(schema);
3265
+ * The shells a class of an import cycle's module will get (`$sh` runs once what they shell is
3266
+ * built): a read through a node they replace, or into a def they clone, waits for them.
3267
+ */ const pendingShells = /* @__PURE__ */ new WeakMap();
3268
+ /** Registers class `T`'s shells as pending (see {@link $sh}): first statement of its module. */ function $ps(T, paths) {
3269
+ const seen = /* @__PURE__ */ new Set();
3270
+ pendingShells.set(T, paths.flatMap(stagesOf).filter((p) => {
3271
+ const k = JSON.stringify(p);
3272
+ return !seen.has(k) && !!seen.add(k);
3273
+ }));
2421
3274
  }
2422
3275
  /**
2423
- * Maps `minimum` / `maximum` / `exclusiveMinimum` / `exclusiveMaximum` onto
2424
- * `@expect.min` / `max` / `exclusiveMin` / `exclusiveMax`. Also reads the draft-4 form,
2425
- * where `exclusiveMinimum: true` makes `minimum` exclusive.
2426
- */ function annotateNumberBounds(handle, s) {
2427
- if (typeof s.minimum === "number") if (s.exclusiveMinimum === true) handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.minimum });
2428
- else handle.annotate("expect.min", { minValue: s.minimum });
2429
- if (typeof s.maximum === "number") if (s.exclusiveMaximum === true) handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.maximum });
2430
- else handle.annotate("expect.max", { maxValue: s.maximum });
2431
- if (typeof s.exclusiveMinimum === "number") handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.exclusiveMinimum });
2432
- if (typeof s.exclusiveMaximum === "number") handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.exclusiveMaximum });
3276
+ * The last step index of each stage of shell path `path` (see {@link stagesOf}): every step that
3277
+ * shells, and the path's last (the build's stage index walks them too, `js-next.ts`
3278
+ * `shellPathsOf`).
3279
+ */ function stageEnds(path) {
3280
+ return path.flatMap(([, kind], j) => kind !== 0 || j === path.length - 1 ? [j] : []);
3281
+ }
3282
+ /** The stages of shell path `path`: each prefix ending at a step that shells, and the path. */ function stagesOf(path) {
3283
+ return stageEnds(path).map((j) => path.slice(0, j + 1));
2433
3284
  }
2434
3285
  /**
2435
- * Merges multiple annotated types into a combined schema map with shared `$defs`.
2436
- *
2437
- * Each type must have an `id`. The returned `schemas` object contains individual
2438
- * schemas keyed by type id, and `$defs` contains all shared type definitions
2439
- * deduplicated across schemas.
2440
- *
2441
- * @param types - Array of annotated types, each with an `id`.
2442
- * @returns An object with `schemas` (keyed by id) and shared `$defs`.
2443
- */ function mergeJsonSchemas(types) {
2444
- const mergedDefs = {};
2445
- const schemas = {};
2446
- for (const type of types) {
2447
- const name = type.id;
2448
- if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
2449
- const schema = buildJsonSchema(type);
2450
- if (schema.$defs) {
2451
- for (const [defName, defSchema] of Object.entries(schema.$defs)) if (!mergedDefs[defName]) mergedDefs[defName] = defSchema;
2452
- const { $defs: _, ...rest } = schema;
2453
- schemas[name] = rest;
2454
- } else schemas[name] = schema;
3286
+ * Whether a read at `path` meets what pending shell stages change: a stage (a shell path up to a
3287
+ * step of kind 1 / 2) replaces the node at its end in the def above it (kind 2: in a clone of
3288
+ * that def). A read through that node waits; a read of the def above it waits for a clone
3289
+ * (`TYPED`: it captures the def) or for any stage (`CLONED`: it copies the def's entries).
3290
+ */ function changedBy(shells, path, typed) {
3291
+ for (const s of shells) {
3292
+ const n = s.length;
3293
+ let i = 0;
3294
+ while (i < n && i < path.length && path[i] === s[i][0]) i++;
3295
+ if (i === n || typed !== PLAIN && i === n - 1 && path.length === n - 1 && (typed === CLONED || s[n - 1][1] === 2)) return true;
2455
3296
  }
2456
- return {
2457
- schemas,
2458
- $defs: mergedDefs
2459
- };
3297
+ return false;
3298
+ }
3299
+ function compare(a, b) {
3300
+ return a[0] - b[0] || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0) || a[2] - b[2] || a[3] - b[3];
3301
+ }
3302
+ const records = /* @__PURE__ */ new WeakMap();
3303
+ function recordsOf(m) {
3304
+ let r = records.get(m);
3305
+ if (!r) records.set(m, r = /* @__PURE__ */ new Map());
3306
+ return r;
3307
+ }
3308
+ /**
3309
+ * A block write of a replace key: ignored when the own value is one a higher-ranked block wrote
3310
+ * (a raw write since makes it nobody's: the block applies).
3311
+ */ function writeKey(m, key, value, rank) {
3312
+ const recs = recordsOf(m);
3313
+ const r = recs.get(key);
3314
+ if (r && ownValue(m, key) === r.value && compare(r.rank, rank) > 0) return;
3315
+ m.set(key, value);
3316
+ recs.set(key, {
3317
+ rank,
3318
+ value
3319
+ });
3320
+ }
3321
+ /**
3322
+ * A block write of an append key: the own list is the elements written before any block (by
3323
+ * the builder, or a raw write since), then every block's part by rank.
3324
+ */ function appendKey(m, key, values, rank) {
3325
+ const recs = recordsOf(m);
3326
+ let r = recs.get(key);
3327
+ const own = ownValue(m, key);
3328
+ if (!r || own !== r.value || r.value.length !== r.length) {
3329
+ const before = own === void 0 ? [] : Array.isArray(own) ? [...own] : [own];
3330
+ r = {
3331
+ before,
3332
+ parts: [],
3333
+ value: before,
3334
+ length: 0
3335
+ };
3336
+ }
3337
+ const { parts } = r;
3338
+ let at = 0;
3339
+ while (at < parts.length && compare(parts[at].rank, rank) < 0) at++;
3340
+ if (at < parts.length && compare(parts[at].rank, rank) === 0) parts[at].values = values;
3341
+ else parts.splice(at, 0, {
3342
+ rank,
3343
+ values
3344
+ });
3345
+ const value = [...r.before];
3346
+ for (const p of parts) value.push(...p.values);
3347
+ m.set(key, value);
3348
+ r.value = value;
3349
+ r.length = value.length;
3350
+ recs.set(key, r);
3351
+ }
3352
+ function writeEntry(m, anns, rank) {
3353
+ const values = /* @__PURE__ */ new Map();
3354
+ for (const [key, value, list] of anns) if (list) {
3355
+ const xs = values.get(key);
3356
+ values.set(key, xs ? [...xs, value] : [value]);
3357
+ } else values.set(key, value);
3358
+ for (const [key, value] of values) if (isAppendKey(key)) appendKey(m, key, Array.isArray(value) ? value : [value], rank);
3359
+ else writeKey(m, key, value, rank);
3360
+ }
3361
+ /** The module ids of the blocks applied (the bundled-schema guard reads them). */ const applied = /* @__PURE__ */ new Set();
3362
+ /** The module ids of every block applied so far. */ function appliedBlockModules() {
3363
+ return applied;
3364
+ }
3365
+ /**
3366
+ * Block `index` of a module of rank `R` (`[import depth, module id]`; `null`: an `as` copy's
3367
+ * entries, below every block) on `T`: ensures each entry's shells, then writes its annotations
3368
+ * with rank (R, index, entry index). Re-applying a block is idempotent.
3369
+ */ function $blk(R, index, T, entries) {
3370
+ const target = builtNode(T);
3371
+ const nodes = entries.map(([, ...paths]) => paths.map((path) => ensure(target, path)));
3372
+ entries.forEach(([anns], e) => {
3373
+ const rank = R ? [
3374
+ R[0],
3375
+ R[1],
3376
+ index,
3377
+ e
3378
+ ] : [
3379
+ -1,
3380
+ "",
3381
+ index,
3382
+ e
3383
+ ];
3384
+ for (const node of nodes[e]) writeEntry(node.metadata, anns, rank);
3385
+ });
3386
+ if (R) applied.add(R[1]);
3387
+ }
3388
+ const queue = [];
3389
+ /**
3390
+ * Whether `e` is a statement's wait — a class not built yet (`NOT_READY`), a binding in its
3391
+ * temporal dead zone — rather than its failure.
3392
+ */ const isWait = (e) => e === NOT_READY || e instanceof ReferenceError;
3393
+ /**
3394
+ * Runs `fn` (a statement reading a class of another module of its import cycle), or queues it
3395
+ * when that class is not built yet (ESM: its temporal dead zone; CommonJS: `undefined`). `own`:
3396
+ * the module's own list of queued statements (a module in no import cycle, see {@link $end}).
3397
+ */ function $q(fn, own) {
3398
+ try {
3399
+ fn();
3400
+ } catch (error) {
3401
+ if (!isWait(error)) throw error;
3402
+ queue.push(fn);
3403
+ own?.push(fn);
3404
+ }
3405
+ }
3406
+ /**
3407
+ * The last statement of a module: runs the queued statements that can run now, in order. A module
3408
+ * in no import cycle passes its own queued statements (`own`, see {@link $q}) and throws when one
3409
+ * of them still waits: nothing it waits for can come later. (A module of an import cycle is
3410
+ * checked when the build loads the cycle from each of its modules.)
3411
+ */ function $end(own) {
3412
+ let progress = true;
3413
+ while (progress && queue.length > 0) {
3414
+ progress = false;
3415
+ for (let i = 0; i < queue.length;) {
3416
+ try {
3417
+ queue[i]();
3418
+ } catch (error) {
3419
+ if (isWait(error)) {
3420
+ i++;
3421
+ continue;
3422
+ }
3423
+ queue.splice(i, 1);
3424
+ throw error;
3425
+ }
3426
+ queue.splice(i, 1);
3427
+ progress = true;
3428
+ }
3429
+ }
3430
+ const left = own?.filter((fn) => queue.includes(fn)) ?? [];
3431
+ if (left.length > 0) {
3432
+ for (const fn of left) queue.splice(queue.indexOf(fn), 1);
3433
+ throw new Error(`atscript: ${left.length} statement(s) of this module never ran: they wait for each other (an internal code generation error: please report it)`);
3434
+ }
3435
+ }
3436
+ /** How many statements wait for a class of an import cycle (0 once every module loaded). */ function pendingStatements() {
3437
+ return queue.length;
2460
3438
  }
2461
3439
 
2462
3440
  //#endregion
2463
- Object.defineProperty(exports, 'ARRAY_BITS', {
2464
- enumerable: true,
2465
- get: function () {
2466
- return ARRAY_BITS;
2467
- }
2468
- });
2469
- Object.defineProperty(exports, 'B_INT', {
2470
- enumerable: true,
2471
- get: function () {
2472
- return B_INT;
2473
- }
2474
- });
2475
- Object.defineProperty(exports, 'B_REQUIRED', {
2476
- enumerable: true,
2477
- get: function () {
2478
- return B_REQUIRED;
2479
- }
2480
- });
2481
- Object.defineProperty(exports, 'B_UNIQUE', {
2482
- enumerable: true,
2483
- get: function () {
2484
- return B_UNIQUE;
2485
- }
2486
- });
2487
- Object.defineProperty(exports, 'D_ARRAY', {
2488
- enumerable: true,
2489
- get: function () {
2490
- return D_ARRAY;
2491
- }
2492
- });
2493
- Object.defineProperty(exports, 'D_FINAL', {
2494
- enumerable: true,
2495
- get: function () {
2496
- return D_FINAL;
2497
- }
2498
- });
2499
- Object.defineProperty(exports, 'D_INTERSECTION', {
2500
- enumerable: true,
2501
- get: function () {
2502
- return D_INTERSECTION;
2503
- }
2504
- });
2505
- Object.defineProperty(exports, 'D_OBJECT', {
2506
- enumerable: true,
2507
- get: function () {
2508
- return D_OBJECT;
2509
- }
2510
- });
2511
- Object.defineProperty(exports, 'D_OBJECT_PATTERNS', {
2512
- enumerable: true,
2513
- get: function () {
2514
- return D_OBJECT_PATTERNS;
2515
- }
2516
- });
2517
- Object.defineProperty(exports, 'D_TUPLE', {
2518
- enumerable: true,
2519
- get: function () {
2520
- return D_TUPLE;
2521
- }
2522
- });
2523
- Object.defineProperty(exports, 'D_UNION', {
3441
+ //#region packages/typescript/src/runtime/unique-name.ts
3442
+ /**
3443
+ * `base`, or — when `taken` reports it taken — the first `<base><sep><n>` (n = 1, 2, …) it
3444
+ * does not.
3445
+ */ function uniqueName(base, taken, sep) {
3446
+ let name = base;
3447
+ for (let n = 1; taken(name); n++) name = `${base}${sep}${n}`;
3448
+ return name;
3449
+ }
3450
+
3451
+ //#endregion
3452
+ Object.defineProperty(exports, '$ak', {
2524
3453
  enumerable: true,
2525
3454
  get: function () {
2526
- return D_UNION;
3455
+ return $ak;
2527
3456
  }
2528
3457
  });
2529
- Object.defineProperty(exports, 'D_UNKNOWN', {
3458
+ Object.defineProperty(exports, '$alias', {
2530
3459
  enumerable: true,
2531
3460
  get: function () {
2532
- return D_UNKNOWN;
3461
+ return $alias;
2533
3462
  }
2534
3463
  });
2535
- Object.defineProperty(exports, 'EXT', {
3464
+ Object.defineProperty(exports, '$blk', {
2536
3465
  enumerable: true,
2537
3466
  get: function () {
2538
- return EXT;
3467
+ return $blk;
2539
3468
  }
2540
3469
  });
2541
- Object.defineProperty(exports, 'F_ERROR', {
3470
+ Object.defineProperty(exports, '$end', {
2542
3471
  enumerable: true,
2543
3472
  get: function () {
2544
- return F_ERROR;
3473
+ return $end;
2545
3474
  }
2546
3475
  });
2547
- Object.defineProperty(exports, 'F_IN_UNION', {
3476
+ Object.defineProperty(exports, '$f', {
2548
3477
  enumerable: true,
2549
3478
  get: function () {
2550
- return F_IN_UNION;
3479
+ return $f;
2551
3480
  }
2552
3481
  });
2553
- Object.defineProperty(exports, 'F_PARTIAL_DEEP', {
3482
+ Object.defineProperty(exports, '$fc', {
2554
3483
  enumerable: true,
2555
3484
  get: function () {
2556
- return F_PARTIAL_DEEP;
3485
+ return $fc;
2557
3486
  }
2558
3487
  });
2559
- Object.defineProperty(exports, 'F_PARTIAL_TOP', {
3488
+ Object.defineProperty(exports, '$ft', {
2560
3489
  enumerable: true,
2561
3490
  get: function () {
2562
- return F_PARTIAL_TOP;
3491
+ return $ft;
2563
3492
  }
2564
3493
  });
2565
- Object.defineProperty(exports, 'F_STRIP', {
3494
+ Object.defineProperty(exports, '$nr', {
2566
3495
  enumerable: true,
2567
3496
  get: function () {
2568
- return F_STRIP;
3497
+ return $nr;
2569
3498
  }
2570
3499
  });
2571
- Object.defineProperty(exports, 'F_TOP', {
3500
+ Object.defineProperty(exports, '$ps', {
2572
3501
  enumerable: true,
2573
3502
  get: function () {
2574
- return F_TOP;
3503
+ return $ps;
2575
3504
  }
2576
3505
  });
2577
- Object.defineProperty(exports, 'INTERP', {
3506
+ Object.defineProperty(exports, '$q', {
2578
3507
  enumerable: true,
2579
3508
  get: function () {
2580
- return INTERP;
3509
+ return $q;
2581
3510
  }
2582
3511
  });
2583
- Object.defineProperty(exports, 'ITEMS_KIND_CODES', {
3512
+ Object.defineProperty(exports, '$sh', {
2584
3513
  enumerable: true,
2585
3514
  get: function () {
2586
- return ITEMS_KIND_CODES;
3515
+ return $sh;
2587
3516
  }
2588
3517
  });
2589
- Object.defineProperty(exports, 'LAYOUT_VERSION', {
3518
+ Object.defineProperty(exports, 'DECIMAL_RE', {
2590
3519
  enumerable: true,
2591
3520
  get: function () {
2592
- return LAYOUT_VERSION;
3521
+ return DECIMAL_RE;
2593
3522
  }
2594
3523
  });
2595
- Object.defineProperty(exports, 'NUMBER_BITS', {
3524
+ Object.defineProperty(exports, 'LayerMap', {
2596
3525
  enumerable: true,
2597
3526
  get: function () {
2598
- return NUMBER_BITS;
3527
+ return LayerMap;
2599
3528
  }
2600
3529
  });
2601
- Object.defineProperty(exports, 'STRING_BITS', {
3530
+ Object.defineProperty(exports, 'VALIDATOR_KEYS', {
2602
3531
  enumerable: true,
2603
3532
  get: function () {
2604
- return STRING_BITS;
3533
+ return VALIDATOR_KEYS;
2605
3534
  }
2606
3535
  });
2607
3536
  Object.defineProperty(exports, 'Validator', {
@@ -2622,22 +3551,22 @@ Object.defineProperty(exports, 'annotate', {
2622
3551
  return annotate;
2623
3552
  }
2624
3553
  });
2625
- Object.defineProperty(exports, 'buildJsonSchema', {
3554
+ Object.defineProperty(exports, 'appliedBlockModules', {
2626
3555
  enumerable: true,
2627
3556
  get: function () {
2628
- return buildJsonSchema;
3557
+ return appliedBlockModules;
2629
3558
  }
2630
3559
  });
2631
- Object.defineProperty(exports, 'childSites', {
3560
+ Object.defineProperty(exports, 'arrayKeyProps', {
2632
3561
  enumerable: true,
2633
3562
  get: function () {
2634
- return childSites;
3563
+ return arrayKeyProps;
2635
3564
  }
2636
3565
  });
2637
- Object.defineProperty(exports, 'cloneRefProp', {
3566
+ Object.defineProperty(exports, 'boundOf', {
2638
3567
  enumerable: true,
2639
3568
  get: function () {
2640
- return cloneRefProp;
3569
+ return boundOf;
2641
3570
  }
2642
3571
  });
2643
3572
  Object.defineProperty(exports, 'createAnnotatedTypeNode', {
@@ -2658,40 +3587,28 @@ Object.defineProperty(exports, 'createObjectTypeDef', {
2658
3587
  return createObjectTypeDef;
2659
3588
  }
2660
3589
  });
2661
- Object.defineProperty(exports, 'defineAnnotatedType', {
2662
- enumerable: true,
2663
- get: function () {
2664
- return defineAnnotatedType;
2665
- }
2666
- });
2667
- Object.defineProperty(exports, 'detectDiscriminator', {
3590
+ Object.defineProperty(exports, 'cutAs', {
2668
3591
  enumerable: true,
2669
3592
  get: function () {
2670
- return detectDiscriminator;
3593
+ return cutAs;
2671
3594
  }
2672
3595
  });
2673
- Object.defineProperty(exports, 'forAnnotatedType', {
3596
+ Object.defineProperty(exports, 'cutKey', {
2674
3597
  enumerable: true,
2675
3598
  get: function () {
2676
- return forAnnotatedType;
3599
+ return cutKey;
2677
3600
  }
2678
3601
  });
2679
- Object.defineProperty(exports, 'fromJsonSchema', {
2680
- enumerable: true,
2681
- get: function () {
2682
- return fromJsonSchema;
2683
- }
2684
- });
2685
- Object.defineProperty(exports, 'getRegex', {
3602
+ Object.defineProperty(exports, 'defineAnnotatedType', {
2686
3603
  enumerable: true,
2687
3604
  get: function () {
2688
- return getRegex;
3605
+ return defineAnnotatedType;
2689
3606
  }
2690
3607
  });
2691
- Object.defineProperty(exports, 'hasRejectSlot', {
3608
+ Object.defineProperty(exports, 'enterCut', {
2692
3609
  enumerable: true,
2693
3610
  get: function () {
2694
- return hasRejectSlot;
3611
+ return enterCut;
2695
3612
  }
2696
3613
  });
2697
3614
  Object.defineProperty(exports, 'invalidateCompiledValidators', {
@@ -2718,28 +3635,34 @@ Object.defineProperty(exports, 'isPhantomType', {
2718
3635
  return isPhantomType;
2719
3636
  }
2720
3637
  });
2721
- Object.defineProperty(exports, 'isValidatorKey', {
3638
+ Object.defineProperty(exports, 'jsonSchemaPattern', {
2722
3639
  enumerable: true,
2723
3640
  get: function () {
2724
- return isValidatorKey;
3641
+ return jsonSchemaPattern;
2725
3642
  }
2726
3643
  });
2727
- Object.defineProperty(exports, 'keySlots', {
3644
+ Object.defineProperty(exports, 'metaEmpty', {
2728
3645
  enumerable: true,
2729
3646
  get: function () {
2730
- return keySlots;
3647
+ return metaEmpty;
2731
3648
  }
2732
3649
  });
2733
- Object.defineProperty(exports, 'mergeJsonSchemas', {
3650
+ Object.defineProperty(exports, 'metadataWriteCount', {
2734
3651
  enumerable: true,
2735
3652
  get: function () {
2736
- return mergeJsonSchemas;
3653
+ return metadataWriteCount;
2737
3654
  }
2738
3655
  });
2739
- Object.defineProperty(exports, 'readKeys', {
3656
+ Object.defineProperty(exports, 'pendingStatements', {
2740
3657
  enumerable: true,
2741
3658
  get: function () {
2742
- return readKeys;
3659
+ return pendingStatements;
3660
+ }
3661
+ });
3662
+ Object.defineProperty(exports, 'propAtChain', {
3663
+ enumerable: true,
3664
+ get: function () {
3665
+ return propAtChain;
2743
3666
  }
2744
3667
  });
2745
3668
  Object.defineProperty(exports, 'registerCompiledCheck', {
@@ -2748,15 +3671,33 @@ Object.defineProperty(exports, 'registerCompiledCheck', {
2748
3671
  return registerCompiledCheck;
2749
3672
  }
2750
3673
  });
2751
- Object.defineProperty(exports, 'siteBits', {
3674
+ Object.defineProperty(exports, 'stageEnds', {
3675
+ enumerable: true,
3676
+ get: function () {
3677
+ return stageEnds;
3678
+ }
3679
+ });
3680
+ Object.defineProperty(exports, 'statelessRegExp', {
3681
+ enumerable: true,
3682
+ get: function () {
3683
+ return statelessRegExp;
3684
+ }
3685
+ });
3686
+ Object.defineProperty(exports, 'touched', {
3687
+ enumerable: true,
3688
+ get: function () {
3689
+ return touched;
3690
+ }
3691
+ });
3692
+ Object.defineProperty(exports, 'uniqueName', {
2752
3693
  enumerable: true,
2753
3694
  get: function () {
2754
- return siteBits;
3695
+ return uniqueName;
2755
3696
  }
2756
3697
  });
2757
- Object.defineProperty(exports, 'siteSlotCount', {
3698
+ Object.defineProperty(exports, 'watchLayer', {
2758
3699
  enumerable: true,
2759
3700
  get: function () {
2760
- return siteSlotCount;
3701
+ return watchLayer;
2761
3702
  }
2762
3703
  });