@atscript/typescript 0.2.4 → 0.2.6

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.
@@ -76,10 +76,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
76
76
  const mapSet = Map.prototype.set;
77
77
  /** Global mutation epoch: compiled checks bound in an older epoch re-bind before use. */ let epoch = 0;
78
78
  /**
79
- * Writes of metadata maps so far (any map, any key: `annotate()`, the `Map` methods, a node's map
80
- * replaced, a layer flag or intrinsic mark registered): a lazy JSON schema or a layered map's
81
- * flattened view built before the last one is built again (see `lazyJsonSchema`, `LayerMap`).
82
- */ let metadataWrites = 0;
79
+ * Writes of type trees so far, watched or not: of metadata (any map, any key: `annotate()`, the
80
+ * `Map` methods, a node's map replaced, a layer flag or intrinsic mark registered) and of shape
81
+ * (every {@link touched} mutation, `invalidateCompiledValidators()`). What is derived from a type
82
+ * tree before the last write is derived again (`lazyJsonSchema`, `LayerMap`, `normalizeForType`).
83
+ */ let typeWrites = 0;
83
84
  /** Some bind has watched an object (until then no mutation can affect a compiled check). */ let tracking = false;
84
85
  /** Objects (nodes, type defs, metadata / props maps) read by some compiled-check bind. */ const watched = /* @__PURE__ */ new WeakSet();
85
86
  /** The current mutation epoch. */ function currentEpoch() {
@@ -89,7 +90,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
89
90
  tracking = true;
90
91
  watched.add(obj);
91
92
  }
92
- /** Records a tracked mutation of `obj` (a no-op unless some bind has read it). */ function touched(obj) {
93
+ /**
94
+ * Records a tracked mutation of `obj`: a type tree write (see `typeWrites`); compiled checks
95
+ * re-bind when some bind has read it.
96
+ */ function touched(obj) {
97
+ typeWrites++;
93
98
  if (tracking && watched.has(obj)) epoch++;
94
99
  }
95
100
  /**
@@ -115,13 +120,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
115
120
  * avoid mutating validated types per request.
116
121
  */ function invalidateCompiledValidators() {
117
122
  epoch++;
118
- metadataWrites++;
123
+ typeWrites++;
119
124
  }
120
- /** The number of metadata writes so far (see `metadataWrites`). */ function metadataWriteCount() {
121
- return metadataWrites;
125
+ /** The number of type tree writes so far (see `typeWrites`). */ function typeWriteCount() {
126
+ return typeWrites;
122
127
  }
123
128
  /** Records a write of a node's metadata the maps do not see: the node's map replaced. */ function metadataReplaced() {
124
- metadataWrites++;
129
+ typeWrites++;
125
130
  }
126
131
  /**
127
132
  * `annotate(m, key, value, true)` where map `m` holds `own` as its own value of `key`: appended in
@@ -130,7 +135,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
130
135
  if (Array.isArray(own)) {
131
136
  own.push(value);
132
137
  if (VALIDATOR_KEY_SET.has(key)) touched(m);
133
- metadataWrites++;
138
+ else typeWrites++;
134
139
  } else m.set(key, [own, value]);
135
140
  }
136
141
  /**
@@ -140,21 +145,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
140
145
  set(key, value) {
141
146
  super.set(key, value);
142
147
  if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
143
- metadataWrites++;
148
+ else typeWrites++;
144
149
  return this;
145
150
  }
146
151
  delete(key) {
147
152
  const deleted = super.delete(key);
148
- if (deleted) {
149
- if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
150
- metadataWrites++;
151
- }
153
+ if (deleted) if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
154
+ else typeWrites++;
152
155
  return deleted;
153
156
  }
154
157
  clear() {
155
158
  super.clear();
156
159
  touched(this);
157
- metadataWrites++;
158
160
  }
159
161
  /** A new map holding `entries`: no write (a new map is in no compiled check nor schema). */ constructor(entries) {
160
162
  super();
@@ -222,12 +224,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
222
224
  * a base shows through every layer over it.
223
225
  *
224
226
  * Reads go through a flattened view of the effective entries, rebuilt on the first read after any
225
- * metadata write (one global write counter: `metadataWriteCount`). The view is used only while
227
+ * type tree write (one global write counter: `typeWriteCount`). The view is used only while
226
228
  * every map below is tracked (an `AnnotationMap` or a `LayerMap`, whose writes the counter
227
229
  * sees); otherwise the reads are live. A raw write the counter does not see (a node's map swapped,
228
230
  * `node.metadata = X`, or edited in place) must be followed by `invalidateCompiledValidators()`,
229
231
  * as compiled checks require (PERF-2).
230
- */ function _define_property$5(obj, key, value) {
232
+ */ function _define_property$6(obj, key, value) {
231
233
  if (key in obj) Object.defineProperty(obj, key, {
232
234
  value,
233
235
  enumerable: true,
@@ -292,7 +294,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
292
294
  s.add(key);
293
295
  hiding = true;
294
296
  touched(m);
295
- metadataReplaced();
296
297
  }
297
298
  /** The keys map `m` hides from its bases (see {@link hideKey}), for a map replacing it. */ function moveHidden(from, to) {
298
299
  const s = HIDDEN.get(from);
@@ -313,7 +314,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
313
314
  * The flattened view (built again after a metadata write), `undefined`: read live. Internal:
314
315
  * this module's readers and the validators read it (`readable`, `filledMeta`), never write.
315
316
  */ view() {
316
- return this.w === metadataWriteCount() ? this.f : this.flatten();
317
+ return this.w === typeWriteCount() ? this.f : this.flatten();
317
318
  }
318
319
  flatten() {
319
320
  this.w = -1;
@@ -323,7 +324,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
323
324
  f = keys.length === 0 ? NO_ENTRIES : new AnnotationMap(keys.map((k) => [k, this.liveGet(k)]));
324
325
  }
325
326
  this.f = f;
326
- this.w = metadataWriteCount();
327
+ this.w = typeWriteCount();
327
328
  return f;
328
329
  }
329
330
  /** The value of `key` (not concatenated), or `MISS`; `nr`: a `passedWhenReferred:false` key. */ lookup(key, nr) {
@@ -351,7 +352,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
351
352
  return MISS;
352
353
  }
353
354
  get(key) {
354
- const view = this.w === metadataWriteCount() ? this.f : this.flatten();
355
+ const view = this.w === typeWriteCount() ? this.f : this.flatten();
355
356
  return view === void 0 ? this.liveGet(key) : mapGet.call(view, key);
356
357
  }
357
358
  /** `get` read through the layers (see the file comment). */ liveGet(key) {
@@ -412,7 +413,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
412
413
  const deleted = super.delete(key);
413
414
  if ((hiding ? HIDDEN.get(this) : void 0)?.delete(key)) {
414
415
  touched(this);
415
- metadataReplaced();
416
416
  return true;
417
417
  }
418
418
  return deleted;
@@ -437,7 +437,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
437
437
  for (const k of this.effectiveKeys()) cb.call(thisArg, this.get(k), k, this);
438
438
  }
439
439
  constructor(bases, reference = false, own) {
440
- super(own), _define_property$5(this, "b", void 0), _define_property$5(this, "r", void 0), _define_property$5(this, "f", void 0), _define_property$5(this, "w", void 0);
440
+ super(own), _define_property$6(this, "b", void 0), _define_property$6(this, "r", void 0), _define_property$6(this, "f", void 0), _define_property$6(this, "w", void 0);
441
441
  this.b = bases;
442
442
  this.r = reference;
443
443
  this.f = void 0;
@@ -454,7 +454,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
454
454
  });
455
455
  /**
456
456
  * Every map of `m`'s layers is tracked (an `AnnotationMap` or a `LayerMap`, whose writes count in
457
- * `metadataWrites`), so a flattened view of `m` stays right until the next write.
457
+ * `typeWrites`), so a flattened view of `m` stays right until the next write.
458
458
  */ function tracked(m, seen) {
459
459
  const p = Object.getPrototypeOf(m);
460
460
  if (p !== AnnotationMap.prototype && p !== LayerMap.prototype) return false;
@@ -1450,7 +1450,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1450
1450
  let result = null;
1451
1451
  for (const candidate of candidates) {
1452
1452
  const values = /* @__PURE__ */ new Set();
1453
- const indexMapping = {};
1453
+ const indexMapping = Object.create(null);
1454
1454
  let valid = true;
1455
1455
  for (let i = 0; i < items.length; i++) {
1456
1456
  const prop = items[i].type.props.get(candidate);
@@ -1904,7 +1904,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1904
1904
 
1905
1905
  //#endregion
1906
1906
  //#region packages/typescript/src/runtime/validator-fast-check.ts
1907
- function _define_property$4(obj, key, value) {
1907
+ function _define_property$5(obj, key, value) {
1908
1908
  if (key in obj) Object.defineProperty(obj, key, {
1909
1909
  value,
1910
1910
  enumerable: true,
@@ -2409,42 +2409,42 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2409
2409
  const plans = /* @__PURE__ */ new WeakMap();
2410
2410
  /** One shape for every plan, so plan field access stays monomorphic. */ let Plan = class Plan {
2411
2411
  constructor(def) {
2412
- _define_property$4(this, "def", void 0);
2413
- /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$4(this, "stamp", void 0);
2414
- /** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$4(this, "metaStamp", void 0);
2415
- _define_property$4(this, "op", void 0);
2416
- _define_property$4(this, "type", void 0);
2417
- _define_property$4(this, "optional", void 0);
2418
- _define_property$4(this, "metadata", void 0);
2419
- _define_property$4(this, "kind", void 0);
2420
- _define_property$4(this, "designType", void 0);
2421
- _define_property$4(this, "literal", void 0);
2422
- /** String plans: compiled `@expect.pattern` regexes by position (checked against the live entry). */ _define_property$4(this, "regexes", void 0);
2412
+ _define_property$5(this, "def", void 0);
2413
+ /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$5(this, "stamp", void 0);
2414
+ /** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$5(this, "metaStamp", void 0);
2415
+ _define_property$5(this, "op", void 0);
2416
+ _define_property$5(this, "type", void 0);
2417
+ _define_property$5(this, "optional", void 0);
2418
+ _define_property$5(this, "metadata", void 0);
2419
+ _define_property$5(this, "kind", void 0);
2420
+ _define_property$5(this, "designType", void 0);
2421
+ _define_property$5(this, "literal", void 0);
2422
+ /** String plans: compiled `@expect.pattern` regexes by position (checked against the live entry). */ _define_property$5(this, "regexes", void 0);
2423
2423
  /**
2424
2424
  * Annotation keys the node's check reads, and their values (`undefined` when absent):
2425
2425
  * string `meta.required, expect.minLength, maxLength, pattern`; number `expect.int, min,
2426
2426
  * max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`;
2427
2427
  * object `expect.minKeys, maxKeys`.
2428
- */ _define_property$4(this, "k0", void 0);
2429
- _define_property$4(this, "k1", void 0);
2430
- _define_property$4(this, "k2", void 0);
2431
- _define_property$4(this, "k3", void 0);
2432
- _define_property$4(this, "k4", void 0);
2433
- _define_property$4(this, "m0", void 0);
2434
- _define_property$4(this, "m1", void 0);
2435
- _define_property$4(this, "m2", void 0);
2436
- _define_property$4(this, "m3", void 0);
2437
- _define_property$4(this, "m4", void 0);
2438
- _define_property$4(this, "props", void 0);
2439
- _define_property$4(this, "propsPatterns", void 0);
2440
- _define_property$4(this, "keys", void 0);
2441
- /** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$4(this, "edges", void 0);
2442
- /** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$4(this, "byKey", void 0);
2443
- _define_property$4(this, "nodes", void 0);
2444
- _define_property$4(this, "children", void 0);
2445
- _define_property$4(this, "of", void 0);
2446
- _define_property$4(this, "ofPlan", void 0);
2447
- _define_property$4(this, "items", void 0);
2428
+ */ _define_property$5(this, "k0", void 0);
2429
+ _define_property$5(this, "k1", void 0);
2430
+ _define_property$5(this, "k2", void 0);
2431
+ _define_property$5(this, "k3", void 0);
2432
+ _define_property$5(this, "k4", void 0);
2433
+ _define_property$5(this, "m0", void 0);
2434
+ _define_property$5(this, "m1", void 0);
2435
+ _define_property$5(this, "m2", void 0);
2436
+ _define_property$5(this, "m3", void 0);
2437
+ _define_property$5(this, "m4", void 0);
2438
+ _define_property$5(this, "props", void 0);
2439
+ _define_property$5(this, "propsPatterns", void 0);
2440
+ _define_property$5(this, "keys", void 0);
2441
+ /** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$5(this, "edges", void 0);
2442
+ /** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$5(this, "byKey", void 0);
2443
+ _define_property$5(this, "nodes", void 0);
2444
+ _define_property$5(this, "children", void 0);
2445
+ _define_property$5(this, "of", void 0);
2446
+ _define_property$5(this, "ofPlan", void 0);
2447
+ _define_property$5(this, "items", void 0);
2448
2448
  this.def = def;
2449
2449
  this.stamp = -1;
2450
2450
  this.metaStamp = -1;
@@ -2880,7 +2880,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2880
2880
 
2881
2881
  //#endregion
2882
2882
  //#region packages/typescript/src/runtime/validator.ts
2883
- function _define_property$3(obj, key, value) {
2883
+ function _define_property$4(obj, key, value) {
2884
2884
  if (key in obj) Object.defineProperty(obj, key, {
2885
2885
  value,
2886
2886
  enumerable: true,
@@ -3615,17 +3615,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3615
3615
  return count;
3616
3616
  }
3617
3617
  constructor(def, opts) {
3618
- _define_property$3(this, "def", void 0);
3619
- _define_property$3(this, "opts", void 0);
3620
- _define_property$3(this, "hasPlugins", void 0);
3621
- _define_property$3(this, "hasReplace", void 0);
3622
- _define_property$3(this, "replaceCache", void 0);
3623
- /** Validation errors collected during the last {@link validate} call. */ _define_property$3(this, "errors", void 0);
3624
- _define_property$3(this, "stackErrors", void 0);
3625
- _define_property$3(this, "pathSegments", void 0);
3626
- _define_property$3(this, "depth", void 0);
3627
- _define_property$3(this, "limitExceeded", void 0);
3628
- _define_property$3(this, "context", void 0);
3618
+ _define_property$4(this, "def", void 0);
3619
+ _define_property$4(this, "opts", void 0);
3620
+ _define_property$4(this, "hasPlugins", void 0);
3621
+ _define_property$4(this, "hasReplace", void 0);
3622
+ _define_property$4(this, "replaceCache", void 0);
3623
+ /** Validation errors collected during the last {@link validate} call. */ _define_property$4(this, "errors", void 0);
3624
+ _define_property$4(this, "stackErrors", void 0);
3625
+ _define_property$4(this, "pathSegments", void 0);
3626
+ _define_property$4(this, "depth", void 0);
3627
+ _define_property$4(this, "limitExceeded", void 0);
3628
+ _define_property$4(this, "context", void 0);
3629
3629
  /**
3630
3630
  * The unions over objects this call decided inside union branches (value → outcomes). A union
3631
3631
  * nested in its own branches, many branches each, is reached again with the same value and path
@@ -3635,17 +3635,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3635
3635
  * never make it. It decides each such union once, with the same result and the same error object
3636
3636
  * (both depend only on these, the options and the input, which the walk never changes), and
3637
3637
  * records the same strips again.
3638
- */ _define_property$3(this, "unionMemo", void 0);
3639
- /** Union branches being checked (`> 0`: inside a union branch). */ _define_property$3(this, "unionDepth", void 0);
3640
- /** Failed branches of unions over objects inside union branches (see `unionMemo`). */ _define_property$3(this, "nestedFailures", void 0);
3641
- /** Wasted union branches since the outermost union was entered (see `unionMemo`). */ _define_property$3(this, "wasted", void 0);
3638
+ */ _define_property$4(this, "unionMemo", void 0);
3639
+ /** Union branches being checked (`> 0`: inside a union branch). */ _define_property$4(this, "unionDepth", void 0);
3640
+ /** Failed branches of unions over objects inside union branches (see `unionMemo`). */ _define_property$4(this, "nestedFailures", void 0);
3641
+ /** Wasted union branches since the outermost union was entered (see `unionMemo`). */ _define_property$4(this, "wasted", void 0);
3642
3642
  /**
3643
3643
  * `unknownProps: 'strip'`: the unknown keys of the objects that passed (`object, key, …`), in the
3644
3644
  * order the objects completed, then in key order. A rejected union branch, pattern property
3645
3645
  * attempt or plugin sub-validation drops what it recorded; the keys are deleted once the whole
3646
3646
  * call passes (`performStrips`).
3647
- */ _define_property$3(this, "strips", void 0);
3648
- /** The context the plugins get (see {@link pluginContext}), made on the first plugin call. */ _define_property$3(this, "pluginCtx", void 0);
3647
+ */ _define_property$4(this, "strips", void 0);
3648
+ /** The context the plugins get (see {@link pluginContext}), made on the first plugin call. */ _define_property$4(this, "pluginCtx", void 0);
3649
3649
  this.def = def;
3650
3650
  this.errors = [];
3651
3651
  this.stackErrors = [];
@@ -3672,8 +3672,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3672
3672
  return typeof annotation === "object" && annotation !== null ? annotation.message || void 0 : void 0;
3673
3673
  }
3674
3674
  /**
3675
- * Decided discriminators, by union `items` (reported errors only: a union's discriminator is
3676
- * looked for once its value failed). An entry is reused while the items, their type defs and the
3675
+ * Decided discriminators, by union `items` (the validator's reported errors, the branch
3676
+ * `normalizeForType` takes). An entry is reused while the items, their type defs and the
3677
3677
  * discriminator props are the same objects.
3678
3678
  */ const discCache = /* @__PURE__ */ new WeakMap();
3679
3679
  /**
@@ -3762,7 +3762,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3762
3762
  }
3763
3763
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */ var ValidatorError = class extends Error {
3764
3764
  constructor(errors) {
3765
- super(`${errors[0].path ? errors[0].path + ": " : ""}${errors[0].message}`), _define_property$3(this, "errors", void 0), _define_property$3(this, "name", void 0), this.errors = errors, this.name = "Validation Error";
3765
+ super(`${errors[0].path ? errors[0].path + ": " : ""}${errors[0].message}`), _define_property$4(this, "errors", void 0), _define_property$4(this, "name", void 0), this.errors = errors, this.name = "Validation Error";
3766
3766
  }
3767
3767
  };
3768
3768
 
@@ -3996,12 +3996,436 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3996
3996
  }
3997
3997
 
3998
3998
  //#endregion
3999
- //#region packages/typescript/src/runtime/coerce.ts
3999
+ //#region packages/typescript/src/runtime/copy-on-change.ts
4000
4000
  /**
4001
- * Internal sentinel returned when a value cannot be coerced to a type node.
4002
- * Drives union branch selection without allocating per-node result objects.
4003
- */ const NO_MATCH = Symbol("atscript.coerce.no-match");
4001
+ * Internal sentinel: the value cannot be taken by a type node (drives union branch selection in
4002
+ * `coerce.ts` and `normalize.ts`). A {@link mapProps} step returns it to reject the whole object.
4003
+ */ const NO_MATCH = Symbol("atscript.no-match");
4004
+ /**
4005
+ * Maps the props of plain object `value` with `step` (props without a def — declared or pattern —
4006
+ * are kept as they are). Copy-on-first-change: allocates the output only when some prop changed,
4007
+ * else returns `value`; an own `__proto__` key stays an own key (never the output's prototype).
4008
+ * NO_MATCH when a step returns it.
4009
+ */ function mapProps(type, value, step, ctx) {
4010
+ const keys = Object.keys(value);
4011
+ let out;
4012
+ for (let i = 0; i < keys.length; i++) {
4013
+ const key = keys[i];
4014
+ const input = value[key];
4015
+ let def = type.props.get(key);
4016
+ if (!def) {
4017
+ for (const { pattern, def: patternDef } of type.propsPatterns) if (pattern.test(key)) {
4018
+ def = patternDef;
4019
+ break;
4020
+ }
4021
+ }
4022
+ const mapped = def ? step(def, input, ctx) : input;
4023
+ if (mapped === NO_MATCH) return NO_MATCH;
4024
+ if (out) setOwn(out, key, mapped);
4025
+ else if (mapped !== input) {
4026
+ out = {};
4027
+ for (let j = 0; j < i; j++) setOwn(out, keys[j], value[keys[j]]);
4028
+ setOwn(out, key, mapped);
4029
+ }
4030
+ }
4031
+ return out ?? value;
4032
+ }
4004
4033
  /**
4034
+ * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
4035
+ * items). Copy-on-first-change, as {@link mapProps}.
4036
+ */ function mapItems(value, of, step, ctx) {
4037
+ return mapList(value, (input, i) => step(Array.isArray(of) ? of[i] : of, input, ctx));
4038
+ }
4039
+ /** Maps the items of `list` with `step`. Copy-on-first-change: `list` itself when none changed. */ function mapList(list, step) {
4040
+ let out;
4041
+ for (let i = 0; i < list.length; i++) {
4042
+ const mapped = step(list[i], i);
4043
+ if (out) out.push(mapped);
4044
+ else if (mapped !== list[i]) {
4045
+ out = list.slice(0, i);
4046
+ out.push(mapped);
4047
+ }
4048
+ }
4049
+ return out ?? list;
4050
+ }
4051
+ /**
4052
+ * Maps the own values of JSON object `obj` with `step`. Copy-on-first-change: `obj` itself when
4053
+ * none changed; an own `__proto__` key stays an own key.
4054
+ */ function mapEntries(obj, step) {
4055
+ let out;
4056
+ for (const key of Object.keys(obj)) {
4057
+ const mapped = step(key, obj[key]);
4058
+ if (mapped !== obj[key]) {
4059
+ out ?? (out = { ...obj });
4060
+ setOwn(out, key, mapped);
4061
+ }
4062
+ }
4063
+ return out ?? obj;
4064
+ }
4065
+ /** Whether `value` is a plain object (`{}` or prototype-less): class instances are not. */ function isPlainObject$1(value) {
4066
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4067
+ const proto = Object.getPrototypeOf(value);
4068
+ return proto === Object.prototype || proto === null;
4069
+ }
4070
+ /**
4071
+ * Sets own property `key` of `out`: `__proto__` as an own data property (an assignment would set
4072
+ * the object's prototype instead — input parsed from JSON may carry such a key).
4073
+ */ function setOwn(out, key, value) {
4074
+ if (key === "__proto__") Object.defineProperty(out, key, {
4075
+ value,
4076
+ writable: true,
4077
+ enumerable: true,
4078
+ configurable: true
4079
+ });
4080
+ else out[key] = value;
4081
+ }
4082
+
4083
+ //#endregion
4084
+ //#region packages/typescript/src/runtime/normalize.ts
4085
+ const TRIM = 1;
4086
+ const LOWERCASE = 2;
4087
+ const UPPERCASE = 4;
4088
+ /**
4089
+ * Whether each node's subtree has normalizers: valid until the next type tree write (metadata or
4090
+ * shape) or `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
4091
+ */ let reach = /* @__PURE__ */ new WeakMap();
4092
+ let stampWrites = -1;
4093
+ function newJudges(opts) {
4094
+ const root = {
4095
+ ...opts,
4096
+ errorLimit: 1
4097
+ };
4098
+ delete root.translate;
4099
+ if (root.unknownProps === "strip") root.unknownProps = "ignore";
4100
+ const judge = {
4101
+ opts: root,
4102
+ validators: /* @__PURE__ */ new WeakMap()
4103
+ };
4104
+ return {
4105
+ root: judge,
4106
+ nested: root.partial === true ? {
4107
+ opts: {
4108
+ ...root,
4109
+ partial: false
4110
+ },
4111
+ validators: /* @__PURE__ */ new WeakMap()
4112
+ } : judge
4113
+ };
4114
+ }
4115
+ const DEFAULT_JUDGES = newJudges({});
4116
+ /** The judges by the options object passed (the same options: the same validators). */ const judgesByOpts = /* @__PURE__ */ new WeakMap();
4117
+ function judgesFor(opts) {
4118
+ if (!opts) return DEFAULT_JUDGES;
4119
+ let found = judgesByOpts.get(opts);
4120
+ if (!found) {
4121
+ found = newJudges(opts);
4122
+ judgesByOpts.set(opts, found);
4123
+ }
4124
+ return found;
4125
+ }
4126
+ /**
4127
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
4128
+ * `@normalize.lowercase` and `@normalize.uppercase`.
4129
+ *
4130
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
4131
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
4132
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
4133
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
4134
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
4135
+ * uppercase. Other values (including class instances such as `Date`) and strings without
4136
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
4137
+ *
4138
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
4139
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
4140
+ * value is left as it is. A union normalizes a value only when the result does not depend on
4141
+ * which branch takes it:
4142
+ * - an object union with a discriminator (a literal prop every object branch requires, see
4143
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
4144
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
4145
+ * only when the normalized string equals its literal): when they all give the same result it
4146
+ * is used; when they differ, the branches whose result their own validator accepts are kept,
4147
+ * and the result is used when they agree; else the value is returned untouched (ambiguous).
4148
+ * The branch validators take `opts` — pass the options the result will be validated with
4149
+ * (`partial`, `unknownProps`, …) so a branch is judged as the validator will judge it; default
4150
+ * options when omitted. (`unknownProps: 'strip'` judges as `'ignore'`: nothing is stripped.)
4151
+ *
4152
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
4153
+ *
4154
+ * @example
4155
+ * ```ts
4156
+ * // @normalize.trim @normalize.lowercase email: string.email
4157
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
4158
+ * // judged as a partial update will be validated
4159
+ * normalizeForType(Patch, body, { partial: true })
4160
+ * ```
4161
+ */ function normalizeForType(def, value, opts) {
4162
+ const writes = typeWriteCount();
4163
+ if (writes !== stampWrites) {
4164
+ stampWrites = writes;
4165
+ reach = /* @__PURE__ */ new WeakMap();
4166
+ }
4167
+ if (!hasNormalizers(def)) return value;
4168
+ const result = normalize(def, value, 0, {
4169
+ memo: /* @__PURE__ */ new Map(),
4170
+ root: value,
4171
+ opts
4172
+ });
4173
+ return result === NO_MATCH ? value : result;
4174
+ }
4175
+ /** The nodes `def`'s value walk can enter (props, pattern props, items, elements). */ function childrenOf(def) {
4176
+ const type = def.type;
4177
+ switch (type.kind) {
4178
+ case "object": {
4179
+ const t = type;
4180
+ const out = [...t.props.values()];
4181
+ for (const p of t.propsPatterns) out.push(p.def);
4182
+ return out;
4183
+ }
4184
+ case "array": return [type.of];
4185
+ case "union":
4186
+ case "intersection":
4187
+ case "tuple": return type.items;
4188
+ default: return [];
4189
+ }
4190
+ }
4191
+ /**
4192
+ * Whether `def` or a node its walk reaches has normalizers. Answers (and caches) every node
4193
+ * reached, recursive types included: collects the reached nodes with their parents, then marks
4194
+ * the nodes with normalizers and, back along the parents, every node that reaches one.
4195
+ */ function hasNormalizers(def) {
4196
+ const known = reach.get(def);
4197
+ if (known !== void 0) return known;
4198
+ const parents = new Map([[def, []]]);
4199
+ const marked = [];
4200
+ const todo = [def];
4201
+ while (todo.length > 0) {
4202
+ const node = todo.pop();
4203
+ if (flagsOf(node, 0) !== 0) marked.push(node);
4204
+ for (const child of childrenOf(node)) {
4205
+ const cached = reach.get(child);
4206
+ if (cached !== void 0) {
4207
+ if (cached) marked.push(node);
4208
+ continue;
4209
+ }
4210
+ let of = parents.get(child);
4211
+ if (!of) {
4212
+ parents.set(child, of = []);
4213
+ todo.push(child);
4214
+ }
4215
+ of.push(node);
4216
+ }
4217
+ }
4218
+ for (const node of parents.keys()) reach.set(node, false);
4219
+ while (marked.length > 0) {
4220
+ const node = marked.pop();
4221
+ if (!reach.get(node)) {
4222
+ reach.set(node, true);
4223
+ marked.push(...parents.get(node));
4224
+ }
4225
+ }
4226
+ return reach.get(def);
4227
+ }
4228
+ /** The normalizer flags of `def`, on top of `inherited` (a union's, for its branches). */ function flagsOf(def, inherited) {
4229
+ const meta = def.metadata;
4230
+ if (metaEmpty(meta)) return inherited;
4231
+ let flags = inherited;
4232
+ if (meta.get("normalize.trim")) flags |= TRIM;
4233
+ if (meta.get("normalize.lowercase")) flags |= LOWERCASE;
4234
+ if (meta.get("normalize.uppercase")) flags |= UPPERCASE;
4235
+ return flags;
4236
+ }
4237
+ /** `value` with normalizer `flags` applied, in their fixed order (see {@link flagsOf}). */ function applyFlags(value, flags) {
4238
+ let out = value;
4239
+ if (flags & TRIM) out = out.trim();
4240
+ if (flags & LOWERCASE) out = out.toLowerCase();
4241
+ if (flags & UPPERCASE) out = out.toUpperCase();
4242
+ return out;
4243
+ }
4244
+ /**
4245
+ * The normalized value, or NO_MATCH when `def` cannot take it (its kind does not fit the value).
4246
+ * `inherited`: the normalizer flags of the unions / intersections `def` is a member of.
4247
+ *
4248
+ * Objects and unions are memoized per call by input object: a recursive union without a
4249
+ * discriminator is tried for every branch at every level, which without it is exponential in
4250
+ * the depth of the value.
4251
+ */ function normalize(def, value, inherited, walk) {
4252
+ if (value === void 0 || value === null) return value;
4253
+ if (inherited === 0 && !hasNormalizers(def)) return takes$1(def, value) ? value : NO_MATCH;
4254
+ const type = def.type;
4255
+ switch (type.kind) {
4256
+ case "": {
4257
+ const out = typeof value === "string" && type.designType === "string" ? applyFlags(value, flagsOf(def, inherited)) : value;
4258
+ return takes$1(def, out) ? out : NO_MATCH;
4259
+ }
4260
+ case "object": {
4261
+ if (!isPlainObject$1(value)) return NO_MATCH;
4262
+ const entries = entriesOf(walk.memo, value);
4263
+ return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, walk));
4264
+ }
4265
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, walk) : NO_MATCH;
4266
+ case "tuple": {
4267
+ const items = type.items;
4268
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, walk) : NO_MATCH;
4269
+ }
4270
+ case "union": {
4271
+ const flags = flagsOf(def, inherited);
4272
+ const items = type.items;
4273
+ if (typeof value !== "object") return normalizeUnion(items, value, flags, walk);
4274
+ const entries = entriesOf(walk.memo, value);
4275
+ return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, walk));
4276
+ }
4277
+ case "intersection": {
4278
+ const flags = flagsOf(def, inherited);
4279
+ let current = value;
4280
+ for (const item of type.items) {
4281
+ const result = normalize(item, current, flags, walk);
4282
+ if (result === NO_MATCH) return NO_MATCH;
4283
+ current = result;
4284
+ }
4285
+ return current;
4286
+ }
4287
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
4288
+ }
4289
+ }
4290
+ /** The memoized results for input object `value` (see {@link normalize}). */ function entriesOf(memo, value) {
4291
+ let entries = memo.get(value);
4292
+ if (!entries) {
4293
+ entries = [];
4294
+ memo.set(value, entries);
4295
+ }
4296
+ return entries;
4297
+ }
4298
+ /** The memoized result for `type` and `flags`, `undefined` when none. */ function recall(entries, type, flags) {
4299
+ for (const [t, f, result] of entries) if (t === type && f === flags) return result;
4300
+ }
4301
+ /** Memoizes `result` for `type` and `flags` and returns it. */ function remember(entries, type, flags, result) {
4302
+ entries.push([
4303
+ type,
4304
+ flags,
4305
+ result
4306
+ ]);
4307
+ return result;
4308
+ }
4309
+ /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, walk) {
4310
+ if (!hasNormalizers(def)) return input;
4311
+ const result = normalize(def, input, 0, walk);
4312
+ return result === NO_MATCH ? input : result;
4313
+ }
4314
+ /**
4315
+ * A prop: as {@link normalizeItem}, but NO_MATCH (the object is not this type) when a literal prop
4316
+ * (`kind: 'cat'`, `kind: 'cat' | null`, see {@link literalNodes}) holds another value.
4317
+ */ function normalizeProp(def, input, walk) {
4318
+ const out = normalizeItem(def, input, walk);
4319
+ if (out === input && input !== void 0 && input !== null) {
4320
+ const literals = literalNodes(def);
4321
+ if (literals && !literals.some((l) => l.node.type.value === input)) return NO_MATCH;
4322
+ }
4323
+ return out;
4324
+ }
4325
+ /**
4326
+ * The literals a literal prop can hold: `def` itself when it is a literal (`kind: 'cat'`), the
4327
+ * literals of a union of literals, `null` and `undefined` (`kind: 'cat' | null`, nested unions and
4328
+ * aliases too); `undefined` for any other type. Each with the normalizers of the nodes on its way
4329
+ * (a union's apply to its members). A literal prop holding another value tells that an object is
4330
+ * not of its type, for normalization and coercion alike (see `coerce.ts`).
4331
+ */ function literalNodes(def, inherited = 0) {
4332
+ const type = def.type;
4333
+ if (type.kind === "") return type.value === void 0 ? void 0 : [{
4334
+ node: def,
4335
+ flags: flagsOf(def, inherited)
4336
+ }];
4337
+ if (type.kind !== "union") return;
4338
+ const flags = flagsOf(def, inherited);
4339
+ const out = [];
4340
+ for (const item of type.items) {
4341
+ const designType = item.type.designType;
4342
+ if (item.type.kind === "" && (designType === "null" || designType === "undefined")) continue;
4343
+ const inner = literalNodes(item, flags);
4344
+ if (!inner) return;
4345
+ out.push(...inner);
4346
+ }
4347
+ return out.length > 0 ? out : void 0;
4348
+ }
4349
+ /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes$1(def, value) {
4350
+ const type = def.type;
4351
+ switch (type.kind) {
4352
+ case "": {
4353
+ const final = type;
4354
+ switch (final.designType) {
4355
+ case "string":
4356
+ case "number":
4357
+ case "boolean": return typeof value === final.designType && (final.value === void 0 || value === final.value);
4358
+ case "decimal": return typeof value === "string";
4359
+ case "object": return typeof value === "object";
4360
+ case "any":
4361
+ case "phantom": return true;
4362
+ default: return false;
4363
+ }
4364
+ }
4365
+ case "object": return isPlainObject$1(value);
4366
+ case "array": return Array.isArray(value);
4367
+ case "tuple": return Array.isArray(value) && value.length === type.items.length;
4368
+ case "union": return type.items.some((item) => takes$1(item, value));
4369
+ case "intersection": return type.items.every((item) => takes$1(item, value));
4370
+ default: return false;
4371
+ }
4372
+ }
4373
+ /**
4374
+ * A union: the branch a discriminator names, else the one result every branch that can take
4375
+ * the value agrees on — or, when they differ, the one result of the branches whose validator
4376
+ * accepts their result (NO_MATCH when none can take the value or it stays ambiguous).
4377
+ */ function normalizeUnion(items, value, flags, walk) {
4378
+ if (isPlainObject$1(value)) {
4379
+ const disc = unionDiscriminator(items);
4380
+ if (disc) {
4381
+ const tag = value[disc.property];
4382
+ for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, walk);
4383
+ }
4384
+ }
4385
+ let first = NO_MATCH;
4386
+ let firstItem;
4387
+ let rest;
4388
+ for (const item of items) {
4389
+ const out = normalize(item, value, flags, walk);
4390
+ if (out === NO_MATCH) continue;
4391
+ if (first === NO_MATCH) {
4392
+ first = out;
4393
+ firstItem = item;
4394
+ } else (rest ?? (rest = [])).push([item, out]);
4395
+ }
4396
+ if (!rest || rest.every(([, out]) => sameValue(out, first))) return first;
4397
+ rest.unshift([firstItem, first]);
4398
+ const judges = judgesFor(walk.opts);
4399
+ const judge = value === walk.root ? judges.root : judges.nested;
4400
+ let accepted = NO_MATCH;
4401
+ for (const [item, out] of rest) {
4402
+ if (!branchValidator(judge, item).validate(out, true)) continue;
4403
+ if (accepted === NO_MATCH) accepted = out;
4404
+ else if (!sameValue(accepted, out)) return NO_MATCH;
4405
+ }
4406
+ return accepted;
4407
+ }
4408
+ /** Union branch `def`'s validator, judging its own normalized result (see {@link TJudges}). */ function branchValidator(judge, def) {
4409
+ let validator = judge.validators.get(def);
4410
+ if (!validator) {
4411
+ validator = new Validator(def, judge.opts);
4412
+ judge.validators.set(def, validator);
4413
+ }
4414
+ return validator;
4415
+ }
4416
+ /** Whether two results of the same input are equal (shared, untouched parts are identical). */ function sameValue(a, b) {
4417
+ if (a === b) return true;
4418
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
4419
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
4420
+ const keys = Object.keys(a);
4421
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
4422
+ }
4423
+ return false;
4424
+ }
4425
+
4426
+ //#endregion
4427
+ //#region packages/typescript/src/runtime/coerce.ts
4428
+ /**
4005
4429
  * Coerces string-transport input (route params, query strings) toward the
4006
4430
  * scalar shapes an annotated type expects.
4007
4431
  *
@@ -4014,9 +4438,19 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4014
4438
  * - Strings targeting `number` are trimmed and parsed via `Number()`; only
4015
4439
  * finite results are accepted.
4016
4440
  * - Strings targeting `boolean` accept `"true"/"1"` and `"false"/"0"`.
4017
- * - Unions try each branch in declared order; the first successful parse wins.
4441
+ * - Unions pick one branch and coerce the value against it only (linear, no
4442
+ * backtracking). A scalar branch takes what it parses; an object (tuple)
4443
+ * branch takes a plain object (an array of its length) unless a literal
4444
+ * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
4445
+ * does not coerce to it, a string compared after the normalizers of the
4446
+ * literal and of the unions it is in. An object takes the branch its
4447
+ * discriminator names (as the validator does: the literal itself first, else
4448
+ * `"2"` names a `2` literal), else the first whose shape it has (required
4449
+ * props present, no undeclared key), else the first that takes it. When no
4450
+ * branch takes the value, it is returned untouched.
4018
4451
  * - Objects recurse into props when the input is a plain object (covers
4019
- * `@Query()` DTOs where every field arrives as a string).
4452
+ * `@Query()` DTOs where every field arrives as a string), whatever their
4453
+ * literal props hold unless tried as a union branch.
4020
4454
  * - Arrays and tuples coerce items; intersections apply each member in order.
4021
4455
  * - `string` / `decimal` targets never change string input.
4022
4456
  *
@@ -4050,18 +4484,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4050
4484
  }
4051
4485
  case "object":
4052
4486
  if (!isPlainObject$1(value)) return NO_MATCH;
4053
- return coerceProps(def, value);
4054
- case "array": return Array.isArray(value) ? coerceItems(value, type.of) : NO_MATCH;
4487
+ return mapProps(type, value, coerceChild, void 0);
4488
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
4055
4489
  case "tuple": {
4056
4490
  const items = type.items;
4057
- return Array.isArray(value) && value.length === items.length ? coerceItems(value, void 0, items) : NO_MATCH;
4491
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
4492
+ }
4493
+ case "union": {
4494
+ const branch = branchOf(type.items, value);
4495
+ return branch ? coerce(branch, value) : NO_MATCH;
4058
4496
  }
4059
- case "union":
4060
- for (const item of type.items) {
4061
- const result = coerce(item, value);
4062
- if (result !== NO_MATCH) return result;
4063
- }
4064
- return NO_MATCH;
4065
4497
  case "intersection": {
4066
4498
  let current = value;
4067
4499
  for (const item of type.items) {
@@ -4100,56 +4532,99 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4100
4532
  }
4101
4533
  }
4102
4534
  /**
4103
- * Coerces the props of a plain object. Copy-on-first-change: allocates the
4104
- * output object only when some prop actually coerced, else returns the input.
4105
- */ function coerceProps(def, value) {
4106
- const keys = Object.keys(value);
4107
- let out;
4108
- for (let i = 0; i < keys.length; i++) {
4109
- const key = keys[i];
4110
- const input = value[key];
4111
- let propDef = def.type.props.get(key);
4112
- if (!propDef) {
4113
- for (const { pattern, def: patternDef } of def.type.propsPatterns) if (pattern.test(key)) {
4114
- propDef = patternDef;
4115
- break;
4116
- }
4117
- }
4118
- let coerced = input;
4119
- if (propDef) {
4120
- const result = coerce(propDef, input);
4121
- if (result !== NO_MATCH) coerced = result;
4122
- }
4123
- if (out) out[key] = coerced;
4124
- else if (coerced !== input) {
4125
- out = {};
4126
- for (let j = 0; j < i; j++) out[keys[j]] = value[keys[j]];
4127
- out[key] = coerced;
4128
- }
4535
+ * The branch of union `items` that takes `value` (see {@link takes}): the one an object's
4536
+ * discriminator names; else, for an object, the first that takes it and whose shape it has (see
4537
+ * {@link fits}); else the first that takes it, in declared order (a partial patch); `undefined`
4538
+ * when none does.
4539
+ */ function branchOf(items, value) {
4540
+ let first;
4541
+ if (isPlainObject$1(value)) {
4542
+ const named = discriminatedBranch(items, value);
4543
+ if (named && takes(named, value)) return named;
4544
+ for (const item of items) if (takes(item, value)) {
4545
+ if (fits(item, value)) return item;
4546
+ first ?? (first = item);
4547
+ }
4548
+ return first;
4549
+ }
4550
+ return items.find((item) => takes(item, value));
4551
+ }
4552
+ /**
4553
+ * Whether object `value` has the shape of branch `def`, by its own keys alone: every required
4554
+ * prop is one of them, and each of them is a prop (or matches a prop pattern) of the branch. A
4555
+ * union: one of its branches; a branch that is not an object (nor an intersection of objects)
4556
+ * has any shape.
4557
+ */ function fits(def, value) {
4558
+ if (def.type.kind === "union") return def.type.items.some((item) => fits(item, value));
4559
+ const objects = [];
4560
+ if (!objectsOf(def, objects)) return true;
4561
+ for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return false;
4562
+ return Object.keys(value).every((key) => objects.some((o) => o.props.has(key) || o.propsPatterns.some((p) => p.pattern.test(key))));
4563
+ }
4564
+ /** Collects the objects `def` is (an object, an intersection of objects); `false` for others. */ function objectsOf(def, out) {
4565
+ const type = def.type;
4566
+ if (type.kind === "object") {
4567
+ out.push(type);
4568
+ return true;
4129
4569
  }
4130
- return out ?? value;
4570
+ return type.kind === "intersection" && type.items.every((item) => objectsOf(item, out));
4131
4571
  }
4132
4572
  /**
4133
- * Coerces array/tuple items against `of` (arrays) or `items[i]` (tuples).
4134
- * Copy-on-first-change, same as {@link coerceProps}.
4135
- */ function coerceItems(value, of, items) {
4136
- let out;
4137
- for (let i = 0; i < value.length; i++) {
4138
- const input = value[i];
4139
- const result = coerce(of ?? items[i], input);
4140
- const coerced = result === NO_MATCH ? input : result;
4141
- if (out) out.push(coerced);
4142
- else if (coerced !== input) {
4143
- out = value.slice(0, i);
4144
- out.push(coerced);
4573
+ * Whether union branch `def` takes `value`: exactly when coercing `value` against it does not
4574
+ * fail (a branch taken never fails after it), decided from `value` itself — its kind, its length,
4575
+ * its direct literal props and items — never from what it holds deeper. A union takes one branch
4576
+ * once, so coercion is linear in the value.
4577
+ */ function takes(def, value) {
4578
+ if (value === void 0 || value === null) return def.optional === true;
4579
+ const type = def.type;
4580
+ switch (type.kind) {
4581
+ case "": return coerce(def, value) !== NO_MATCH;
4582
+ case "object":
4583
+ if (!isPlainObject$1(value)) return false;
4584
+ for (const [key, prop] of type.props) if (Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
4585
+ return true;
4586
+ case "array": return Array.isArray(value);
4587
+ case "tuple": {
4588
+ const items = type.items;
4589
+ return Array.isArray(value) && value.length === items.length && items.every((item, i) => holdsLiteral(item, value[i]));
4145
4590
  }
4591
+ case "union": return type.items.some((item) => takes(item, value));
4592
+ case "intersection": return type.items.every((item) => takes(item, value));
4593
+ default: return false;
4146
4594
  }
4147
- return out ?? value;
4148
4595
  }
4149
- function isPlainObject$1(value) {
4150
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4151
- const proto = Object.getPrototypeOf(value);
4152
- return proto === Object.prototype || proto === null;
4596
+ /**
4597
+ * Whether prop (item) `def` of a union branch can hold `input`: anything, but a literal prop
4598
+ * (see `literalNodes`: `kind: 'cat'`, `kind: 'cat' | null`) only a value that coerces to one of
4599
+ * its literals — a string after the normalizers on the literal's way (`' Cat '` to `'cat'` with
4600
+ * `@normalize.trim @normalize.lowercase`). `null` / `undefined` are left to the validator.
4601
+ */ function holdsLiteral(def, input) {
4602
+ if (input === void 0 || input === null) return true;
4603
+ const literals = literalNodes(def);
4604
+ return !literals || literals.some((literal) => coercesTo(literal, input));
4605
+ }
4606
+ /** Whether `input` coerces to the value of `literal` (see `holdsLiteral`). */ function coercesTo(literal, input) {
4607
+ const value = typeof input === "string" ? applyFlags(input, literal.flags) : input;
4608
+ return coerce(literal.node, value) !== NO_MATCH;
4609
+ }
4610
+ /**
4611
+ * The branch of union `items` the discriminator of object `value` names: its literal itself,
4612
+ * else the one its value coerces to (`"2"` names `2`, see {@link coercesTo}); `undefined` when the
4613
+ * union has no discriminator or the value names no branch.
4614
+ */ function discriminatedBranch(items, value) {
4615
+ const disc = unionDiscriminator(items);
4616
+ if (disc === void 0) return;
4617
+ const tag = Object.hasOwn(value, disc.property) ? value[disc.property] : void 0;
4618
+ if (tag === void 0 || tag === null) return;
4619
+ for (const [index, literal] of disc.branches) if (literal === tag) return items[index];
4620
+ for (const [index] of disc.branches) {
4621
+ const prop = items[index].type.props.get(disc.property);
4622
+ if (prop && holdsLiteral(prop, tag)) return items[index];
4623
+ }
4624
+ }
4625
+ /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
4626
+ const result = coerce(def, input);
4627
+ return result === NO_MATCH ? input : result;
4153
4628
  }
4154
4629
 
4155
4630
  //#endregion
@@ -4212,7 +4687,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4212
4687
 
4213
4688
  //#endregion
4214
4689
  //#region packages/typescript/src/runtime/json-schema.ts
4215
- /**
4690
+ /** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
4691
+ /**
4216
4692
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
4217
4693
  *
4218
4694
  * Translates the atscript type structure and validation metadata
@@ -4227,8 +4703,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4227
4703
  * ```
4228
4704
  *
4229
4705
  * @param type - The annotated type to convert.
4706
+ * @param opts - {@link TJsonSchemaOptions}.
4230
4707
  * @returns A JSON Schema object.
4231
- */ function buildJsonSchema(type) {
4708
+ */ function buildJsonSchema(type, opts) {
4709
+ const closed = opts?.closed === true;
4710
+ const annotations = opts?.annotations !== false;
4711
+ const enums = opts?.enums !== false;
4232
4712
  /**
4233
4713
  * `$defs` entries by type def (identity): named objects (always extracted) and types found
4234
4714
  * recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
@@ -4256,8 +4736,35 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4256
4736
  ...schema,
4257
4737
  type: [schema.type, "null"]
4258
4738
  };
4259
- if (Object.keys(schema).length === 1 && Array.isArray(schema.anyOf)) return { anyOf: [...schema.anyOf, { type: "null" }] };
4260
- return { anyOf: [schema, { type: "null" }] };
4739
+ const notes = {};
4740
+ let body = schema;
4741
+ for (const [, keyword] of ANNOTATION_KEYWORDS) if (body[keyword] !== void 0) {
4742
+ if (body === schema) body = { ...schema };
4743
+ notes[keyword] = body[keyword];
4744
+ delete body[keyword];
4745
+ }
4746
+ if (body !== schema && Object.keys(body).length === 1 && body.allOf?.length === 1) body = body.allOf[0];
4747
+ if (Object.keys(body).length === 1 && Array.isArray(body.anyOf)) return {
4748
+ anyOf: [...body.anyOf, { type: "null" }],
4749
+ ...notes
4750
+ };
4751
+ return {
4752
+ anyOf: [body, { type: "null" }],
4753
+ ...notes
4754
+ };
4755
+ };
4756
+ /**
4757
+ * A use of a `$defs` entry: `schema` (its `$ref`) with what the use adds to the entry (built
4758
+ * from `own`, see `ownDef`): its key counts, and its title / description when they differ
4759
+ * from the entry's — beside the reference, in an `allOf`.
4760
+ */ const useOf = (schema, def, own, keyCounts = false) => {
4761
+ const extra = {};
4762
+ if (annotations) applyAnnotationKeywords(extra, def.metadata, own?.metadata);
4763
+ if (keyCounts) applyKeyCounts(extra, def.metadata);
4764
+ return Object.keys(extra).length > 0 ? {
4765
+ allOf: [schema],
4766
+ ...extra
4767
+ } : schema;
4261
4768
  };
4262
4769
  /**
4263
4770
  * Non-primitive type defs being built: `true` once re-entered (recursive). A named object
@@ -4294,7 +4801,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4294
4801
  * A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
4295
4802
  * them instead, its recursion referring to the shared definition.
4296
4803
  */ function* refTo(typeDef, def, own) {
4297
- if (def === own || inlining.has(def) || sameConstraints(def, own)) return ref(typeDef);
4804
+ if (def === own || inlining.has(def) || sameConstraints(def, own)) return useOf(ref(typeDef), def, own);
4298
4805
  inlining.add(def);
4299
4806
  const schema = yield buildDef(def);
4300
4807
  inlining.delete(def);
@@ -4324,6 +4831,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4324
4831
  for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
4325
4832
  schema.patternProperties = patternProperties(built, Object.keys(properties));
4326
4833
  }
4834
+ if (closed) schema.additionalProperties = false;
4327
4835
  return schema;
4328
4836
  }
4329
4837
  /** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
@@ -4333,14 +4841,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4333
4841
  const atRoot = def === type && !rootEntered;
4334
4842
  rootEntered = true;
4335
4843
  if (def.id && typeDef.kind === "object" && !atRoot) {
4844
+ const own = annotations ? ownDef(def, type) ?? def : void 0;
4336
4845
  if (!defs.has(typeDef)) {
4337
4846
  reserve(typeDef, def.id, true);
4338
4847
  const outer = building;
4339
4848
  building = /* @__PURE__ */ new Map();
4340
- defs.get(typeDef).schema = yield buildObject(def);
4849
+ const entry = yield buildObject(def);
4850
+ if (own) applyAnnotationKeywords(entry, own.metadata);
4851
+ defs.get(typeDef).schema = entry;
4341
4852
  building = outer;
4342
4853
  }
4343
- return withKeyCounts(ref(typeDef), def.metadata);
4854
+ return useOf(ref(typeDef), def, own, true);
4344
4855
  }
4345
4856
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
4346
4857
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -4369,7 +4880,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4369
4880
  const own = ownOf(def);
4370
4881
  const same = def === own || sameConstraints(def, own);
4371
4882
  defs.get(typeDef).schema = same ? schema : yield buildDef(own);
4372
- return def === type || !same ? schema : ref(typeDef);
4883
+ return def === type || !same ? schema : useOf(ref(typeDef), def, own);
4373
4884
  }
4374
4885
  /** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
4375
4886
  const ownOf = (def) => {
@@ -4380,7 +4891,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4380
4891
  }
4381
4892
  return own;
4382
4893
  };
4383
- /** The schema of `def`'s own type (see {@link build}). */ function* buildDef(def) {
4894
+ /** The schema of `def`'s own type (see {@link build}), with its title / description. */ function* buildDef(def) {
4895
+ const schema = yield buildBody(def);
4896
+ if (annotations) applyAnnotationKeywords(schema, def.metadata);
4897
+ return schema;
4898
+ }
4899
+ /** The schema of `def`'s own type, without its title / description (see {@link buildDef}). */ function* buildBody(def) {
4384
4900
  const meta = def.metadata;
4385
4901
  const all = function* (items) {
4386
4902
  const out = [];
@@ -4435,7 +4951,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4435
4951
  };
4436
4952
  } else {
4437
4953
  if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
4438
- schema = { anyOf: built };
4954
+ schema = enums && enumOf(built, refSchemas) || { anyOf: built };
4439
4955
  }
4440
4956
  applyKeyCounts(schema, meta);
4441
4957
  return schema;
@@ -4688,13 +5204,41 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4688
5204
  const maxKeys = meta.get("expect.maxKeys");
4689
5205
  if (maxKeys !== void 0) schema.maxProperties = boundOf(maxKeys, "count");
4690
5206
  }
4691
- /** `schema` (a `$ref`) with the key counts of `meta`, if any (beside it, in an `allOf`). */ function withKeyCounts(schema, meta) {
4692
- const counts = {};
4693
- applyKeyCounts(counts, meta);
4694
- return Object.keys(counts).length > 0 ? {
4695
- allOf: [schema],
4696
- ...counts
4697
- } : schema;
5207
+ /** `@meta.label` → `title`, `@meta.description` → `description` (see `annotations`). */ function applyAnnotationKeywords(schema, meta, except) {
5208
+ if (metaEmpty(meta)) return;
5209
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) {
5210
+ const value = meta.get(key);
5211
+ if (value !== void 0 && value !== except?.get(key)) schema[keyword] = value;
5212
+ }
5213
+ }
5214
+ /**
5215
+ * The `{ type, enum }` schema of a union whose members are all literals (`const`, a nested
5216
+ * union of literals' `enum`, or `null`), at least one of them not `null`; `undefined` for any
5217
+ * other union (a member with other keywords — a title, a constraint — keeps the `anyOf`).
5218
+ */ function enumOf(members, refs) {
5219
+ const values = [];
5220
+ const types = [];
5221
+ let literal = false;
5222
+ for (const member of members) {
5223
+ if (refs.has(member)) return;
5224
+ const keys = Object.keys(member);
5225
+ let memberValues;
5226
+ if ("const" in member && keys.every((k) => k === "const" || k === "type")) {
5227
+ memberValues = [member.const];
5228
+ literal = true;
5229
+ } else if (Array.isArray(member.enum) && keys.every((k) => k === "enum" || k === "type")) {
5230
+ memberValues = member.enum;
5231
+ literal = true;
5232
+ } else if (member.type === "null" && keys.length === 1) memberValues = [null];
5233
+ else return;
5234
+ for (const value of memberValues) if (!values.includes(value)) values.push(value);
5235
+ for (const t of [member.type ?? []].flat()) if (!types.includes(t)) types.push(t);
5236
+ }
5237
+ if (!literal) return;
5238
+ const schema = {};
5239
+ if (types.length > 0) schema.type = types.length === 1 ? types[0] : types;
5240
+ schema.enum = values;
5241
+ return schema;
4698
5242
  }
4699
5243
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
4700
5244
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
@@ -4748,7 +5292,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4748
5292
  applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
4749
5293
  continue;
4750
5294
  }
4751
- if (member.const !== void 0) continue;
5295
+ if (member.const !== void 0 || member.enum !== void 0) continue;
4752
5296
  const type = member.type;
4753
5297
  const extra = { type };
4754
5298
  if (type === "array") {
@@ -4791,7 +5335,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4791
5335
  */ function fromJsonSchema(schema) {
4792
5336
  const defsSource = schema.$defs || schema.definitions || {};
4793
5337
  const resolved = /* @__PURE__ */ new Map();
4794
- const convert = (s) => {
5338
+ /** `title` → `@meta.label`, `description` → `@meta.description` (not on a shared `$ref`). */ const convert = (s) => {
5339
+ const type = convertNode(s);
5340
+ if (s && !s.$ref) {
5341
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) if (typeof s[keyword] === "string") annotate(type.metadata, key, s[keyword]);
5342
+ }
5343
+ return type;
5344
+ };
5345
+ const convertNode = (s) => {
4795
5346
  if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
4796
5347
  if (s.$ref) {
4797
5348
  const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
@@ -4837,7 +5388,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4837
5388
  const handle = defineAnnotatedType("union");
4838
5389
  for (const t of s.type) handle.item(convert({
4839
5390
  ...s,
4840
- type: t
5391
+ type: t,
5392
+ title: void 0,
5393
+ description: void 0
4841
5394
  }));
4842
5395
  return handle.$type;
4843
5396
  }
@@ -4935,14 +5488,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4935
5488
  * to it are renamed.
4936
5489
  *
4937
5490
  * @param types - Array of annotated types, each with an `id`.
5491
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
4938
5492
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
4939
- */ function mergeJsonSchemas(types) {
5493
+ */ function mergeJsonSchemas(types, opts) {
4940
5494
  const mergedDefs = {};
4941
5495
  const schemas = {};
4942
5496
  for (const type of types) {
4943
5497
  const name = type.id;
4944
5498
  if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
4945
- const { $defs: defs, ...schema } = buildJsonSchema(type);
5499
+ const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
4946
5500
  if (!defs) {
4947
5501
  schemas[name] = schema;
4948
5502
  continue;
@@ -5190,13 +5744,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5190
5744
  /** The lazy JSON schema of each type, with the metadata write count it was built at. */ const lazy = /* @__PURE__ */ new WeakMap();
5191
5745
  /**
5192
5746
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
5193
- * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
5194
- * (`static toJsonSchema()`).
5195
- */ function lazyJsonSchema(type) {
5747
+ * a type tree write (a block, a runtime edit of metadata or shape: see `typeWrites`). Called by
5748
+ * generated code (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same
5749
+ * for every call of a type).
5750
+ */ function lazyJsonSchema(type, opts) {
5196
5751
  const known = lazy.get(type);
5197
- const writes = metadataWriteCount();
5752
+ const writes = typeWriteCount();
5198
5753
  if (known?.writes === writes) return known.schema;
5199
- const schema = buildJsonSchema(type);
5754
+ const schema = buildJsonSchema(type, opts);
5200
5755
  lazy.set(type, {
5201
5756
  writes,
5202
5757
  schema
@@ -5208,14 +5763,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5208
5763
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
5209
5764
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
5210
5765
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
5211
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
5212
- */ function bundledSchemaOf(type, literal, modules = []) {
5766
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
5767
+ * `jsonSchemaOptions` of the build (the literal was built with them).
5768
+ */ function bundledSchemaOf(type, literal, modules = [], opts) {
5213
5769
  const applied = appliedBlockModules();
5214
5770
  const known = bundled.get(type);
5215
5771
  if (known?.size === applied.size) return known.schema;
5216
5772
  const accounted = new Set(modules);
5217
5773
  const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
5218
- const schema = same ? literal() : buildJsonSchema(type);
5774
+ const schema = same ? literal() : buildJsonSchema(type, opts);
5219
5775
  bundled.set(type, {
5220
5776
  size: applied.size,
5221
5777
  schema,
@@ -5358,7 +5914,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5358
5914
 
5359
5915
  //#endregion
5360
5916
  //#region packages/typescript/src/runtime/serialize.ts
5361
- function _define_property$2(obj, key, value) {
5917
+ function _define_property$3(obj, key, value) {
5362
5918
  if (key in obj) Object.defineProperty(obj, key, {
5363
5919
  value,
5364
5920
  enumerable: true,
@@ -5430,17 +5986,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5430
5986
  return id;
5431
5987
  }
5432
5988
  constructor() {
5433
- _define_property$2(this, "own", /* @__PURE__ */ new Map());
5989
+ _define_property$3(this, "own", /* @__PURE__ */ new Map());
5434
5990
  /**
5435
5991
  * The nodes without an id met more than once (see `indexPayload`): serialized once, with a
5436
5992
  * payload id, and referenced (`$ref`, `anon`) wherever else they are.
5437
- */ _define_property$2(this, "repeated", /* @__PURE__ */ new Set());
5438
- _define_property$2(this, "firstKeys", /* @__PURE__ */ new Map());
5439
- _define_property$2(this, "identities", /* @__PURE__ */ new WeakMap());
5440
- _define_property$2(this, "nextId", 0);
5441
- /** Payload ids by type def (see {@link keyOf}). */ _define_property$2(this, "keys", /* @__PURE__ */ new WeakMap());
5442
- /** The payload ids given so far. */ _define_property$2(this, "taken", /* @__PURE__ */ new Set());
5443
- /** The `cut` payload of defs (see `indexPayload`). */ _define_property$2(this, "cutKeys", /* @__PURE__ */ new WeakMap());
5993
+ */ _define_property$3(this, "repeated", /* @__PURE__ */ new Set());
5994
+ _define_property$3(this, "firstKeys", /* @__PURE__ */ new Map());
5995
+ _define_property$3(this, "identities", /* @__PURE__ */ new WeakMap());
5996
+ _define_property$3(this, "nextId", 0);
5997
+ /** Payload ids by type def (see {@link keyOf}). */ _define_property$3(this, "keys", /* @__PURE__ */ new WeakMap());
5998
+ /** The payload ids given so far. */ _define_property$3(this, "taken", /* @__PURE__ */ new Set());
5999
+ /** The `cut` payload of defs (see `indexPayload`). */ _define_property$3(this, "cutKeys", /* @__PURE__ */ new WeakMap());
5444
6000
  }
5445
6001
  };
5446
6002
  /**
@@ -5904,7 +6460,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5904
6460
  * their specs flag `userText`. Core's are known from the start ({@link CORE_USER_TEXT}); a plugin's
5905
6461
  * are registered by the generated modules that write them (`$ut`), or by the plugin itself
5906
6462
  * ({@link registerUserText}), so a translator finds them at runtime without the specs.
5907
- */ /** `true`: the value itself is the text; a list: those fields of the value object are. */ /**
6463
+ */ /**
6464
+ * `true`: the value itself is the text; `'expression'`: the value is the source of a function the
6465
+ * client evaluates, its string literals the texts; a list: those fields of the value object are
6466
+ * (a name ending in `()`: that field is an expression).
6467
+ */ /**
5908
6468
  * The user-facing text of `@atscript/core`'s annotations (its specs' `userText` arguments; a test
5909
6469
  * keeps them equal).
5910
6470
  */ const CORE_USER_TEXT = new Map([
@@ -5927,33 +6487,36 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5927
6487
  ]);
5928
6488
  const USER_TEXT = new Map(CORE_USER_TEXT);
5929
6489
  /**
5930
- * Registers metadata key `key` as holding user-facing text: `true` (default) — its value is the
5931
- * text; a list of field names — those fields of its value object are. Fields add up across calls.
6490
+ * Registers metadata key `key` as holding user-facing text (see {@link TUserTextFields}; `true` by
6491
+ * default). Fields add up across calls; a whole-value kind replaces a field list, and an
6492
+ * expression wins over text (`name()` over `name`), whatever the order of the calls.
5932
6493
  * For plugins that write such metadata at runtime; generated modules register what they write.
5933
6494
  */ function registerUserText(key, fields = true) {
5934
6495
  const known = USER_TEXT.get(key);
5935
- if (known === true || fields === true) {
5936
- USER_TEXT.set(key, true);
6496
+ if (known === "expression" || known === true && typeof fields === "object") return;
6497
+ if (typeof fields !== "object") {
6498
+ USER_TEXT.set(key, fields);
5937
6499
  return;
5938
6500
  }
5939
- const added = fields.filter((f) => !known?.includes(f));
5940
- if (added.length > 0 || !known) USER_TEXT.set(key, [...known ?? [], ...added]);
6501
+ const all = new Set([...typeof known === "object" ? known : [], ...fields]);
6502
+ USER_TEXT.set(key, [...all].filter((f) => !all.has(`${f}()`)));
5941
6503
  }
5942
6504
  /**
5943
6505
  * Registers user-text keys written by a generated module (see {@link registerUserText}): `key` —
5944
- * the value itself; `key:field` — that field of the value object.
6506
+ * the value itself; `key()` — the value is an expression; `key:field` — that field of the value
6507
+ * object; `key:field()` — that field is an expression.
5945
6508
  */ function $ut(...entries) {
5946
6509
  for (const entry of entries) {
5947
6510
  const at = entry.indexOf(":");
5948
- if (at === -1) registerUserText(entry);
5949
- else registerUserText(entry.slice(0, at), [entry.slice(at + 1)]);
6511
+ if (at !== -1) registerUserText(entry.slice(0, at), [entry.slice(at + 1)]);
6512
+ else if (entry.endsWith("()")) registerUserText(entry.slice(0, -2), "expression");
6513
+ else registerUserText(entry);
5950
6514
  }
5951
6515
  }
5952
6516
  /**
5953
- * Where metadata key `key` holds user-facing text: `true` — its value is the text (a string; for
5954
- * a `multiple` annotation, each item of the list); a list of field names — those fields of its
5955
- * value object (each item's, for a list); `undefined` — no user-facing text. Core keys are known
5956
- * from the start; a plugin's once a module writing them is loaded (or the plugin registered them).
6517
+ * Where metadata key `key` holds user-facing text (see {@link TUserTextFields}; for a `multiple`
6518
+ * annotation, each item of its list), `undefined` when it holds none. Core keys are known from the
6519
+ * start; a plugin's once a module writing them is loaded (or the plugin registered them).
5957
6520
  */ function userTextOf(key) {
5958
6521
  return USER_TEXT.get(key);
5959
6522
  }
@@ -5961,6 +6524,235 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5961
6524
  return USER_TEXT;
5962
6525
  }
5963
6526
 
6527
+ //#endregion
6528
+ //#region packages/typescript/src/runtime/translate-served.ts
6529
+ /**
6530
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
6531
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
6532
+ * collected for the client.
6533
+ */ function _define_property$2(obj, key, value) {
6534
+ if (key in obj) Object.defineProperty(obj, key, {
6535
+ value,
6536
+ enumerable: true,
6537
+ configurable: true,
6538
+ writable: true
6539
+ });
6540
+ else obj[key] = value;
6541
+ return obj;
6542
+ }
6543
+ /**
6544
+ * Translates the user-facing text of serialized annotated types (the output of
6545
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
6546
+ * found at any depth is read with {@link userTextOf}:
6547
+ *
6548
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
6549
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
6550
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
6551
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
6552
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
6553
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
6554
+ * translates the expressions' results by exact match.
6555
+ *
6556
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
6557
+ * result shares every part with no translated text, and is `json` itself when nothing was
6558
+ * translated.
6559
+ *
6560
+ * @example
6561
+ * ```ts
6562
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
6563
+ * i18n.exists(text) ? i18n.t(text) : undefined
6564
+ * )
6565
+ * ```
6566
+ */ function translateServed(json, t) {
6567
+ const texts = {};
6568
+ return {
6569
+ value: walk(json, void 0, {
6570
+ t,
6571
+ texts
6572
+ }),
6573
+ texts
6574
+ };
6575
+ }
6576
+ /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
6577
+ if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
6578
+ if (typeof value === "string") {
6579
+ if (mode === "expression") collectLiterals(value, ctx);
6580
+ else if (mode === true && formatCodeOf(value) === void 0) return translate(value, ctx) ?? value;
6581
+ return value;
6582
+ }
6583
+ if (typeof value !== "object" || value === null) return value;
6584
+ return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
6585
+ }
6586
+ /**
6587
+ * The mode of the value at `key` of an object of `mode`: a metadata key's user text, a field of a
6588
+ * value object's, else `metadata` objects only (a non-string text value — a `ref` target — has
6589
+ * metadata).
6590
+ */ function modeOf(key, mode) {
6591
+ if (typeof mode === "object") return mode.includes(`${key}()`) ? "expression" : mode.includes(key) || void 0;
6592
+ return mode === "metadata" && userTextOf(key) || (key === "metadata" ? "metadata" : void 0);
6593
+ }
6594
+ /** `t(text)` when it is a string (a plain-object dictionary also has `constructor`, …). */ function translate(text, ctx) {
6595
+ const out = ctx.t(text);
6596
+ return typeof out === "string" ? out : void 0;
6597
+ }
6598
+ /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
6599
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
6600
+ const translated = translate(literal, ctx);
6601
+ if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
6602
+ }
6603
+ }
6604
+ /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
6605
+ "n": "\n",
6606
+ "t": " ",
6607
+ "r": "\r",
6608
+ "b": "\b",
6609
+ "f": "\f",
6610
+ "v": "\v",
6611
+ "0": "\0",
6612
+ "\n": "",
6613
+ "\r": "",
6614
+ "\r\n": ""
6615
+ };
6616
+ /** An escape of a literal's raw text: `\u{…}`, `\u….`, `\x..`, or a single character. */ const ESCAPE = /\\(u\{[\dA-Fa-f]+\}|u[\dA-Fa-f]{4}|x[\dA-Fa-f]{2}|\r\n|[\s\S])/gu;
6617
+ /** The string a literal's raw text (between its quotes) evaluates to. */ function decode(raw) {
6618
+ return raw.includes("\\") ? raw.replace(ESCAPE, (_, c) => {
6619
+ if (c.length < 3) return Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : c;
6620
+ const code = Number.parseInt(c.replace(/[ux{}]/g, ""), 16);
6621
+ return code > 1114111 ? "" : String.fromCodePoint(code);
6622
+ }) : raw;
6623
+ }
6624
+ /** A character of an identifier or a number. */ const IDENT = RegExp("[\\p{ID_Continue}$]", "u");
6625
+ /** A run of {@link IDENT} characters at `lastIndex`. */ const IDENT_RUN = RegExp("[\\p{ID_Continue}$]+", "uy");
6626
+ /** Keywords whose `(…)` a statement follows: a `/` after the `)` starts a regular expression. */ const CONTROL = new Set([
6627
+ "if",
6628
+ "while",
6629
+ "for",
6630
+ "with"
6631
+ ]);
6632
+ /** Keywords after which `/` starts a regular expression rather than a division. */ const REGEX_AFTER_WORD = new Set([
6633
+ "return",
6634
+ "typeof",
6635
+ "instanceof",
6636
+ "in",
6637
+ "of",
6638
+ "new",
6639
+ "delete",
6640
+ "void",
6641
+ "throw",
6642
+ "case",
6643
+ "do",
6644
+ "else",
6645
+ "yield",
6646
+ "await"
6647
+ ]);
6648
+ let LiteralScanner = class LiteralScanner {
6649
+ /** Scans code up to the end, or to the `}` closing a template's `${`. */ code() {
6650
+ const src = this.src;
6651
+ while (this.i < src.length) {
6652
+ const c = src[this.i];
6653
+ if (c === "/" && src[this.i + 1] === "/") {
6654
+ const end = src.indexOf("\n", this.i);
6655
+ this.i = end === -1 ? src.length : end;
6656
+ } else if (c === "/" && src[this.i + 1] === "*") {
6657
+ const end = src.indexOf("*/", this.i + 2);
6658
+ this.i = end === -1 ? src.length : end + 2;
6659
+ } else if (c === "'" || c === "\"" || c === "`") {
6660
+ const text = this.literal(c);
6661
+ if (text !== void 0 && text.trim() !== "") this.out.add(text);
6662
+ this.regexOk = false;
6663
+ } else if (c === "/" && this.regexOk) {
6664
+ this.regex();
6665
+ this.regexOk = false;
6666
+ } else if (IDENT.test(c)) this.word();
6667
+ else if ((c === "+" || c === "-") && src[this.i + 1] === c) {
6668
+ this.i += 2;
6669
+ this.regexOk = false;
6670
+ } else {
6671
+ this.i++;
6672
+ if (/\s/.test(c)) continue;
6673
+ if (c === "(" || c === "{") this.open.push(c === "(" ? "p" : c);
6674
+ else if (c === ")" || c === "}") {
6675
+ const top = this.open.pop();
6676
+ if (top === "$") return;
6677
+ this.regexOk = top === "c";
6678
+ continue;
6679
+ }
6680
+ this.regexOk = c !== "]";
6681
+ }
6682
+ }
6683
+ }
6684
+ /** An identifier, keyword or number at `i`; `i` past it (and past a control keyword's `(`). */ word() {
6685
+ const src = this.src;
6686
+ IDENT_RUN.lastIndex = this.i;
6687
+ IDENT_RUN.test(src);
6688
+ const word = src.slice(this.i, IDENT_RUN.lastIndex);
6689
+ this.i = IDENT_RUN.lastIndex;
6690
+ this.regexOk = REGEX_AFTER_WORD.has(word);
6691
+ if (CONTROL.has(word)) {
6692
+ while (/\s/.test(src[this.i] ?? "")) this.i++;
6693
+ if (src[this.i] === "(") {
6694
+ this.i++;
6695
+ this.open.push("c");
6696
+ this.regexOk = true;
6697
+ }
6698
+ }
6699
+ }
6700
+ /**
6701
+ * A `'…'` / `"…"` / `` `…` `` literal at `i`, decoded (`undefined`: a template with `${…}`, whose
6702
+ * code is scanned); `i` past it.
6703
+ */ literal(quote) {
6704
+ const src = this.src;
6705
+ const start = ++this.i;
6706
+ let plain = true;
6707
+ while (this.i < src.length && src[this.i] !== quote) if (src[this.i] === "\\") this.i += src.startsWith("\r\n", this.i + 1) ? 3 : 2;
6708
+ else if (quote === "`" && src.startsWith("${", this.i)) {
6709
+ plain = false;
6710
+ this.i += 2;
6711
+ this.open.push("$");
6712
+ this.code();
6713
+ } else this.i++;
6714
+ const end = this.i++;
6715
+ return plain ? decode(src.slice(start, end)) : void 0;
6716
+ }
6717
+ /** A regular expression literal starting at `i`; `i` past its flags. */ regex() {
6718
+ const src = this.src;
6719
+ let inClass = false;
6720
+ this.i++;
6721
+ while (this.i < src.length && src[this.i] !== "\n") {
6722
+ const c = src[this.i++];
6723
+ if (c === "\\") this.i++;
6724
+ else if (c === "[") inClass = true;
6725
+ else if (c === "]") inClass = false;
6726
+ else if (c === "/" && !inClass) break;
6727
+ }
6728
+ while (this.i < src.length && /[a-z]/i.test(src[this.i])) this.i++;
6729
+ }
6730
+ constructor(src, out) {
6731
+ _define_property$2(this, "src", void 0);
6732
+ _define_property$2(this, "out", void 0);
6733
+ _define_property$2(this, "i", void 0);
6734
+ /** A `/` here starts a regular expression (no operand just ended), not a division. */ _define_property$2(this, "regexOk", void 0);
6735
+ /**
6736
+ * The open brackets: `c` — the `(` of an `if` / `while` / `for` / `with` (a `/` after its `)` is
6737
+ * a regex); `p` — another `(`; `{`; `$` — a template's `${`.
6738
+ */ _define_property$2(this, "open", void 0);
6739
+ this.src = src;
6740
+ this.out = out;
6741
+ this.i = 0;
6742
+ this.regexOk = true;
6743
+ this.open = [];
6744
+ }
6745
+ };
6746
+ /**
6747
+ * The string literals of JavaScript `source`, as the strings they evaluate to: `'…'`, `"…"` and
6748
+ * `` `…` `` templates without `${…}` (the literals inside a `${…}` count). Comments and regular
6749
+ * expression literals are skipped; empty and blank literals are left out.
6750
+ */ function stringLiterals(source) {
6751
+ const out = /* @__PURE__ */ new Set();
6752
+ new LiteralScanner(source, out).code();
6753
+ return [...out];
6754
+ }
6755
+
5964
6756
  //#endregion
5965
6757
  //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
5966
6758
  /**
@@ -6927,11 +7719,14 @@ exports.localizeErrors = localizeErrors;
6927
7719
  exports.mergeJsonSchemas = mergeJsonSchemas;
6928
7720
  exports.messagesTranslator = messagesTranslator;
6929
7721
  exports.metaEmpty = metaEmpty;
7722
+ exports.normalizeForType = normalizeForType;
6930
7723
  exports.pendingStatements = pendingStatements;
6931
7724
  exports.registerCompiledCheck = registerCompiledCheck;
6932
7725
  exports.registerUserText = registerUserText;
6933
7726
  exports.serializeAnnotatedType = serializeAnnotatedType;
6934
7727
  exports.throwFeatureDisabled = throwFeatureDisabled;
7728
+ exports.translateServed = translateServed;
7729
+ exports.unionDiscriminator = unionDiscriminator;
6935
7730
  exports.userTextKeys = userTextKeys;
6936
7731
  exports.userTextOf = userTextOf;
6937
7732
  exports.watchLayer = watchLayer;