@atscript/typescript 0.2.3 → 0.2.5

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.
@@ -26,6 +26,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
26
26
  "expect.maxLength",
27
27
  "expect.array.uniqueItems"
28
28
  ];
29
+ /** Annotations of an object node, in check order (before its props). */ const OBJECT_KEYS = ["expect.minKeys", "expect.maxKeys"];
29
30
  /**
30
31
  * Every annotation key the validator pre-check reads. The order is the bit order of
31
32
  * compiled-check layouts: changing it changes the layout format.
@@ -39,7 +40,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
39
40
  "expect.max",
40
41
  "expect.exclusiveMin",
41
42
  "expect.exclusiveMax",
42
- "expect.array.uniqueItems"
43
+ "expect.array.uniqueItems",
44
+ "expect.minKeys",
45
+ "expect.maxKeys"
43
46
  ];
44
47
  /**
45
48
  * The number a length / bound annotation compares with: the annotation is either the number
@@ -224,7 +227,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
224
227
  * sees); otherwise the reads are live. A raw write the counter does not see (a node's map swapped,
225
228
  * `node.metadata = X`, or edited in place) must be followed by `invalidateCompiledValidators()`,
226
229
  * as compiled checks require (PERF-2).
227
- */ function _define_property$5(obj, key, value) {
230
+ */ function _define_property$6(obj, key, value) {
228
231
  if (key in obj) Object.defineProperty(obj, key, {
229
232
  value,
230
233
  enumerable: true,
@@ -268,6 +271,32 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
268
271
  */ function moveIntrinsic(from, to) {
269
272
  const s = INTRINSIC.get(from);
270
273
  if (s) INTRINSIC.set(to, s);
274
+ moveHidden(from, to);
275
+ }
276
+ /**
277
+ * Keys a map hides from its bases (`@annotate.reset`): read as if no base had them. Kept per map
278
+ * (as `INTRINSIC`), moved with it when a node's map is replaced; `hiding`: some map hides a key
279
+ * (until then the reads skip the lookup).
280
+ */ const HIDDEN = /* @__PURE__ */ new WeakMap();
281
+ let hiding = false;
282
+ /** Whether map `m` hides `key` from its bases (see {@link HIDDEN}). */ function hides(m, key) {
283
+ return hiding && HIDDEN.get(m)?.has(key) === true;
284
+ }
285
+ /**
286
+ * Hides `key` of map `m`'s bases (`@annotate.reset`): `m` reads as if no base had it — its own
287
+ * value, if any, is what it has. A metadata write (layered views and compiled checks re-read).
288
+ * `metadata.delete(key)` on a layered map ends it: the bases show through again.
289
+ */ function hideKey(m, key) {
290
+ let s = HIDDEN.get(m);
291
+ if (!s) HIDDEN.set(m, s = /* @__PURE__ */ new Set());
292
+ s.add(key);
293
+ hiding = true;
294
+ touched(m);
295
+ metadataReplaced();
296
+ }
297
+ /** The keys map `m` hides from its bases (see {@link hideKey}), for a map replacing it. */ function moveHidden(from, to) {
298
+ const s = HIDDEN.get(from);
299
+ if (s) HIDDEN.set(to, s);
271
300
  }
272
301
  const MISS = Symbol("miss");
273
302
  /** The view of a layered map without effective entries (never written: views stay internal). */ const NO_ENTRIES = new AnnotationMap();
@@ -302,6 +331,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
302
331
  const v = mapGet.call(this, key);
303
332
  if (v !== void 0 || mapHas.call(this, key)) return v;
304
333
  }
334
+ if (hiding && hides(this, key)) return MISS;
305
335
  if (nr && this.r) {
306
336
  for (const n of this.b) {
307
337
  const x = intrinsicLookup(n.metadata, key);
@@ -332,10 +362,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
332
362
  }
333
363
  has(key) {
334
364
  const view = this.view();
335
- return view === void 0 ? this.lookup(key, notReferred(key)) !== MISS : mapHas.call(view, key);
365
+ return view === void 0 ? this.liveHas(key) : mapHas.call(view, key);
366
+ }
367
+ /** `has` read through the layers (see the file comment). */ liveHas(key) {
368
+ return this.lookup(key, notReferred(key)) !== MISS;
336
369
  }
337
370
  /** An append key: the bases' values (lowest priority first), then the own ones. */ append(key) {
338
371
  const own = mapGet.call(this, key);
372
+ if (hiding && hides(this, key)) return own;
339
373
  if (this.r && notReferred(key)) {
340
374
  const parts = [];
341
375
  const acc = {
@@ -372,8 +406,20 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
372
406
  }
373
407
  liveKeys() {
374
408
  const out = /* @__PURE__ */ new Set();
375
- keysOf(this, false, out, /* @__PURE__ */ new Map());
376
- return [...out];
409
+ return keysOf(this, false, out, /* @__PURE__ */ new Map()) ? [...out].filter((k) => this.liveHas(k)) : [...out];
410
+ }
411
+ /** Deletes the own value of `key`; a key hidden from the bases (`hideKey`) shows them again. */ delete(key) {
412
+ const deleted = super.delete(key);
413
+ if ((hiding ? HIDDEN.get(this) : void 0)?.delete(key)) {
414
+ touched(this);
415
+ metadataReplaced();
416
+ return true;
417
+ }
418
+ return deleted;
419
+ }
420
+ /** Deletes the own values; the keys hidden from the bases (`hideKey`) show them again. */ clear() {
421
+ super.clear();
422
+ HIDDEN.delete(this);
377
423
  }
378
424
  keys() {
379
425
  return this.effectiveKeys()[Symbol.iterator]();
@@ -391,7 +437,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
391
437
  for (const k of this.effectiveKeys()) cb.call(thisArg, this.get(k), k, this);
392
438
  }
393
439
  constructor(bases, reference = false, own) {
394
- 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);
395
441
  this.b = bases;
396
442
  this.r = reference;
397
443
  this.f = void 0;
@@ -424,7 +470,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
424
470
  if (m instanceof LayerMap ? mapHas.call(m, key) : m.has(key)) return m instanceof LayerMap ? mapGet.call(m, key) : m.get(key);
425
471
  }
426
472
  const b = m.b;
427
- if (b !== void 0) for (const n of b) {
473
+ if (b !== void 0 && !hides(m, key)) for (const n of b) {
428
474
  const x = intrinsicLookup(n.metadata, key);
429
475
  if (x !== MISS) return x;
430
476
  }
@@ -449,7 +495,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
449
495
  const was = acc.seen.get(m);
450
496
  if (!visit(m, filtered, acc.seen)) return;
451
497
  const layer = m instanceof LayerMap ? m : void 0;
452
- if (layer) {
498
+ if (layer && !hides(layer, key)) {
453
499
  const below = filtered || layer.r && notReferred(key);
454
500
  for (let i = layer.b.length - 1; i >= 0; i--) collect(layer.b[i].metadata, key, acc, below);
455
501
  }
@@ -458,14 +504,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
458
504
  }
459
505
  /**
460
506
  * The keys of `m` (own first, then its bases'), each map once (see {@link visit}). `filtered`:
461
- * reached through a reference layer.
507
+ * reached through a reference layer. Returns whether a map visited hides keys from its bases.
462
508
  */ function keysOf(m, filtered, out, seen) {
463
- if (!visit(m, filtered, seen)) return;
509
+ if (!visit(m, filtered, seen)) return false;
510
+ let hid = hiding && (HIDDEN.get(m)?.size ?? 0) > 0;
464
511
  const layer = m instanceof LayerMap ? m : void 0;
465
512
  const own = layer ? Map.prototype.keys.call(m) : m.keys();
466
513
  const intrinsic = INTRINSIC.get(m);
467
514
  for (const k of own) if (!filtered || !notReferred(k) || intrinsic?.has(k)) out.add(k);
468
- if (layer) for (const n of layer.b) keysOf(n.metadata, filtered || layer.r, out, seen);
515
+ if (layer) for (const n of layer.b) hid = keysOf(n.metadata, filtered || layer.r, out, seen) || hid;
516
+ return hid;
469
517
  }
470
518
  /**
471
519
  * `m` has no entry (own or through its bases): the validators' `metadata.size === 0` fast path,
@@ -799,10 +847,25 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
799
847
  * A block write of an append key: the own list is the elements written before any block (by
800
848
  * the builder, or a raw write since), then every block's part by rank.
801
849
  */ function appendKey(m, key, values, rank) {
850
+ const r = appendRecord(m, key);
851
+ const { parts } = r;
852
+ let at = 0;
853
+ while (at < parts.length && compare(parts[at].rank, rank) < 0) at++;
854
+ if (at < parts.length && compare(parts[at].rank, rank) === 0) parts[at].values = values;
855
+ else parts.splice(at, 0, {
856
+ rank,
857
+ values
858
+ });
859
+ writeAppend(m, key, r);
860
+ }
861
+ /**
862
+ * The block record of append key `key` of `m`: a new one when a raw write since changed the own
863
+ * list (the elements written before any block: the builder's, or that raw write).
864
+ */ function appendRecord(m, key) {
802
865
  const recs = recordsOf(m);
803
866
  let r = recs.get(key);
804
867
  const own = ownValue(m, key);
805
- if (!r || own !== r.value || r.value.length !== r.length) {
868
+ if (!r || own !== r.value || r.value !== void 0 && r.value.length !== r.length) {
806
869
  const before = own === void 0 ? [] : Array.isArray(own) ? [...own] : [own];
807
870
  r = {
808
871
  before,
@@ -810,28 +873,59 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
810
873
  value: before,
811
874
  length: 0
812
875
  };
876
+ recs.set(key, r);
877
+ }
878
+ return r;
879
+ }
880
+ /** Writes append key `key`'s own list from its record: the elements, then the parts by rank. */ function writeAppend(m, key, r) {
881
+ const reset = r.reset;
882
+ const value = reset ? [] : [...r.before];
883
+ for (const p of r.parts) if (!reset || compare(p.rank, reset) >= 0) value.push(...p.values);
884
+ if (value.length > 0) {
885
+ m.set(key, value);
886
+ r.value = value;
887
+ } else {
888
+ m.delete(key);
889
+ r.value = void 0;
813
890
  }
814
- const { parts } = r;
815
- let at = 0;
816
- while (at < parts.length && compare(parts[at].rank, rank) < 0) at++;
817
- if (at < parts.length && compare(parts[at].rank, rank) === 0) parts[at].values = values;
818
- else parts.splice(at, 0, {
819
- rank,
820
- values
821
- });
822
- const value = [...r.before];
823
- for (const p of parts) value.push(...p.values);
824
- m.set(key, value);
825
- r.value = value;
826
891
  r.length = value.length;
827
- recs.set(key, r);
892
+ if (reset) hideKey(m, key);
893
+ }
894
+ /**
895
+ * `@annotate.reset 'key'` by a block of rank `rank` at the node of map `m`: the node reads as if
896
+ * the key had no value below that block — none from its bases (the types it references, the
897
+ * target of an `as` copy: hidden, see `hideKey`), none written on the node itself (its
898
+ * declaration, lower-ranked blocks). A block ranked at or above it (the resetting block's own
899
+ * values included) writes as usual; one ranked below is ignored, whatever the load order.
900
+ */ function resetKey(m, key, rank) {
901
+ if (isAppendKey(key)) {
902
+ const r = appendRecord(m, key);
903
+ if (!r.reset || compare(r.reset, rank) < 0) r.reset = rank;
904
+ writeAppend(m, key, r);
905
+ return;
906
+ }
907
+ const recs = recordsOf(m);
908
+ const r = recs.get(key);
909
+ if (!(r && ownValue(m, key) === r.value && compare(r.rank, rank) > 0)) {
910
+ m.delete(key);
911
+ recs.set(key, {
912
+ rank,
913
+ value: void 0
914
+ });
915
+ }
916
+ hideKey(m, key);
828
917
  }
918
+ /** The block annotation resetting the annotation it names at its node (`@annotate.reset`). */ const RESET = "annotate.reset";
829
919
  function writeEntry(m, anns, rank) {
920
+ for (const [key, value] of anns) if (key === RESET) resetKey(m, value, rank);
830
921
  const values = /* @__PURE__ */ new Map();
831
- for (const [key, value, list] of anns) if (list) {
832
- const xs = values.get(key);
833
- values.set(key, xs ? [...xs, value] : [value]);
834
- } else values.set(key, value);
922
+ for (const [key, value, list] of anns) {
923
+ if (key === RESET) continue;
924
+ if (list) {
925
+ const xs = values.get(key);
926
+ values.set(key, xs ? [...xs, value] : [value]);
927
+ } else values.set(key, value);
928
+ }
835
929
  for (const [key, value] of values) if (isAppendKey(key)) appendKey(m, key, Array.isArray(value) ? value : [value], rank);
836
930
  else writeKey(m, key, value, rank);
837
931
  }
@@ -1338,6 +1432,51 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1338
1432
  };
1339
1433
  }
1340
1434
 
1435
+ //#endregion
1436
+ //#region packages/typescript/src/runtime/discriminator.ts
1437
+ /**
1438
+ * Detects a discriminator property across union items.
1439
+ *
1440
+ * Scans all items for object-typed members that share a common property
1441
+ * with distinct const/literal values. If exactly one such property exists,
1442
+ * it is returned as the discriminator. Returns `null` when no qualifying
1443
+ * property exists, or when more than one does (ambiguous).
1444
+ */ function detectDiscriminator(items) {
1445
+ if (items.length < 2) return null;
1446
+ for (const item of items) if (item.type.kind !== "object") return null;
1447
+ const firstObj = items[0].type;
1448
+ const candidates = [];
1449
+ for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
1450
+ let result = null;
1451
+ for (const candidate of candidates) {
1452
+ const values = /* @__PURE__ */ new Set();
1453
+ const indexMapping = Object.create(null);
1454
+ let valid = true;
1455
+ for (let i = 0; i < items.length; i++) {
1456
+ const prop = items[i].type.props.get(candidate);
1457
+ if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
1458
+ valid = false;
1459
+ break;
1460
+ }
1461
+ const val = prop.type.value;
1462
+ if (values.has(val)) {
1463
+ valid = false;
1464
+ break;
1465
+ }
1466
+ values.add(val);
1467
+ indexMapping[String(val)] = i;
1468
+ }
1469
+ if (valid) {
1470
+ if (result) return null;
1471
+ result = {
1472
+ propertyName: candidate,
1473
+ indexMapping
1474
+ };
1475
+ }
1476
+ }
1477
+ return result;
1478
+ }
1479
+
1341
1480
  //#endregion
1342
1481
  //#region packages/typescript/src/runtime/compiled-check/layout.ts
1343
1482
  /**
@@ -1418,11 +1557,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1418
1557
  const B_EX_MIN = bit("expect.exclusiveMin");
1419
1558
  const B_EX_MAX = bit("expect.exclusiveMax");
1420
1559
  const B_UNIQUE = bit("expect.array.uniqueItems");
1560
+ const B_MIN_KEYS = bit("expect.minKeys");
1561
+ const B_MAX_KEYS = bit("expect.maxKeys");
1421
1562
  /** Annotations the pre-check reads per kind of value (see validator-keys.ts). */ const STRING_BITS = bitsOf(STRING_KEYS);
1422
1563
  const NUMBER_BITS = bitsOf(NUMBER_KEYS);
1423
1564
  const ARRAY_BITS = bitsOf(ARRAY_KEYS);
1565
+ const OBJECT_BITS = bitsOf(OBJECT_KEYS);
1424
1566
  const BOOLEAN_BITS = bitsOf(BOOLEAN_KEYS);
1425
- /** Keys whose value the compiled code reads (one K slot each). */ const VALUE_BITS = B_MIN_LENGTH | B_MAX_LENGTH | B_MIN | B_MAX | B_EX_MIN | B_EX_MAX;
1567
+ /** Keys whose value the compiled code reads (one K slot each). */ const VALUE_BITS = B_MIN_LENGTH | B_MAX_LENGTH | B_MIN | B_MAX | B_EX_MIN | B_EX_MAX | B_MIN_KEYS | B_MAX_KEYS;
1426
1568
  const FLAG_BITS = B_REQUIRED | B_INT | B_UNIQUE;
1427
1569
  const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
1428
1570
  /** The field holding the bound of each value key's object form. */ const BOUND_FIELDS = {
@@ -1431,7 +1573,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1431
1573
  [B_MIN]: "minValue",
1432
1574
  [B_MAX]: "maxValue",
1433
1575
  [B_EX_MIN]: "exclusiveMinValue",
1434
- [B_EX_MAX]: "exclusiveMaxValue"
1576
+ [B_EX_MAX]: "exclusiveMaxValue",
1577
+ [B_MIN_KEYS]: "count",
1578
+ [B_MAX_KEYS]: "count"
1435
1579
  };
1436
1580
  /**
1437
1581
  * Validator annotations the pre-check reads for a node of this type def (the rest of the
@@ -1447,6 +1591,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1447
1591
  default: return 0;
1448
1592
  }
1449
1593
  case "array": return ARRAY_BITS;
1594
+ case "object": return OBJECT_BITS;
1450
1595
  case "union": return ALL_BITS;
1451
1596
  default: return 0;
1452
1597
  }
@@ -1491,7 +1636,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1491
1636
  min: next(B_MIN),
1492
1637
  max: next(B_MAX),
1493
1638
  exMin: next(B_EX_MIN),
1494
- exMax: next(B_EX_MAX)
1639
+ exMax: next(B_EX_MAX),
1640
+ minKeys: next(B_MIN_KEYS),
1641
+ maxKeys: next(B_MAX_KEYS)
1495
1642
  };
1496
1643
  }
1497
1644
  /** The child sites of a def. */ function childSites(def) {
@@ -1757,7 +1904,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1757
1904
 
1758
1905
  //#endregion
1759
1906
  //#region packages/typescript/src/runtime/validator-fast-check.ts
1760
- function _define_property$4(obj, key, value) {
1907
+ function _define_property$5(obj, key, value) {
1761
1908
  if (key in obj) Object.defineProperty(obj, key, {
1762
1909
  value,
1763
1910
  enumerable: true,
@@ -1982,7 +2129,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1982
2129
  for (const item of def.type.items) {
1983
2130
  const failures = COMPILED_ENV.n;
1984
2131
  const result = fastCheck(item, value, branchFlags, opts);
1985
- if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
2132
+ if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value, opts);
1986
2133
  if (COMPILED_ENV.n !== failures) unionWaste();
1987
2134
  if (nested) COMPILED_ENV.n++;
1988
2135
  if (pendingStrips.length !== kept) pendingStrips.length = kept;
@@ -2001,7 +2148,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2001
2148
  for (const child of plan.children) {
2002
2149
  const failures = COMPILED_ENV.n;
2003
2150
  const result = checkPlan(child, value, branchFlags, opts);
2004
- if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
2151
+ if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value, opts);
2005
2152
  if (COMPILED_ENV.n !== failures) unionWaste();
2006
2153
  if (nested) COMPILED_ENV.n++;
2007
2154
  if (pendingStrips.length !== kept) pendingStrips.length = kept;
@@ -2014,7 +2161,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2014
2161
  for (const item of def.type.items) {
2015
2162
  const failures = COMPILED_ENV.n;
2016
2163
  const result = fastCheck(item, value, branchFlags, opts);
2017
- if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
2164
+ if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value, opts);
2018
2165
  if (COMPILED_ENV.n !== failures) unionWaste();
2019
2166
  if (nested) COMPILED_ENV.n++;
2020
2167
  if (pendingStrips.length !== kept) pendingStrips.length = kept;
@@ -2027,7 +2174,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2027
2174
  for (const child of plan.children) {
2028
2175
  const failures = COMPILED_ENV.n;
2029
2176
  const result = checkPlan(child, value, branchFlags, opts);
2030
- if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
2177
+ if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value, opts);
2031
2178
  if (COMPILED_ENV.n !== failures) unionWaste();
2032
2179
  if (nested) COMPILED_ENV.n++;
2033
2180
  if (pendingStrips.length !== kept) pendingStrips.length = kept;
@@ -2073,7 +2220,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2073
2220
  case "string": return typeof value === "string" ? fastCheckString(def.metadata, value) : FAIL;
2074
2221
  case "number": return typeof value === "number" && Number.isFinite(value) ? fastCheckNumber(def.metadata, value) : FAIL;
2075
2222
  case "boolean": return typeof value === "boolean" ? fastCheckBoolean(def.metadata, value) : FAIL;
2076
- case "any": return PASS;
2223
+ case "any": return value === void 0 ? FAIL : PASS;
2077
2224
  case "never": return FAIL;
2078
2225
  case "undefined": return value === void 0 ? PASS : FAIL;
2079
2226
  case "null": return value === null ? PASS : FAIL;
@@ -2081,20 +2228,22 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2081
2228
  default: return BAIL;
2082
2229
  }
2083
2230
  }
2084
- /** Result of a union whose branch `item` did not fail (`PASS` or `BAIL`). */ function unionMatchResult(result, item, metadata, value) {
2085
- return result === PASS && item.type.value === void 0 ? fastCheckUnionConstraints(metadata, value) : result;
2231
+ /** Result of a union whose branch `item` did not fail (`PASS` or `BAIL`). */ function unionMatchResult(result, item, metadata, value, opts) {
2232
+ return result === PASS && item.type.value === void 0 ? fastCheckUnionConstraints(metadata, value, item, opts) : result;
2086
2233
  }
2087
2234
  /**
2088
2235
  * Mirrors Validator.validateUnionConstraints: union-level constraints on the matched value
2089
2236
  * (`null` / objects pass; the caller skips literal branches).
2090
- */ function fastCheckUnionConstraints(meta, value) {
2237
+ */ function fastCheckUnionConstraints(meta, value, branch, opts) {
2091
2238
  const metadata = filledMeta(meta);
2092
2239
  if (metadata === void 0) return PASS;
2093
2240
  switch (typeof value) {
2094
2241
  case "string": return fastCheckString(metadata, value);
2095
2242
  case "number": return fastCheckNumber(metadata, value);
2096
2243
  case "boolean": return fastCheckBoolean(metadata, value);
2097
- case "object": return Array.isArray(value) ? fastCheckArrayConstraints(metadata, value) : PASS;
2244
+ case "object":
2245
+ if (Array.isArray(value)) return fastCheckArrayConstraints(metadata, value);
2246
+ return value === null ? PASS : objectKeyCounts(metadata, value, branch, opts);
2098
2247
  default: return PASS;
2099
2248
  }
2100
2249
  }
@@ -2136,6 +2285,34 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2136
2285
  /** `@expect.minLength` / `@expect.maxLength` (strings and arrays). */ function lengthFails(length, minLength, maxLength) {
2137
2286
  return minLength !== void 0 && length < (typeof minLength === "number" ? minLength : minLength.length) || maxLength !== void 0 && length > (typeof maxLength === "number" ? maxLength : maxLength.length);
2138
2287
  }
2288
+ /** `@expect.minKeys` / `@expect.maxKeys` of an object keeping `count` keys. */ function countFails(count, minKeys, maxKeys) {
2289
+ return minKeys !== void 0 && count < (typeof minKeys === "number" ? minKeys : minKeys.count) || maxKeys !== void 0 && count > (typeof maxKeys === "number" ? maxKeys : maxKeys.count);
2290
+ }
2291
+ /**
2292
+ * The keys of object `value` the walk's result keeps (`Validator.keptKeyCount`): with
2293
+ * `unknownProps: 'strip'`, the keys `props` declares (not phantom); else every own key (with
2294
+ * 'error' an object with an unknown key fails anyway, whatever its count).
2295
+ */ function keptKeys(props, value, opts) {
2296
+ const keys = Object.keys(value);
2297
+ if (opts.unknownProps !== "strip") return keys.length;
2298
+ let count = 0;
2299
+ for (const key of keys) if (!isUnknownKey(props, key)) count++;
2300
+ return count;
2301
+ }
2302
+ /**
2303
+ * `@expect.minKeys` / `maxKeys` in `metadata` (an object's or a union's) of object `value`,
2304
+ * matched as `branch` (pattern props: the walk).
2305
+ */ function objectKeyCounts(metadata, value, branch, opts) {
2306
+ const minKeys = metadata.get("expect.minKeys");
2307
+ const maxKeys = metadata.get("expect.maxKeys");
2308
+ if (minKeys === void 0 && maxKeys === void 0) return PASS;
2309
+ const type = branch.type;
2310
+ let count;
2311
+ if (type.kind !== "object") count = Object.keys(value).length;
2312
+ else if (type.propsPatterns.length > 0 && opts.unknownProps !== "ignore") return BAIL;
2313
+ else count = keptKeys(type.props, value, opts);
2314
+ return countFails(count, minKeys, maxKeys) ? FAIL : PASS;
2315
+ }
2139
2316
  /**
2140
2317
  * {@link fastCheck} of an intersection (a function of its own: `fastCheck` stays small, so the
2141
2318
  * engine inlines it in the hot object and prop checks).
@@ -2172,6 +2349,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2172
2349
  }
2173
2350
  }
2174
2351
  if (result !== PASS) return result;
2352
+ const metadata = filledMeta(def.metadata);
2353
+ if (metadata !== void 0 && objectKeyCounts(metadata, value, def, opts) === FAIL) return FAIL;
2175
2354
  if (unknownProps === "strip") {
2176
2355
  pendStrips(type.props, value);
2177
2356
  return PASS;
@@ -2230,41 +2409,42 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2230
2409
  const plans = /* @__PURE__ */ new WeakMap();
2231
2410
  /** One shape for every plan, so plan field access stays monomorphic. */ let Plan = class Plan {
2232
2411
  constructor(def) {
2233
- _define_property$4(this, "def", void 0);
2234
- /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$4(this, "stamp", void 0);
2235
- /** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$4(this, "metaStamp", void 0);
2236
- _define_property$4(this, "op", void 0);
2237
- _define_property$4(this, "type", void 0);
2238
- _define_property$4(this, "optional", void 0);
2239
- _define_property$4(this, "metadata", void 0);
2240
- _define_property$4(this, "kind", void 0);
2241
- _define_property$4(this, "designType", void 0);
2242
- _define_property$4(this, "literal", void 0);
2243
- /** 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);
2244
2423
  /**
2245
2424
  * Annotation keys the node's check reads, and their values (`undefined` when absent):
2246
2425
  * string `meta.required, expect.minLength, maxLength, pattern`; number `expect.int, min,
2247
- * max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`.
2248
- */ _define_property$4(this, "k0", void 0);
2249
- _define_property$4(this, "k1", void 0);
2250
- _define_property$4(this, "k2", void 0);
2251
- _define_property$4(this, "k3", void 0);
2252
- _define_property$4(this, "k4", void 0);
2253
- _define_property$4(this, "m0", void 0);
2254
- _define_property$4(this, "m1", void 0);
2255
- _define_property$4(this, "m2", void 0);
2256
- _define_property$4(this, "m3", void 0);
2257
- _define_property$4(this, "m4", void 0);
2258
- _define_property$4(this, "props", void 0);
2259
- _define_property$4(this, "propsPatterns", void 0);
2260
- _define_property$4(this, "keys", void 0);
2261
- /** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$4(this, "edges", void 0);
2262
- /** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$4(this, "byKey", void 0);
2263
- _define_property$4(this, "nodes", void 0);
2264
- _define_property$4(this, "children", void 0);
2265
- _define_property$4(this, "of", void 0);
2266
- _define_property$4(this, "ofPlan", void 0);
2267
- _define_property$4(this, "items", void 0);
2426
+ * max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`;
2427
+ * object `expect.minKeys, maxKeys`.
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);
2268
2448
  this.def = def;
2269
2449
  this.stamp = -1;
2270
2450
  this.metaStamp = -1;
@@ -2412,6 +2592,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2412
2592
  plan.byKey = byKey;
2413
2593
  plan.props = type.props;
2414
2594
  plan.propsPatterns = type.propsPatterns;
2595
+ setMetaKeys(plan, ...OBJECT_KEYS);
2415
2596
  plan.op = OP_OBJECT;
2416
2597
  break;
2417
2598
  }
@@ -2525,16 +2706,28 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2525
2706
  }
2526
2707
  if (result !== PASS) return result;
2527
2708
  const unknownProps = opts.unknownProps;
2528
- if (unknownProps === "error" || unknownProps === "strip") {
2529
- const byKey = plan.byKey;
2530
- for (const key of Object.keys(value)) {
2709
+ const byKey = plan.byKey;
2710
+ if (plan.metaStamp !== stamp) refreshMeta(plan);
2711
+ if ((plan.m0 !== void 0 || plan.m1 !== void 0) && planKeyCountFails(plan, byKey, value, opts)) return FAIL;
2712
+ if (unknownProps === "error" || unknownProps === "strip") for (const key of Object.keys(value)) {
2713
+ const known = byKey.get(key);
2714
+ if (known !== void 0 && known.op !== OP_PHANTOM) continue;
2715
+ if (unknownProps === "error") return FAIL;
2716
+ pendingStrips.push(value, key);
2717
+ }
2718
+ return PASS;
2719
+ }
2720
+ /** The key counts of an object plan (see `keptKeys`; `byKey` verified). */ function planKeyCountFails(plan, byKey, value, opts) {
2721
+ const keys = Object.keys(value);
2722
+ let count = keys.length;
2723
+ if (opts.unknownProps === "strip") {
2724
+ count = 0;
2725
+ for (const key of keys) {
2531
2726
  const known = byKey.get(key);
2532
- if (known !== void 0 && known.op !== OP_PHANTOM) continue;
2533
- if (unknownProps === "error") return FAIL;
2534
- pendingStrips.push(value, key);
2727
+ if (known !== void 0 && known.op !== OP_PHANTOM) count++;
2535
2728
  }
2536
2729
  }
2537
- return PASS;
2730
+ return countFails(count, plan.m0, plan.m1);
2538
2731
  }
2539
2732
  /** Plan counterpart of {@link fastCheckArray}. */ function checkArray(plan, value, flags, opts) {
2540
2733
  if (!Array.isArray(value)) return FAIL;
@@ -2544,9 +2737,150 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2544
2737
  return checkItems(plan.ofPlan, value, flags, opts);
2545
2738
  }
2546
2739
 
2740
+ //#endregion
2741
+ //#region packages/typescript/src/runtime/validator-messages.ts
2742
+ /**
2743
+ * Validator error codes, their default English templates and the translation helpers.
2744
+ *
2745
+ * The validator is locale-agnostic: every error it reports carries a stable `code` and the
2746
+ * `params` its message needs, and its `message` is the default English text (the code's
2747
+ * template filled with the params) or the app's own text from an annotation (`custom: true`).
2748
+ * Translate after the fact with {@link localizeErrors}, or per validator with the `translate`
2749
+ * option.
2750
+ */ /**
2751
+ * Default English templates of the built-in error codes. `{name}` is replaced with
2752
+ * `params.name` (see {@link formatValidatorMessage}).
2753
+ */ const VALIDATOR_MESSAGES = Object.freeze({
2754
+ REQUIRED: "Must not be empty",
2755
+ REQUIRED_CHECKED: "Must be checked",
2756
+ TYPE: "Expected {expected}, got {actual}",
2757
+ TYPE_ARRAY: "Expected array",
2758
+ TYPE_OBJECT: "Expected object",
2759
+ TYPE_DECIMAL: "Expected string (decimal), got {actual}",
2760
+ NOT_FINITE: "Expected finite number, got {actual}",
2761
+ DECIMAL_FORMAT: "Invalid decimal format: \"{value}\"",
2762
+ NEVER: "This type is impossible, must be an internal problem",
2763
+ LITERAL: "Expected {expected}, got {actual}",
2764
+ UNION: "Value does not match any of the allowed types: {expected}",
2765
+ UNION_DISCRIMINATOR: "Expected one of {allowed}, got {actual}",
2766
+ UNEXPECTED_PROPERTY: "Unexpected property",
2767
+ TUPLE_LENGTH: "Expected array of length {length}",
2768
+ MIN_LENGTH: "Expected minimum length of {min} characters, got {actual} characters",
2769
+ MAX_LENGTH: "Expected maximum length of {max} characters, got {actual} characters",
2770
+ MIN_ITEMS: "Expected minimum length of {min} items, got {actual} items",
2771
+ MAX_ITEMS: "Expected maximum length of {max} items, got {actual} items",
2772
+ UNIQUE_ITEMS: "Duplicate items are not allowed",
2773
+ MIN_KEYS: "Expected at least {min} properties, got {actual}",
2774
+ MAX_KEYS: "Expected at most {max} properties, got {actual}",
2775
+ PATTERN: "Value is expected to match pattern \"{pattern}\"",
2776
+ INT: "Expected integer, got {actual}",
2777
+ MIN: "Expected minimum {min}, got {actual}",
2778
+ MAX: "Expected maximum {max}, got {actual}",
2779
+ EXCLUSIVE_MIN: "Expected greater than {min}, got {actual}",
2780
+ EXCLUSIVE_MAX: "Expected less than {max}, got {actual}",
2781
+ EMAIL: "Invalid email format.",
2782
+ PHONE: "Invalid phone number format.",
2783
+ DATE: "Invalid date format.",
2784
+ ISO_DATE: "Invalid ISO date format.",
2785
+ UUID: "Invalid UUID format.",
2786
+ URL: "Invalid URL format.",
2787
+ IPV4: "Invalid IPv4 address.",
2788
+ IPV6: "Invalid IPv6 address.",
2789
+ IP: "Invalid IP address."
2790
+ });
2791
+ /**
2792
+ * The built-in validator error codes by name (`VALIDATOR_ERROR_CODES.MIN_LENGTH === 'MIN_LENGTH'`).
2793
+ * `CUSTOM` is the code of an error a validator plugin reports without a code of its own.
2794
+ */ const VALIDATOR_ERROR_CODES = Object.freeze(Object.fromEntries([...Object.keys(VALIDATOR_MESSAGES), "CUSTOM"].map((code) => [code, code])));
2795
+ /**
2796
+ * Codes of the format messages built into the `string.*` primitives, by their English text
2797
+ * (the primitives' `@expect.pattern` message).
2798
+ */ const FORMAT_CODES = new Map([
2799
+ "EMAIL",
2800
+ "PHONE",
2801
+ "DATE",
2802
+ "ISO_DATE",
2803
+ "UUID",
2804
+ "URL",
2805
+ "IPV4",
2806
+ "IPV6",
2807
+ "IP"
2808
+ ].map((code) => [VALIDATOR_MESSAGES[code], code]));
2809
+ /** The code of a primitive's built-in format message (`string.email`'s → `EMAIL`), if it is one. */ function formatCodeOf(message) {
2810
+ return FORMAT_CODES.get(message);
2811
+ }
2812
+ /**
2813
+ * Fills a message template: each `{name}` becomes `params.name` (arrays: their items joined
2814
+ * with `, `). A placeholder without a param stays as it is.
2815
+ */ function formatValidatorMessage(template, params) {
2816
+ if (params === void 0) return template;
2817
+ const parts = BUILTIN_PARTS.get(template);
2818
+ if (parts === void 0) return template.includes("{") ? template.replaceAll(PLACEHOLDER, fill(params)) : template;
2819
+ let out = parts[0];
2820
+ for (let i = 1; i < parts.length; i += 2) out += paramText(params, parts[i]) + parts[i + 1];
2821
+ return out;
2822
+ }
2823
+ const PLACEHOLDER = /\{(\w+)\}/g;
2824
+ /** The replacer of {@link PLACEHOLDER} over `params`. */ function fill(params) {
2825
+ return (_match, name) => paramText(params, name);
2826
+ }
2827
+ /** The text of placeholder `name` (the placeholder itself without the param). */ function paramText(params, name) {
2828
+ if (!Object.hasOwn(params, name)) return `{${name}}`;
2829
+ const value = params[name];
2830
+ return Array.isArray(value) ? value.map(String).join(", ") : String(value);
2831
+ }
2832
+ /**
2833
+ * The {@link VALIDATOR_MESSAGES} templates with placeholders, split at them: text, name, text,
2834
+ * name, …, text (`'a {b} c'.split(/\{(\w+)\}/)`).
2835
+ */ const BUILTIN_PARTS = new Map(Object.values(VALIDATOR_MESSAGES).filter((template) => template.includes("{")).map((template) => [template, template.split(/\{(\w+)\}/)]));
2836
+ /**
2837
+ * Returns `errors` with translated messages (new objects; `details` too): `translate` gets
2838
+ * each error's code (or its message text, for app text — see {@link TValidatorTranslate}),
2839
+ * params and the error itself. Errors it returns `undefined` for keep their message.
2840
+ *
2841
+ * @example
2842
+ * ```ts
2843
+ * const errors = localizeErrors(validator.errors, (id, params) =>
2844
+ * i18n.exists(id) ? i18n.t(id, params) : undefined
2845
+ * )
2846
+ * ```
2847
+ */ function localizeErrors(errors, translate) {
2848
+ return errors.map((error) => {
2849
+ const id = error.custom || error.code === void 0 ? error.message : error.code;
2850
+ const out = { ...error };
2851
+ if (error.params !== void 0) out.params = copyValue(error.params);
2852
+ const message = translate(id, out.params ?? {}, out);
2853
+ if (message !== void 0) out.message = message;
2854
+ if (error.details) out.details = localizeErrors(error.details, translate);
2855
+ return out;
2856
+ });
2857
+ }
2858
+ /** A copy of `value`: plain objects and arrays copied, at any depth (error params). */ function copyValue(value) {
2859
+ if (Array.isArray(value)) return value.map(copyValue);
2860
+ if (typeof value === "object" && value !== null) {
2861
+ const out = {};
2862
+ for (const [key, item] of Object.entries(value)) out[key] = copyValue(item);
2863
+ return out;
2864
+ }
2865
+ return value;
2866
+ }
2867
+ /**
2868
+ * A {@link TValidatorTranslate} over a map of message templates keyed by code (and, for app
2869
+ * text, by the text itself): `{name}` placeholders are filled from the error's params. Ids
2870
+ * missing from the map keep their message.
2871
+ *
2872
+ * @example
2873
+ * ```ts
2874
+ * // templates served per locale, e.g. { MIN_LENGTH: 'Mindestens {min} Zeichen', … }
2875
+ * localizeErrors(errors, messagesTranslator(templates))
2876
+ * ```
2877
+ */ function messagesTranslator(messages) {
2878
+ return (id, params) => Object.hasOwn(messages, id) ? formatValidatorMessage(messages[id], params) : void 0;
2879
+ }
2880
+
2547
2881
  //#endregion
2548
2882
  //#region packages/typescript/src/runtime/validator.ts
2549
- function _define_property$3(obj, key, value) {
2883
+ function _define_property$4(obj, key, value) {
2550
2884
  if (key in obj) Object.defineProperty(obj, key, {
2551
2885
  value,
2552
2886
  enumerable: true,
@@ -2591,36 +2925,67 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2591
2925
  pop(saveErrors) {
2592
2926
  this.depth--;
2593
2927
  const popped = this.stackErrors.pop();
2594
- if (saveErrors && popped !== null && popped !== void 0 && popped.length > 0) for (const err of popped) this.error(err.message, err.path, err.details);
2928
+ if (saveErrors && popped) this.reportAll(popped);
2595
2929
  return popped;
2596
2930
  }
2597
2931
  clear() {
2598
2932
  this.stackErrors[this.stackErrors.length - 1] = null;
2599
2933
  if (this.limitExceeded) this.limitExceeded = false;
2600
2934
  }
2601
- error(message, path, details) {
2602
- let errors = this.stackErrors[this.stackErrors.length - 1];
2603
- if (!errors) if (this.stackErrors.length > 0) {
2604
- errors = [];
2605
- this.stackErrors[this.stackErrors.length - 1] = errors;
2606
- } else errors = this.errors;
2935
+ /**
2936
+ * Reports an error at `path` (default: the current path). `info` gives its code and params;
2937
+ * without it the error is app text with code `CUSTOM` (a plugin's own message).
2938
+ */ error(message, path, details, info) {
2607
2939
  const error = {
2608
2940
  path: path || this.buildPath(),
2609
- message
2941
+ message,
2942
+ code: info?.code ?? "CUSTOM",
2943
+ params: info?.params ?? {}
2610
2944
  };
2945
+ if (info?.custom ?? info?.code === void 0) error.custom = true;
2611
2946
  if (details?.length) error.details = details;
2612
- errors.push(error);
2613
- if (errors.length >= this.opts.errorLimit) this.limitExceeded = true;
2947
+ this.report(error);
2614
2948
  return error;
2615
2949
  }
2616
- /** Adds `error`, already made, to the errors of the current level (as {@link error} does). */ report(error) {
2950
+ /**
2951
+ * Reports built-in error `code`: `custom` (the app's message from an annotation) when given,
2952
+ * else the code's template filled with `params`.
2953
+ */ fail(code, params, custom) {
2954
+ this.builtin(code, params, custom);
2955
+ return false;
2956
+ }
2957
+ /** Reports built-in error `code` at `path` (see {@link fail}), with `details` (a union's). */ builtin(code, params, custom, path, details) {
2958
+ return custom ? this.error(custom, path, details, {
2959
+ code,
2960
+ params,
2961
+ custom: true
2962
+ }) : this.error(formatValidatorMessage(VALIDATOR_MESSAGES[code], params), path, details, {
2963
+ code,
2964
+ params
2965
+ });
2966
+ }
2967
+ /** {@link fail} of a type mismatch of `def`: its `@expect.message` replaces the message. */ mismatch(def, code, params) {
2968
+ return this.fail(code, params, expectMessage(def));
2969
+ }
2970
+ /** The `@meta.required` error of `def` (custom message or the type's default). */ required(def) {
2971
+ const isBoolean = def.type.kind === "" && def.type.designType === "boolean";
2972
+ return this.fail(isBoolean ? "REQUIRED_CHECKED" : "REQUIRED", {}, messageOf(def.metadata.get("meta.required")));
2973
+ }
2974
+ /**
2975
+ * Adds `error`, already made, to the errors of the current level (as {@link error} does);
2976
+ * `true` once the level holds as many errors as the limit.
2977
+ */ report(error) {
2617
2978
  let errors = this.stackErrors[this.stackErrors.length - 1];
2618
2979
  if (!errors) if (this.stackErrors.length > 0) {
2619
2980
  errors = [];
2620
2981
  this.stackErrors[this.stackErrors.length - 1] = errors;
2621
2982
  } else errors = this.errors;
2622
2983
  errors.push(error);
2623
- if (errors.length >= this.opts.errorLimit) this.limitExceeded = true;
2984
+ if (errors.length >= this.opts.errorLimit) {
2985
+ this.limitExceeded = true;
2986
+ return true;
2987
+ }
2988
+ return false;
2624
2989
  }
2625
2990
  throw() {
2626
2991
  throw new ValidatorError(this.errors);
@@ -2650,6 +3015,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2650
3015
  if (this.unionMemo !== void 0) this.unionMemo = void 0;
2651
3016
  if (this.strips.length > 0) performStrips(this.strips, passed);
2652
3017
  if (!passed) {
3018
+ if (this.opts.translate) this.errors = localizeErrors(this.errors, this.opts.translate);
2653
3019
  if (safe) return false;
2654
3020
  this.throw();
2655
3021
  }
@@ -2667,10 +3033,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2667
3033
  if (this.limitExceeded) return false;
2668
3034
  if (this.hasReplace) def = this.replaced(def);
2669
3035
  if (def.optional && (value === void 0 || value === null)) {
2670
- if (value === null && rejectsNullAsRequired(def)) {
2671
- this.error(requiredMessage(def));
2672
- return false;
2673
- }
3036
+ if (value === null && rejectsNullAsRequired(def)) return this.required(def);
2674
3037
  return true;
2675
3038
  }
2676
3039
  if (this.hasPlugins) {
@@ -2684,10 +3047,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2684
3047
  * optional `def` passes `undefined` / `null`, a plugin may decide — `undefined` to go on.
2685
3048
  */ preCheck(def, value) {
2686
3049
  if (def.optional && (value === void 0 || value === null)) {
2687
- if (value === null && rejectsNullAsRequired(def)) {
2688
- this.error(requiredMessage(def));
2689
- return false;
2690
- }
3050
+ if (value === null && rejectsNullAsRequired(def)) return this.required(def);
2691
3051
  return true;
2692
3052
  }
2693
3053
  if (this.hasPlugins) {
@@ -2709,7 +3069,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2709
3069
  if (!passed && this.strips.length !== kept) this.strips.length = kept;
2710
3070
  return passed;
2711
3071
  },
2712
- error: (message, path, details) => this.error(message, path, details)
3072
+ error: (message, path, details, info) => this.error(message, path, details, info)
2713
3073
  }, {
2714
3074
  opts: {
2715
3075
  get: () => this.opts,
@@ -2774,11 +3134,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2774
3134
  path = this.buildPath();
2775
3135
  const known = this.decided(def, value, path);
2776
3136
  if (known !== void 0) {
2777
- if (known.error === void 0) {
3137
+ if (known.errors === void 0) {
2778
3138
  stripAgain(this.strips, known.strips);
2779
3139
  return this.validateUnionConstraints(def, known.item, value);
2780
3140
  }
2781
- this.report(known.error);
3141
+ this.reportAll(known.errors);
2782
3142
  return false;
2783
3143
  }
2784
3144
  }
@@ -2787,6 +3147,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2787
3147
  } else this.wasted = 0;
2788
3148
  const kept = this.strips.length;
2789
3149
  let details;
3150
+ /**
3151
+ * Where each failed branch's errors start in `details` (by branch index): plain object
3152
+ * values only, the ones a discriminator can report (see `discriminatedErrors`).
3153
+ */ let starts;
3154
+ const plainObject = typeof value === "object" && value !== null && !Array.isArray(value);
2790
3155
  for (const item of items) {
2791
3156
  this.stackErrors.push(null);
2792
3157
  const failures = this.nestedFailures;
@@ -2803,14 +3168,52 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2803
3168
  if (this.limitExceeded) this.limitExceeded = false;
2804
3169
  if (this.nestedFailures !== failures) this.wasteBranch();
2805
3170
  if (nested) this.nestedFailures++;
3171
+ if (plainObject) (starts ?? (starts = [])).push(details?.length ?? 0);
2806
3172
  if (branchErrors) if (details) for (const err of branchErrors) details.push(err);
2807
3173
  else details = branchErrors;
2808
3174
  }
2809
- const expected = items.map((item, i) => `[${item.type.kind || item.type.designType}(${i})]`).join(", ");
2810
- const error = this.error(`Value does not match any of the allowed types: ${expected}`, void 0, details);
2811
- if (path !== void 0) this.decide(def, value, path, kept, void 0, error);
3175
+ const errors = this.discriminatedErrors(def, value, details, starts ?? []) ?? this.unionError(def, details);
3176
+ if (path !== void 0) this.decide(def, value, path, kept, void 0, errors);
2812
3177
  return false;
2813
3178
  }
3179
+ /** Reports the error of union `def` no branch matched (`details`: the branches' errors). */ unionError(def, details) {
3180
+ const expected = def.type.items.map((item, i) => `[${item.type.kind || item.type.designType}(${i})]`).join(", ");
3181
+ return [this.builtin("UNION", { expected }, expectMessage(def), void 0, details)];
3182
+ }
3183
+ /**
3184
+ * The errors of an object union over object `value` with a shared literal discriminator (see
3185
+ * {@link unionDiscriminator}), reported in place of the union error: the errors of the branch
3186
+ * the value's discriminator picks, or one `UNION_DISCRIMINATOR` error at the discriminator
3187
+ * when it picks none. `undefined` (nothing reported) for other unions and values.
3188
+ */ discriminatedErrors(def, value, details, starts) {
3189
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
3190
+ const disc = unionDiscriminator(def.type.items);
3191
+ if (disc === void 0) return;
3192
+ const tag = value[disc.property];
3193
+ if (tag === void 0 && this.partialHere()) return;
3194
+ const picked = disc.branches.findIndex(([, literal]) => literal === tag);
3195
+ if (picked < 0) {
3196
+ const params = {
3197
+ property: disc.property,
3198
+ allowed: disc.branches.map(([, literal]) => literal),
3199
+ actual: clip(printValue(tag))
3200
+ };
3201
+ const at = this.depth > 0 ? `${this.buildPath()}.${disc.property}` : disc.property;
3202
+ return [this.builtin("UNION_DISCRIMINATOR", params, expectMessage(def), at)];
3203
+ }
3204
+ const index = disc.branches[picked][0];
3205
+ const errors = details?.slice(starts[index], starts[index + 1] ?? details.length);
3206
+ if (errors === void 0 || errors.length === 0) return;
3207
+ this.reportAll(errors);
3208
+ return errors;
3209
+ }
3210
+ /** Reports `errors`, made already, until the error limit is reached. */ reportAll(errors) {
3211
+ for (const error of errors) if (this.report(error)) break;
3212
+ }
3213
+ /** Whether missing props are allowed at the current depth (the `partial` option). */ partialHere() {
3214
+ const partial = this.opts.partial;
3215
+ return partial === "deep" || partial === true && this.depth === 0 || typeof partial === "function";
3216
+ }
2814
3217
  /** A union branch failed after branches of nested unions over objects did (see `unionMemo`). */ wasteBranch() {
2815
3218
  if (++this.wasted === WASTE_BEFORE_MEMO && this.unionMemo === void 0) this.unionMemo = /* @__PURE__ */ new Map();
2816
3219
  }
@@ -2824,13 +3227,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2824
3227
  /**
2825
3228
  * Records the outcome of union `def` over `value` at `path`, entered with `kept` strips (the
2826
3229
  * ones after them are its own).
2827
- */ decide(def, value, path, kept, item, error) {
3230
+ */ decide(def, value, path, kept, item, errors) {
2828
3231
  const outcome = {
2829
3232
  def,
2830
3233
  path,
2831
3234
  unknownProps: this.opts.unknownProps,
2832
3235
  item,
2833
- error,
3236
+ errors,
2834
3237
  strips: stripsSince(this.strips, kept)
2835
3238
  };
2836
3239
  const outcomes = this.unionMemo.get(value);
@@ -2850,7 +3253,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2850
3253
  case "boolean": return this.validateBooleanConstraints(metadata, value);
2851
3254
  case "object":
2852
3255
  if (Array.isArray(value)) return this.validateArrayConstraints(metadata, value, arrayElementType(branch));
2853
- return true;
3256
+ return value === null || this.validateObjectConstraints(metadata, value, branch, this.skipListHere());
2854
3257
  default: return true;
2855
3258
  }
2856
3259
  }
@@ -2864,7 +3267,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2864
3267
  */ unknownKey(key, keysToStrip) {
2865
3268
  if (this.opts.unknownProps === "error") {
2866
3269
  this.push(key);
2867
- this.error(`Unexpected property`);
3270
+ this.fail("UNEXPECTED_PROPERTY", { property: clip(key) });
2868
3271
  this.pop(true);
2869
3272
  } else if (this.opts.unknownProps === "strip") (keysToStrip ?? (keysToStrip = [])).push(key);
2870
3273
  return keysToStrip;
@@ -2877,10 +3280,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2877
3280
  return skipList;
2878
3281
  }
2879
3282
  validateTuple(def, value) {
2880
- if (!Array.isArray(value) || value.length !== def.type.items.length) {
2881
- this.error(`Expected array of length ${def.type.items.length}`);
2882
- return false;
2883
- }
3283
+ if (!Array.isArray(value) || value.length !== def.type.items.length) return this.mismatch(def, "TUPLE_LENGTH", { length: def.type.items.length });
2884
3284
  let i = 0;
2885
3285
  for (const item of def.type.items) {
2886
3286
  this.push(String(i));
@@ -2894,10 +3294,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2894
3294
  return true;
2895
3295
  }
2896
3296
  validateArray(def, value) {
2897
- if (!Array.isArray(value)) {
2898
- this.error("Expected array");
2899
- return false;
2900
- }
3297
+ if (!Array.isArray(value)) return this.mismatch(def, "TYPE_ARRAY", { actual: typeOf(value) });
2901
3298
  if (!metaEmpty(def.metadata) && !this.validateArrayConstraints(def.metadata, value, def.type.of)) return false;
2902
3299
  let i = 0;
2903
3300
  let passed = true;
@@ -2916,21 +3313,19 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2916
3313
  const metadata = readable(meta);
2917
3314
  const minLength = metadata.get("expect.minLength");
2918
3315
  if (minLength !== void 0) {
2919
- const length = typeof minLength === "number" ? minLength : minLength.length;
2920
- if (value.length < length) {
2921
- const message = typeof minLength === "object" && minLength.message ? minLength.message : `Expected minimum length of ${length} items, got ${value.length} items`;
2922
- this.error(message);
2923
- return false;
2924
- }
3316
+ const length = boundOf(minLength, "length");
3317
+ if (value.length < length) return this.fail("MIN_ITEMS", {
3318
+ min: length,
3319
+ actual: value.length
3320
+ }, messageOf(minLength));
2925
3321
  }
2926
3322
  const maxLength = metadata.get("expect.maxLength");
2927
3323
  if (maxLength !== void 0) {
2928
- const length = typeof maxLength === "number" ? maxLength : maxLength.length;
2929
- if (value.length > length) {
2930
- const message = typeof maxLength === "object" && maxLength.message ? maxLength.message : `Expected maximum length of ${length} items, got ${value.length} items`;
2931
- this.error(message);
2932
- return false;
2933
- }
3324
+ const length = boundOf(maxLength, "length");
3325
+ if (value.length > length) return this.fail("MAX_ITEMS", {
3326
+ max: length,
3327
+ actual: value.length
3328
+ }, messageOf(maxLength));
2934
3329
  }
2935
3330
  const uniqueItems = metadata.get("expect.array.uniqueItems");
2936
3331
  if (uniqueItems) {
@@ -2946,7 +3341,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2946
3341
  } else key = JSON.stringify(item);
2947
3342
  if (seen.has(key)) {
2948
3343
  this.push(String(idx));
2949
- this.error(uniqueItems.message || "Duplicate items are not allowed");
3344
+ this.fail("UNIQUE_ITEMS", {}, messageOf(uniqueItems));
2950
3345
  this.pop(true);
2951
3346
  return false;
2952
3347
  }
@@ -2956,13 +3351,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2956
3351
  return true;
2957
3352
  }
2958
3353
  validateObject(def, value) {
2959
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
2960
- this.error("Expected object");
2961
- return false;
2962
- }
3354
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return this.mismatch(def, "TYPE_OBJECT", { actual: typeOf(value) });
3355
+ const skipList = this.opts.skipList ? this.skipListHere() : void 0;
2963
3356
  let passed = true;
3357
+ if (!this.validateObjectConstraints(def.metadata, value, def, skipList)) {
3358
+ if (this.limitExceeded) return false;
3359
+ passed = false;
3360
+ }
2964
3361
  let keysToStrip;
2965
- const skipList = this.opts.skipList ? this.skipListHere() : void 0;
2966
3362
  let partialFunctionMatched = false;
2967
3363
  if (typeof this.opts.partial === "function") partialFunctionMatched = this.opts.partial(def, this.buildPath());
2968
3364
  for (const [key, item] of def.type.props.entries()) {
@@ -3022,63 +3418,58 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3022
3418
  }
3023
3419
  validatePrimitive(def, value) {
3024
3420
  if (def.type.value !== void 0) {
3025
- if (value !== def.type.value) {
3026
- this.error(`Expected ${def.type.value}, got ${printValue(value)}`);
3027
- return false;
3028
- }
3421
+ if (value !== def.type.value) return this.mismatch(def, "LITERAL", {
3422
+ expected: def.type.value,
3423
+ actual: clip(printValue(value))
3424
+ });
3029
3425
  return true;
3030
3426
  }
3031
- const typeOfValue = Array.isArray(value) ? "array" : typeof value;
3032
- switch (def.type.designType) {
3033
- case "never":
3034
- this.error(`This type is impossible, must be an internal problem`);
3035
- return false;
3036
- case "any": return true;
3427
+ const typeOfValue = typeOf(value);
3428
+ const designType = def.type.designType;
3429
+ switch (designType) {
3430
+ case "never": return this.fail("NEVER", {});
3431
+ case "any":
3432
+ if (value === void 0) return this.mismatch(def, "TYPE", {
3433
+ expected: "unknown",
3434
+ actual: typeOfValue
3435
+ });
3436
+ return true;
3037
3437
  case "string":
3038
- if (typeOfValue !== def.type.designType) {
3039
- this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
3040
- return false;
3041
- }
3438
+ if (typeOfValue !== designType) return this.mismatch(def, "TYPE", {
3439
+ expected: designType,
3440
+ actual: typeOfValue
3441
+ });
3042
3442
  return this.validateString(def, value);
3043
3443
  case "number":
3044
- if (typeOfValue !== def.type.designType) {
3045
- this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
3046
- return false;
3047
- }
3048
- if (!Number.isFinite(value)) {
3049
- this.error(`Expected finite number, got ${value}`);
3050
- return false;
3051
- }
3444
+ if (typeOfValue !== designType) return this.mismatch(def, "TYPE", {
3445
+ expected: designType,
3446
+ actual: typeOfValue
3447
+ });
3448
+ if (!Number.isFinite(value)) return this.mismatch(def, "NOT_FINITE", { actual: String(value) });
3052
3449
  return this.validateNumber(def, value);
3053
3450
  case "boolean":
3054
- if (typeOfValue !== def.type.designType) {
3055
- this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
3056
- return false;
3057
- }
3451
+ if (typeOfValue !== designType) return this.mismatch(def, "TYPE", {
3452
+ expected: designType,
3453
+ actual: typeOfValue
3454
+ });
3058
3455
  return this.validateBoolean(def, value);
3059
3456
  case "undefined":
3060
- if (value !== void 0) {
3061
- this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
3062
- return false;
3063
- }
3457
+ if (value !== void 0) return this.mismatch(def, "TYPE", {
3458
+ expected: designType,
3459
+ actual: typeOfValue
3460
+ });
3064
3461
  return true;
3065
3462
  case "null":
3066
- if (value !== null) {
3067
- this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
3068
- return false;
3069
- }
3463
+ if (value !== null) return this.mismatch(def, "TYPE", {
3464
+ expected: designType,
3465
+ actual: typeOfValue
3466
+ });
3070
3467
  return true;
3071
3468
  case "decimal":
3072
- if (typeOfValue !== "string") {
3073
- this.error(`Expected string (decimal), got ${typeOfValue}`);
3074
- return false;
3075
- }
3076
- if (!DECIMAL_RE.test(value)) {
3077
- this.error(`Invalid decimal format: ${JSON.stringify(value)}`);
3078
- return false;
3079
- }
3469
+ if (typeOfValue !== "string") return this.mismatch(def, "TYPE_DECIMAL", { actual: typeOfValue });
3470
+ if (!DECIMAL_RE.test(value)) return this.mismatch(def, "DECIMAL_FORMAT", { value: clip(value) });
3080
3471
  return true;
3081
- default: throw new Error(`Unknown type "${def.type.designType}"`);
3472
+ default: throw new Error(`Unknown type "${designType}"`);
3082
3473
  }
3083
3474
  }
3084
3475
  validateString(def, value) {
@@ -3089,36 +3480,33 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3089
3480
  if (metadata === void 0) return true;
3090
3481
  const filled = metadata.get("meta.required");
3091
3482
  if (filled) {
3092
- if (value.trim().length === 0) {
3093
- const message = typeof filled === "object" && filled.message ? filled.message : `Must not be empty`;
3094
- this.error(message);
3095
- return false;
3096
- }
3483
+ if (value.trim().length === 0) return this.fail("REQUIRED", {}, messageOf(filled));
3097
3484
  }
3098
3485
  const minLength = metadata.get("expect.minLength");
3099
3486
  if (minLength !== void 0) {
3100
- const length = typeof minLength === "number" ? minLength : minLength.length;
3101
- if (value.length < length) {
3102
- const message = typeof minLength === "object" && minLength.message ? minLength.message : `Expected minimum length of ${length} characters, got ${value.length} characters`;
3103
- this.error(message);
3104
- return false;
3105
- }
3487
+ const length = boundOf(minLength, "length");
3488
+ if (value.length < length) return this.fail("MIN_LENGTH", {
3489
+ min: length,
3490
+ actual: value.length
3491
+ }, messageOf(minLength));
3106
3492
  }
3107
3493
  const maxLength = metadata.get("expect.maxLength");
3108
3494
  if (maxLength !== void 0) {
3109
- const length = typeof maxLength === "number" ? maxLength : maxLength.length;
3110
- if (value.length > length) {
3111
- const message = typeof maxLength === "object" && maxLength.message ? maxLength.message : `Expected maximum length of ${length} characters, got ${value.length} characters`;
3112
- this.error(message);
3113
- return false;
3114
- }
3495
+ const length = boundOf(maxLength, "length");
3496
+ if (value.length > length) return this.fail("MAX_LENGTH", {
3497
+ max: length,
3498
+ actual: value.length
3499
+ }, messageOf(maxLength));
3115
3500
  }
3116
3501
  const patterns = metadata.get("expect.pattern");
3117
3502
  for (const { pattern, flags, message } of patterns || []) {
3118
3503
  if (!pattern) continue;
3119
3504
  if (!getRegex(pattern, flags).test(value)) {
3120
- this.error(message || `Value is expected to match pattern "${pattern}"`);
3121
- return false;
3505
+ const format = message ? formatCodeOf(message) : void 0;
3506
+ return format === void 0 ? this.fail("PATTERN", flags ? {
3507
+ pattern,
3508
+ flags
3509
+ } : { pattern }, message) : this.fail(format, {});
3122
3510
  }
3123
3511
  }
3124
3512
  return true;
@@ -3130,38 +3518,41 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3130
3518
  const metadata = filledMeta(meta);
3131
3519
  if (metadata === void 0) return true;
3132
3520
  const int = metadata.get("expect.int");
3133
- if (int && value % 1 !== 0) {
3134
- const message = typeof int === "object" && int.message ? int.message : `Expected integer, got ${value}`;
3135
- this.error(message);
3136
- return false;
3137
- }
3521
+ if (int && value % 1 !== 0) return this.fail("INT", { actual: value }, messageOf(int));
3138
3522
  const min = metadata.get("expect.min");
3139
3523
  if (min !== void 0) {
3140
- const minValue = typeof min === "number" ? min : min.minValue;
3141
- if (value < minValue) return this.numberBoundFailed(min, "minimum", minValue, value);
3524
+ const bound = boundOf(min, "minValue");
3525
+ if (value < bound) return this.fail("MIN", {
3526
+ min: bound,
3527
+ actual: value
3528
+ }, messageOf(min));
3142
3529
  }
3143
3530
  const max = metadata.get("expect.max");
3144
3531
  if (max !== void 0) {
3145
- const maxValue = typeof max === "number" ? max : max.maxValue;
3146
- if (value > maxValue) return this.numberBoundFailed(max, "maximum", maxValue, value);
3532
+ const bound = boundOf(max, "maxValue");
3533
+ if (value > bound) return this.fail("MAX", {
3534
+ max: bound,
3535
+ actual: value
3536
+ }, messageOf(max));
3147
3537
  }
3148
3538
  const exMin = metadata.get("expect.exclusiveMin");
3149
3539
  if (exMin !== void 0) {
3150
- const bound = typeof exMin === "number" ? exMin : exMin.exclusiveMinValue;
3151
- if (value <= bound) return this.numberBoundFailed(exMin, "greater than", bound, value);
3540
+ const bound = boundOf(exMin, "exclusiveMinValue");
3541
+ if (value <= bound) return this.fail("EXCLUSIVE_MIN", {
3542
+ min: bound,
3543
+ actual: value
3544
+ }, messageOf(exMin));
3152
3545
  }
3153
3546
  const exMax = metadata.get("expect.exclusiveMax");
3154
3547
  if (exMax !== void 0) {
3155
- const bound = typeof exMax === "number" ? exMax : exMax.exclusiveMaxValue;
3156
- if (value >= bound) return this.numberBoundFailed(exMax, "less than", bound, value);
3548
+ const bound = boundOf(exMax, "exclusiveMaxValue");
3549
+ if (value >= bound) return this.fail("EXCLUSIVE_MAX", {
3550
+ max: bound,
3551
+ actual: value
3552
+ }, messageOf(exMax));
3157
3553
  }
3158
3554
  return true;
3159
3555
  }
3160
- /** Reports a failed number bound: its custom message, else `Expected <label> <bound>, got <value>`. */ numberBoundFailed(annotation, label, bound, value) {
3161
- const message = typeof annotation === "object" && annotation.message ? annotation.message : `Expected ${label} ${bound}, got ${value}`;
3162
- this.error(message);
3163
- return false;
3164
- }
3165
3556
  validateBoolean(def, value) {
3166
3557
  return this.validateBooleanConstraints(def.metadata, value);
3167
3558
  }
@@ -3170,26 +3561,71 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3170
3561
  if (metadata === void 0) return true;
3171
3562
  const filled = metadata.get("meta.required");
3172
3563
  if (filled) {
3173
- if (value !== true) {
3174
- const message = typeof filled === "object" && filled.message ? filled.message : `Must be checked`;
3175
- this.error(message);
3176
- return false;
3177
- }
3564
+ if (value !== true) return this.fail("REQUIRED_CHECKED", {}, messageOf(filled));
3565
+ }
3566
+ return true;
3567
+ }
3568
+ /**
3569
+ * `@expect.minKeys` / `maxKeys` checks for an object value, matched as `shape`: the keys the
3570
+ * result keeps are counted (see {@link keptKeyCount}; `skipList`: the skip list keys here).
3571
+ */ validateObjectConstraints(meta, value, shape, skipList) {
3572
+ const metadata = filledMeta(meta);
3573
+ if (metadata === void 0) return true;
3574
+ const minKeys = metadata.get("expect.minKeys");
3575
+ const maxKeys = metadata.get("expect.maxKeys");
3576
+ if (minKeys === void 0 && maxKeys === void 0) return true;
3577
+ const count = this.keptKeyCount(shape, value, skipList);
3578
+ if (minKeys !== void 0) {
3579
+ const bound = boundOf(minKeys, "count");
3580
+ if (count < bound) return this.fail("MIN_KEYS", {
3581
+ min: bound,
3582
+ actual: count
3583
+ }, messageOf(minKeys));
3584
+ }
3585
+ if (maxKeys !== void 0) {
3586
+ const bound = boundOf(maxKeys, "count");
3587
+ if (count > bound) return this.fail("MAX_KEYS", {
3588
+ max: bound,
3589
+ actual: count
3590
+ }, messageOf(maxKeys));
3178
3591
  }
3179
3592
  return true;
3180
3593
  }
3594
+ /**
3595
+ * The keys of object `value` (matched as `shape`) the result keeps: every own key with
3596
+ * `unknownProps: 'ignore'`; else (and with 'strip', and 'error', where the others are errors
3597
+ * of their own) the keys `shape` declares, its pattern props match or the skip list names.
3598
+ * Matched as anything other than an object type, every own key.
3599
+ */ keptKeyCount(shape, value, skipList) {
3600
+ const keys = Object.keys(value);
3601
+ if (this.opts.unknownProps === "ignore" || shape.type.kind !== "object") return keys.length;
3602
+ const type = shape.type;
3603
+ let count = 0;
3604
+ for (const key of keys) {
3605
+ const prop = type.props.get(key);
3606
+ if (prop !== void 0 && !isPhantomType(prop) || skipList?.has(key)) {
3607
+ count++;
3608
+ continue;
3609
+ }
3610
+ for (const { pattern } of type.propsPatterns) if (pattern.test(key)) {
3611
+ count++;
3612
+ break;
3613
+ }
3614
+ }
3615
+ return count;
3616
+ }
3181
3617
  constructor(def, opts) {
3182
- _define_property$3(this, "def", void 0);
3183
- _define_property$3(this, "opts", void 0);
3184
- _define_property$3(this, "hasPlugins", void 0);
3185
- _define_property$3(this, "hasReplace", void 0);
3186
- _define_property$3(this, "replaceCache", void 0);
3187
- /** Validation errors collected during the last {@link validate} call. */ _define_property$3(this, "errors", void 0);
3188
- _define_property$3(this, "stackErrors", void 0);
3189
- _define_property$3(this, "pathSegments", void 0);
3190
- _define_property$3(this, "depth", void 0);
3191
- _define_property$3(this, "limitExceeded", void 0);
3192
- _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);
3193
3629
  /**
3194
3630
  * The unions over objects this call decided inside union branches (value → outcomes). A union
3195
3631
  * nested in its own branches, many branches each, is reached again with the same value and path
@@ -3199,17 +3635,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3199
3635
  * never make it. It decides each such union once, with the same result and the same error object
3200
3636
  * (both depend only on these, the options and the input, which the walk never changes), and
3201
3637
  * records the same strips again.
3202
- */ _define_property$3(this, "unionMemo", void 0);
3203
- /** Union branches being checked (`> 0`: inside a union branch). */ _define_property$3(this, "unionDepth", void 0);
3204
- /** Failed branches of unions over objects inside union branches (see `unionMemo`). */ _define_property$3(this, "nestedFailures", void 0);
3205
- /** 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);
3206
3642
  /**
3207
3643
  * `unknownProps: 'strip'`: the unknown keys of the objects that passed (`object, key, …`), in the
3208
3644
  * order the objects completed, then in key order. A rejected union branch, pattern property
3209
3645
  * attempt or plugin sub-validation drops what it recorded; the keys are deleted once the whole
3210
3646
  * call passes (`performStrips`).
3211
- */ _define_property$3(this, "strips", void 0);
3212
- /** 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);
3213
3649
  this.def = def;
3214
3650
  this.errors = [];
3215
3651
  this.stackErrors = [];
@@ -3232,10 +3668,78 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3232
3668
  if (this.hasReplace) this.replaceCache = /* @__PURE__ */ new WeakMap();
3233
3669
  }
3234
3670
  };
3235
- /** The `@meta.required` error message for `def` (custom message or the type's default). */ function requiredMessage(def) {
3236
- const filled = def.metadata.get("meta.required");
3237
- if (typeof filled === "object" && filled.message) return filled.message;
3238
- return def.type.kind === "" && def.type.designType === "boolean" ? "Must be checked" : "Must not be empty";
3671
+ /** The message argument of a constraint annotation (`{ message }`), if any. */ function messageOf(annotation) {
3672
+ return typeof annotation === "object" && annotation !== null ? annotation.message || void 0 : void 0;
3673
+ }
3674
+ /**
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
+ * discriminator props are the same objects.
3678
+ */ const discCache = /* @__PURE__ */ new WeakMap();
3679
+ /**
3680
+ * The discriminator of a union over objects (see {@link detectDiscriminator}), required in every
3681
+ * object branch: the property and, per object branch, its index in `items` and its literal. The
3682
+ * other branches must reject any object (scalars, arrays, tuples), so only the object branches
3683
+ * can match an object value.
3684
+ */ function unionDiscriminator(items) {
3685
+ const cached = discCache.get(items);
3686
+ if (cached !== void 0 && sameDiscSource(cached, items)) return cached.disc;
3687
+ const entry = {
3688
+ nodes: [...items],
3689
+ types: items.map((item) => item.type),
3690
+ props: [],
3691
+ disc: findDiscriminator(items)
3692
+ };
3693
+ if (entry.disc !== void 0) {
3694
+ const property = entry.disc.property;
3695
+ entry.props = entry.disc.branches.map(([i]) => items[i].type.props.get(property));
3696
+ }
3697
+ discCache.set(items, entry);
3698
+ return entry.disc;
3699
+ }
3700
+ /** Whether `entry` was decided from `items` as they are. */ function sameDiscSource(entry, items) {
3701
+ if (entry.nodes.length !== items.length) return false;
3702
+ for (let i = 0; i < items.length; i++) if (entry.nodes[i] !== items[i] || entry.types[i] !== items[i].type) return false;
3703
+ const disc = entry.disc;
3704
+ if (disc !== void 0) {
3705
+ const branches = disc.branches;
3706
+ for (let j = 0; j < branches.length; j++) if (items[branches[j][0]].type.props.get(disc.property) !== entry.props[j]) return false;
3707
+ }
3708
+ return true;
3709
+ }
3710
+ /** {@link unionDiscriminator}, decided anew. */ function findDiscriminator(items) {
3711
+ const objects = [];
3712
+ const indexes = [];
3713
+ for (const [i, item] of items.entries()) {
3714
+ const type = item.type;
3715
+ if (type.kind === "object") {
3716
+ objects.push(item);
3717
+ indexes.push(i);
3718
+ } else if (type.kind !== "array" && type.kind !== "tuple" && (type.kind !== "" || type.designType === "any" || isPhantomType(item))) return;
3719
+ }
3720
+ const disc = detectDiscriminator(objects);
3721
+ if (!disc) return;
3722
+ const property = disc.propertyName;
3723
+ const branches = [];
3724
+ for (const [j, item] of objects.entries()) {
3725
+ const prop = item.type.props.get(property);
3726
+ if (prop === void 0 || prop.optional) return;
3727
+ branches.push([indexes[j], prop.type.value]);
3728
+ }
3729
+ return {
3730
+ property,
3731
+ branches
3732
+ };
3733
+ }
3734
+ /** The most characters of input copied into params (see {@link clip}). */ const CLIP = 100;
3735
+ /** Input copied into params: at most {@link CLIP} characters (then an ellipsis). */ function clip(text) {
3736
+ return text.length > CLIP ? `${text.slice(0, CLIP)}…` : text;
3737
+ }
3738
+ /** `def`'s `@expect.message` (the message of its type mismatches), if any. */ function expectMessage(def) {
3739
+ return def.metadata.get("expect.message") || void 0;
3740
+ }
3741
+ /** The type name an error reports for `value` (`array` for arrays, else `typeof`). */ function typeOf(value) {
3742
+ return Array.isArray(value) ? "array" : typeof value;
3239
3743
  }
3240
3744
  /**
3241
3745
  * Element type of the array a union branch holds — through nested unions too
@@ -3258,7 +3762,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3258
3762
  }
3259
3763
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */ var ValidatorError = class extends Error {
3260
3764
  constructor(errors) {
3261
- 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";
3262
3766
  }
3263
3767
  };
3264
3768
 
@@ -3492,14 +3996,95 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3492
3996
  }
3493
3997
 
3494
3998
  //#endregion
3495
- //#region packages/typescript/src/runtime/coerce.ts
3999
+ //#region packages/typescript/src/runtime/copy-on-change.ts
3496
4000
  /**
3497
- * Internal sentinel returned when a value cannot be coerced to a type node.
3498
- * Drives union branch selection without allocating per-node result objects.
3499
- */ 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");
3500
4004
  /**
3501
- * Coerces string-transport input (route params, query strings) toward the
3502
- * scalar shapes an annotated type expects.
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
+ }
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/coerce.ts
4085
+ /**
4086
+ * Coerces string-transport input (route params, query strings) toward the
4087
+ * scalar shapes an annotated type expects.
3503
4088
  *
3504
4089
  * Pure and non-throwing: when a value can't be coerced it is returned
3505
4090
  * untouched, leaving the {@link Validator} to report the proper error.
@@ -3546,11 +4131,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3546
4131
  }
3547
4132
  case "object":
3548
4133
  if (!isPlainObject$1(value)) return NO_MATCH;
3549
- return coerceProps(def, value);
3550
- case "array": return Array.isArray(value) ? coerceItems(value, type.of) : NO_MATCH;
4134
+ return mapProps(type, value, coerceChild, void 0);
4135
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
3551
4136
  case "tuple": {
3552
4137
  const items = type.items;
3553
- return Array.isArray(value) && value.length === items.length ? coerceItems(value, void 0, items) : NO_MATCH;
4138
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
3554
4139
  }
3555
4140
  case "union":
3556
4141
  for (const item of type.items) {
@@ -3595,57 +4180,289 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3595
4180
  default: return NO_MATCH;
3596
4181
  }
3597
4182
  }
4183
+ /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
4184
+ const result = coerce(def, input);
4185
+ return result === NO_MATCH ? input : result;
4186
+ }
4187
+
4188
+ //#endregion
4189
+ //#region packages/typescript/src/runtime/normalize.ts
4190
+ const TRIM = 1;
4191
+ const LOWERCASE = 2;
4192
+ const UPPERCASE = 4;
3598
4193
  /**
3599
- * Coerces the props of a plain object. Copy-on-first-change: allocates the
3600
- * output object only when some prop actually coerced, else returns the input.
3601
- */ function coerceProps(def, value) {
3602
- const keys = Object.keys(value);
3603
- let out;
3604
- for (let i = 0; i < keys.length; i++) {
3605
- const key = keys[i];
3606
- const input = value[key];
3607
- let propDef = def.type.props.get(key);
3608
- if (!propDef) {
3609
- for (const { pattern, def: patternDef } of def.type.propsPatterns) if (pattern.test(key)) {
3610
- propDef = patternDef;
3611
- break;
4194
+ * Whether each node's subtree has normalizers: valid until the next metadata write or
4195
+ * `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
4196
+ */ let reach = /* @__PURE__ */ new WeakMap();
4197
+ let stampWrites = -1;
4198
+ let stampEpoch = -1;
4199
+ /**
4200
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
4201
+ * `@normalize.lowercase` and `@normalize.uppercase`.
4202
+ *
4203
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
4204
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
4205
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
4206
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
4207
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
4208
+ * uppercase. Other values (including class instances such as `Date`) and strings without
4209
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
4210
+ *
4211
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
4212
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
4213
+ * value is left as it is. A union normalizes a value only when the result does not depend on
4214
+ * which branch takes it:
4215
+ * - an object union with a discriminator (a literal prop every object branch requires, see
4216
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
4217
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
4218
+ * only when the normalized string equals its literal): when they all give the same result it
4219
+ * is used; when they differ, the branches whose result their own validator accepts (default
4220
+ * options) are kept, and the result is used when they agree; else the value is returned
4221
+ * untouched (ambiguous).
4222
+ *
4223
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
4224
+ *
4225
+ * @example
4226
+ * ```ts
4227
+ * // @normalize.trim @normalize.lowercase email: string.email
4228
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
4229
+ * ```
4230
+ */ function normalizeForType(def, value) {
4231
+ const writes = metadataWriteCount();
4232
+ const epoch = currentEpoch();
4233
+ if (writes !== stampWrites || epoch !== stampEpoch) {
4234
+ stampWrites = writes;
4235
+ stampEpoch = epoch;
4236
+ reach = /* @__PURE__ */ new WeakMap();
4237
+ }
4238
+ if (!hasNormalizers(def)) return value;
4239
+ const result = normalize(def, value, 0, /* @__PURE__ */ new Map());
4240
+ return result === NO_MATCH ? value : result;
4241
+ }
4242
+ /** The nodes `def`'s value walk can enter (props, pattern props, items, elements). */ function childrenOf(def) {
4243
+ const type = def.type;
4244
+ switch (type.kind) {
4245
+ case "object": {
4246
+ const t = type;
4247
+ const out = [...t.props.values()];
4248
+ for (const p of t.propsPatterns) out.push(p.def);
4249
+ return out;
4250
+ }
4251
+ case "array": return [type.of];
4252
+ case "union":
4253
+ case "intersection":
4254
+ case "tuple": return type.items;
4255
+ default: return [];
4256
+ }
4257
+ }
4258
+ /**
4259
+ * Whether `def` or a node its walk reaches has normalizers. Answers (and caches) every node
4260
+ * reached, recursive types included: collects the reached nodes with their parents, then marks
4261
+ * the nodes with normalizers and, back along the parents, every node that reaches one.
4262
+ */ function hasNormalizers(def) {
4263
+ const known = reach.get(def);
4264
+ if (known !== void 0) return known;
4265
+ const parents = new Map([[def, []]]);
4266
+ const marked = [];
4267
+ const todo = [def];
4268
+ while (todo.length > 0) {
4269
+ const node = todo.pop();
4270
+ if (flagsOf(node, 0) !== 0) marked.push(node);
4271
+ for (const child of childrenOf(node)) {
4272
+ const cached = reach.get(child);
4273
+ if (cached !== void 0) {
4274
+ if (cached) marked.push(node);
4275
+ continue;
4276
+ }
4277
+ let of = parents.get(child);
4278
+ if (!of) {
4279
+ parents.set(child, of = []);
4280
+ todo.push(child);
3612
4281
  }
4282
+ of.push(node);
3613
4283
  }
3614
- let coerced = input;
3615
- if (propDef) {
3616
- const result = coerce(propDef, input);
3617
- if (result !== NO_MATCH) coerced = result;
4284
+ }
4285
+ for (const node of parents.keys()) reach.set(node, false);
4286
+ while (marked.length > 0) {
4287
+ const node = marked.pop();
4288
+ if (!reach.get(node)) {
4289
+ reach.set(node, true);
4290
+ marked.push(...parents.get(node));
3618
4291
  }
3619
- if (out) out[key] = coerced;
3620
- else if (coerced !== input) {
3621
- out = {};
3622
- for (let j = 0; j < i; j++) out[keys[j]] = value[keys[j]];
3623
- out[key] = coerced;
4292
+ }
4293
+ return reach.get(def);
4294
+ }
4295
+ /** The normalizer flags of `def`, on top of `inherited` (a union's, for its branches). */ function flagsOf(def, inherited) {
4296
+ const meta = def.metadata;
4297
+ if (metaEmpty(meta)) return inherited;
4298
+ let flags = inherited;
4299
+ if (meta.get("normalize.trim")) flags |= TRIM;
4300
+ if (meta.get("normalize.lowercase")) flags |= LOWERCASE;
4301
+ if (meta.get("normalize.uppercase")) flags |= UPPERCASE;
4302
+ return flags;
4303
+ }
4304
+ function applyFlags(value, flags) {
4305
+ let out = value;
4306
+ if (flags & TRIM) out = out.trim();
4307
+ if (flags & LOWERCASE) out = out.toLowerCase();
4308
+ if (flags & UPPERCASE) out = out.toUpperCase();
4309
+ return out;
4310
+ }
4311
+ /**
4312
+ * The normalized value, or NO_MATCH when `def` cannot take it (its kind does not fit the value).
4313
+ * `inherited`: the normalizer flags of the unions / intersections `def` is a member of.
4314
+ *
4315
+ * Objects and unions are memoized per call by input object: a recursive union without a
4316
+ * discriminator is tried for every branch at every level, which without it is exponential in
4317
+ * the depth of the value.
4318
+ */ function normalize(def, value, inherited, memo) {
4319
+ if (value === void 0 || value === null) return value;
4320
+ if (inherited === 0 && !hasNormalizers(def)) return takes(def, value) ? value : NO_MATCH;
4321
+ const type = def.type;
4322
+ switch (type.kind) {
4323
+ case "": {
4324
+ const out = typeof value === "string" && type.designType === "string" ? applyFlags(value, flagsOf(def, inherited)) : value;
4325
+ return takes(def, out) ? out : NO_MATCH;
4326
+ }
4327
+ case "object": {
4328
+ if (!isPlainObject$1(value)) return NO_MATCH;
4329
+ const entries = entriesOf(memo, value);
4330
+ return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, memo));
4331
+ }
4332
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, memo) : NO_MATCH;
4333
+ case "tuple": {
4334
+ const items = type.items;
4335
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, memo) : NO_MATCH;
4336
+ }
4337
+ case "union": {
4338
+ const flags = flagsOf(def, inherited);
4339
+ const items = type.items;
4340
+ if (typeof value !== "object") return normalizeUnion(items, value, flags, memo);
4341
+ const entries = entriesOf(memo, value);
4342
+ return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, memo));
4343
+ }
4344
+ case "intersection": {
4345
+ const flags = flagsOf(def, inherited);
4346
+ let current = value;
4347
+ for (const item of type.items) {
4348
+ const result = normalize(item, current, flags, memo);
4349
+ if (result === NO_MATCH) return NO_MATCH;
4350
+ current = result;
4351
+ }
4352
+ return current;
3624
4353
  }
4354
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
3625
4355
  }
3626
- return out ?? value;
4356
+ }
4357
+ /** The memoized results for input object `value` (see {@link normalize}). */ function entriesOf(memo, value) {
4358
+ let entries = memo.get(value);
4359
+ if (!entries) {
4360
+ entries = [];
4361
+ memo.set(value, entries);
4362
+ }
4363
+ return entries;
4364
+ }
4365
+ /** The memoized result for `type` and `flags`, `undefined` when none. */ function recall(entries, type, flags) {
4366
+ for (const [t, f, result] of entries) if (t === type && f === flags) return result;
4367
+ }
4368
+ /** Memoizes `result` for `type` and `flags` and returns it. */ function remember(entries, type, flags, result) {
4369
+ entries.push([
4370
+ type,
4371
+ flags,
4372
+ result
4373
+ ]);
4374
+ return result;
4375
+ }
4376
+ /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, memo) {
4377
+ if (!hasNormalizers(def)) return input;
4378
+ const result = normalize(def, input, 0, memo);
4379
+ return result === NO_MATCH ? input : result;
3627
4380
  }
3628
4381
  /**
3629
- * Coerces array/tuple items against `of` (arrays) or `items[i]` (tuples).
3630
- * Copy-on-first-change, same as {@link coerceProps}.
3631
- */ function coerceItems(value, of, items) {
3632
- let out;
3633
- for (let i = 0; i < value.length; i++) {
3634
- const input = value[i];
3635
- const result = coerce(of ?? items[i], input);
3636
- const coerced = result === NO_MATCH ? input : result;
3637
- if (out) out.push(coerced);
3638
- else if (coerced !== input) {
3639
- out = value.slice(0, i);
3640
- out.push(coerced);
4382
+ * A prop: as {@link normalizeItem}, but NO_MATCH (the object is not this type) when a literal prop
4383
+ * (`kind: 'cat'`) holds another value.
4384
+ */ function normalizeProp(def, input, memo) {
4385
+ const out = normalizeItem(def, input, memo);
4386
+ if (out === input && def.type.kind === "" && def.type.value !== void 0 && input !== def.type.value && input !== void 0 && input !== null) return NO_MATCH;
4387
+ return out;
4388
+ }
4389
+ /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes(def, value) {
4390
+ const type = def.type;
4391
+ switch (type.kind) {
4392
+ case "": {
4393
+ const final = type;
4394
+ switch (final.designType) {
4395
+ case "string":
4396
+ case "number":
4397
+ case "boolean": return typeof value === final.designType && (final.value === void 0 || value === final.value);
4398
+ case "decimal": return typeof value === "string";
4399
+ case "object": return typeof value === "object";
4400
+ case "any":
4401
+ case "phantom": return true;
4402
+ default: return false;
4403
+ }
3641
4404
  }
4405
+ case "object": return isPlainObject$1(value);
4406
+ case "array": return Array.isArray(value);
4407
+ case "tuple": return Array.isArray(value) && value.length === type.items.length;
4408
+ case "union": return type.items.some((item) => takes(item, value));
4409
+ case "intersection": return type.items.every((item) => takes(item, value));
4410
+ default: return false;
3642
4411
  }
3643
- return out ?? value;
3644
4412
  }
3645
- function isPlainObject$1(value) {
3646
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
3647
- const proto = Object.getPrototypeOf(value);
3648
- return proto === Object.prototype || proto === null;
4413
+ /**
4414
+ * A union: the branch a discriminator names, else the one result every branch that can take
4415
+ * the value agrees on — or, when they differ, the one result of the branches whose validator
4416
+ * accepts their result (NO_MATCH when none can take the value or it stays ambiguous).
4417
+ */ function normalizeUnion(items, value, flags, memo) {
4418
+ if (isPlainObject$1(value)) {
4419
+ const disc = unionDiscriminator(items);
4420
+ if (disc) {
4421
+ const tag = value[disc.property];
4422
+ for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, memo);
4423
+ }
4424
+ }
4425
+ let first = NO_MATCH;
4426
+ let firstItem;
4427
+ let rest;
4428
+ for (const item of items) {
4429
+ const out = normalize(item, value, flags, memo);
4430
+ if (out === NO_MATCH) continue;
4431
+ if (first === NO_MATCH) {
4432
+ first = out;
4433
+ firstItem = item;
4434
+ } else (rest ?? (rest = [])).push([item, out]);
4435
+ }
4436
+ if (!rest || rest.every(([, out]) => sameValue(out, first))) return first;
4437
+ rest.unshift([firstItem, first]);
4438
+ let accepted = NO_MATCH;
4439
+ for (const [item, out] of rest) {
4440
+ if (!branchValidator(item).validate(out, true)) continue;
4441
+ if (accepted === NO_MATCH) accepted = out;
4442
+ else if (!sameValue(accepted, out)) return NO_MATCH;
4443
+ }
4444
+ return accepted;
4445
+ }
4446
+ /**
4447
+ * Each union branch's validator (default options; one error is enough to reject a result),
4448
+ * judging its own normalized result.
4449
+ */ const branchValidators = /* @__PURE__ */ new WeakMap();
4450
+ function branchValidator(def) {
4451
+ let validator = branchValidators.get(def);
4452
+ if (!validator) {
4453
+ validator = new Validator(def, { errorLimit: 1 });
4454
+ branchValidators.set(def, validator);
4455
+ }
4456
+ return validator;
4457
+ }
4458
+ /** Whether two results of the same input are equal (shared, untouched parts are identical). */ function sameValue(a, b) {
4459
+ if (a === b) return true;
4460
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
4461
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
4462
+ const keys = Object.keys(a);
4463
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
4464
+ }
4465
+ return false;
3649
4466
  }
3650
4467
 
3651
4468
  //#endregion
@@ -3708,48 +4525,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3708
4525
 
3709
4526
  //#endregion
3710
4527
  //#region packages/typescript/src/runtime/json-schema.ts
3711
- /**
3712
- * Detects a discriminator property across union items.
3713
- *
3714
- * Scans all items for object-typed members that share a common property
3715
- * with distinct const/literal values. If exactly one such property exists,
3716
- * it is returned as the discriminator. Returns `null` when no qualifying
3717
- * property exists, or when more than one does (ambiguous).
3718
- */ function detectDiscriminator(items) {
3719
- if (items.length < 2) return null;
3720
- for (const item of items) if (item.type.kind !== "object") return null;
3721
- const firstObj = items[0].type;
3722
- const candidates = [];
3723
- for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
3724
- let result = null;
3725
- for (const candidate of candidates) {
3726
- const values = /* @__PURE__ */ new Set();
3727
- const indexMapping = {};
3728
- let valid = true;
3729
- for (let i = 0; i < items.length; i++) {
3730
- const prop = items[i].type.props.get(candidate);
3731
- if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
3732
- valid = false;
3733
- break;
3734
- }
3735
- const val = prop.type.value;
3736
- if (values.has(val)) {
3737
- valid = false;
3738
- break;
3739
- }
3740
- values.add(val);
3741
- indexMapping[String(val)] = i;
3742
- }
3743
- if (valid) {
3744
- if (result) return null;
3745
- result = {
3746
- propertyName: candidate,
3747
- indexMapping
3748
- };
3749
- }
3750
- }
3751
- return result;
3752
- }
4528
+ /** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
3753
4529
  /**
3754
4530
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
3755
4531
  *
@@ -3765,8 +4541,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3765
4541
  * ```
3766
4542
  *
3767
4543
  * @param type - The annotated type to convert.
4544
+ * @param opts - {@link TJsonSchemaOptions}.
3768
4545
  * @returns A JSON Schema object.
3769
- */ function buildJsonSchema(type) {
4546
+ */ function buildJsonSchema(type, opts) {
4547
+ const closed = opts?.closed === true;
4548
+ const annotations = opts?.annotations !== false;
4549
+ const enums = opts?.enums !== false;
3770
4550
  /**
3771
4551
  * `$defs` entries by type def (identity): named objects (always extracted) and types found
3772
4552
  * recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
@@ -3794,8 +4574,35 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3794
4574
  ...schema,
3795
4575
  type: [schema.type, "null"]
3796
4576
  };
3797
- if (Object.keys(schema).length === 1 && Array.isArray(schema.anyOf)) return { anyOf: [...schema.anyOf, { type: "null" }] };
3798
- return { anyOf: [schema, { type: "null" }] };
4577
+ const notes = {};
4578
+ let body = schema;
4579
+ for (const [, keyword] of ANNOTATION_KEYWORDS) if (body[keyword] !== void 0) {
4580
+ if (body === schema) body = { ...schema };
4581
+ notes[keyword] = body[keyword];
4582
+ delete body[keyword];
4583
+ }
4584
+ if (body !== schema && Object.keys(body).length === 1 && body.allOf?.length === 1) body = body.allOf[0];
4585
+ if (Object.keys(body).length === 1 && Array.isArray(body.anyOf)) return {
4586
+ anyOf: [...body.anyOf, { type: "null" }],
4587
+ ...notes
4588
+ };
4589
+ return {
4590
+ anyOf: [body, { type: "null" }],
4591
+ ...notes
4592
+ };
4593
+ };
4594
+ /**
4595
+ * A use of a `$defs` entry: `schema` (its `$ref`) with what the use adds to the entry (built
4596
+ * from `own`, see `ownDef`): its key counts, and its title / description when they differ
4597
+ * from the entry's — beside the reference, in an `allOf`.
4598
+ */ const useOf = (schema, def, own, keyCounts = false) => {
4599
+ const extra = {};
4600
+ if (annotations) applyAnnotationKeywords(extra, def.metadata, own?.metadata);
4601
+ if (keyCounts) applyKeyCounts(extra, def.metadata);
4602
+ return Object.keys(extra).length > 0 ? {
4603
+ allOf: [schema],
4604
+ ...extra
4605
+ } : schema;
3799
4606
  };
3800
4607
  /**
3801
4608
  * Non-primitive type defs being built: `true` once re-entered (recursive). A named object
@@ -3832,7 +4639,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3832
4639
  * A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
3833
4640
  * them instead, its recursion referring to the shared definition.
3834
4641
  */ function* refTo(typeDef, def, own) {
3835
- if (def === own || inlining.has(def) || sameConstraints(def, own)) return ref(typeDef);
4642
+ if (def === own || inlining.has(def) || sameConstraints(def, own)) return useOf(ref(typeDef), def, own);
3836
4643
  inlining.add(def);
3837
4644
  const schema = yield buildDef(def);
3838
4645
  inlining.delete(def);
@@ -3862,6 +4669,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3862
4669
  for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
3863
4670
  schema.patternProperties = patternProperties(built, Object.keys(properties));
3864
4671
  }
4672
+ if (closed) schema.additionalProperties = false;
3865
4673
  return schema;
3866
4674
  }
3867
4675
  /** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
@@ -3871,14 +4679,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3871
4679
  const atRoot = def === type && !rootEntered;
3872
4680
  rootEntered = true;
3873
4681
  if (def.id && typeDef.kind === "object" && !atRoot) {
4682
+ const own = annotations ? ownDef(def, type) ?? def : void 0;
3874
4683
  if (!defs.has(typeDef)) {
3875
4684
  reserve(typeDef, def.id, true);
3876
4685
  const outer = building;
3877
4686
  building = /* @__PURE__ */ new Map();
3878
- defs.get(typeDef).schema = yield buildObject(def);
4687
+ const entry = yield buildObject(def);
4688
+ if (own) applyAnnotationKeywords(entry, own.metadata);
4689
+ defs.get(typeDef).schema = entry;
3879
4690
  building = outer;
3880
4691
  }
3881
- return ref(typeDef);
4692
+ return useOf(ref(typeDef), def, own, true);
3882
4693
  }
3883
4694
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
3884
4695
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -3907,7 +4718,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3907
4718
  const own = ownOf(def);
3908
4719
  const same = def === own || sameConstraints(def, own);
3909
4720
  defs.get(typeDef).schema = same ? schema : yield buildDef(own);
3910
- return def === type || !same ? schema : ref(typeDef);
4721
+ return def === type || !same ? schema : useOf(ref(typeDef), def, own);
3911
4722
  }
3912
4723
  /** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
3913
4724
  const ownOf = (def) => {
@@ -3918,7 +4729,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3918
4729
  }
3919
4730
  return own;
3920
4731
  };
3921
- /** The schema of `def`'s own type (see {@link build}). */ function* buildDef(def) {
4732
+ /** The schema of `def`'s own type (see {@link build}), with its title / description. */ function* buildDef(def) {
4733
+ const schema = yield buildBody(def);
4734
+ if (annotations) applyAnnotationKeywords(schema, def.metadata);
4735
+ return schema;
4736
+ }
4737
+ /** The schema of `def`'s own type, without its title / description (see {@link buildDef}). */ function* buildBody(def) {
3922
4738
  const meta = def.metadata;
3923
4739
  const all = function* (items) {
3924
4740
  const out = [];
@@ -3926,7 +4742,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3926
4742
  return out;
3927
4743
  };
3928
4744
  const kind = def.type.kind;
3929
- if (kind === "object") return yield buildObject(def);
4745
+ if (kind === "object") {
4746
+ const schema = yield buildObject(def);
4747
+ applyKeyCounts(schema, meta);
4748
+ return schema;
4749
+ }
3930
4750
  if (kind === "array") {
3931
4751
  const d = def;
3932
4752
  const schema = {
@@ -3948,6 +4768,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3948
4768
  maxItems: items.length
3949
4769
  };
3950
4770
  const disc = detectDiscriminator(items);
4771
+ let schema;
3951
4772
  if (disc) {
3952
4773
  const mapping = {};
3953
4774
  for (const [val, idx] of Object.entries(disc.indexMapping)) {
@@ -3959,16 +4780,19 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3959
4780
  ]);
3960
4781
  else mapping[val] = `#/oneOf/${idx}`;
3961
4782
  }
3962
- return {
4783
+ schema = {
3963
4784
  oneOf: built,
3964
4785
  discriminator: {
3965
4786
  propertyName: disc.propertyName,
3966
4787
  mapping
3967
4788
  }
3968
4789
  };
4790
+ } else {
4791
+ if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
4792
+ schema = enums && enumOf(built, refSchemas) || { anyOf: built };
3969
4793
  }
3970
- if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
3971
- return { anyOf: built };
4794
+ applyKeyCounts(schema, meta);
4795
+ return schema;
3972
4796
  }
3973
4797
  return forAnnotatedType(def, {
3974
4798
  phantom() {
@@ -4209,6 +5033,51 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4209
5033
  const maxLength = meta.get("expect.maxLength");
4210
5034
  if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
4211
5035
  }
5036
+ /**
5037
+ * `@expect.minKeys` / `maxKeys` → `minProperties` / `maxProperties` (they constrain objects
5038
+ * only, so they also sit on a union's schema as they are).
5039
+ */ function applyKeyCounts(schema, meta) {
5040
+ const minKeys = meta.get("expect.minKeys");
5041
+ if (minKeys !== void 0) schema.minProperties = boundOf(minKeys, "count");
5042
+ const maxKeys = meta.get("expect.maxKeys");
5043
+ if (maxKeys !== void 0) schema.maxProperties = boundOf(maxKeys, "count");
5044
+ }
5045
+ /** `@meta.label` → `title`, `@meta.description` → `description` (see `annotations`). */ function applyAnnotationKeywords(schema, meta, except) {
5046
+ if (metaEmpty(meta)) return;
5047
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) {
5048
+ const value = meta.get(key);
5049
+ if (value !== void 0 && value !== except?.get(key)) schema[keyword] = value;
5050
+ }
5051
+ }
5052
+ /**
5053
+ * The `{ type, enum }` schema of a union whose members are all literals (`const`, a nested
5054
+ * union of literals' `enum`, or `null`), at least one of them not `null`; `undefined` for any
5055
+ * other union (a member with other keywords — a title, a constraint — keeps the `anyOf`).
5056
+ */ function enumOf(members, refs) {
5057
+ const values = [];
5058
+ const types = [];
5059
+ let literal = false;
5060
+ for (const member of members) {
5061
+ if (refs.has(member)) return;
5062
+ const keys = Object.keys(member);
5063
+ let memberValues;
5064
+ if ("const" in member && keys.every((k) => k === "const" || k === "type")) {
5065
+ memberValues = [member.const];
5066
+ literal = true;
5067
+ } else if (Array.isArray(member.enum) && keys.every((k) => k === "enum" || k === "type")) {
5068
+ memberValues = member.enum;
5069
+ literal = true;
5070
+ } else if (member.type === "null" && keys.length === 1) memberValues = [null];
5071
+ else return;
5072
+ for (const value of memberValues) if (!values.includes(value)) values.push(value);
5073
+ for (const t of [member.type ?? []].flat()) if (!types.includes(t)) types.push(t);
5074
+ }
5075
+ if (!literal) return;
5076
+ const schema = {};
5077
+ if (types.length > 0) schema.type = types.length === 1 ? types[0] : types;
5078
+ schema.enum = values;
5079
+ return schema;
5080
+ }
4212
5081
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
4213
5082
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
4214
5083
  if (schema.type === "string") {
@@ -4261,7 +5130,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4261
5130
  applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
4262
5131
  continue;
4263
5132
  }
4264
- if (member.const !== void 0) continue;
5133
+ if (member.const !== void 0 || member.enum !== void 0) continue;
4265
5134
  const type = member.type;
4266
5135
  const extra = { type };
4267
5136
  if (type === "array") {
@@ -4304,7 +5173,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4304
5173
  */ function fromJsonSchema(schema) {
4305
5174
  const defsSource = schema.$defs || schema.definitions || {};
4306
5175
  const resolved = /* @__PURE__ */ new Map();
4307
- const convert = (s) => {
5176
+ /** `title` → `@meta.label`, `description` → `@meta.description` (not on a shared `$ref`). */ const convert = (s) => {
5177
+ const type = convertNode(s);
5178
+ if (s && !s.$ref) {
5179
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) if (typeof s[keyword] === "string") annotate(type.metadata, key, s[keyword]);
5180
+ }
5181
+ return type;
5182
+ };
5183
+ const convertNode = (s) => {
4308
5184
  if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
4309
5185
  if (s.$ref) {
4310
5186
  const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
@@ -4350,7 +5226,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4350
5226
  const handle = defineAnnotatedType("union");
4351
5227
  for (const t of s.type) handle.item(convert({
4352
5228
  ...s,
4353
- type: t
5229
+ type: t,
5230
+ title: void 0,
5231
+ description: void 0
4354
5232
  }));
4355
5233
  return handle.$type;
4356
5234
  }
@@ -4364,6 +5242,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4364
5242
  handle.prop(key, propType);
4365
5243
  }
4366
5244
  for (const [pattern, propSchema] of Object.entries(s.patternProperties ?? {})) handle.propPattern(compilePattern(pattern), convert(propSchema));
5245
+ if (typeof s.minProperties === "number") handle.annotate("expect.minKeys", { count: s.minProperties });
5246
+ if (typeof s.maxProperties === "number") handle.annotate("expect.maxKeys", { count: s.maxProperties });
4367
5247
  return handle.$type;
4368
5248
  }
4369
5249
  if (s.type === "array") {
@@ -4446,14 +5326,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4446
5326
  * to it are renamed.
4447
5327
  *
4448
5328
  * @param types - Array of annotated types, each with an `id`.
5329
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
4449
5330
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
4450
- */ function mergeJsonSchemas(types) {
5331
+ */ function mergeJsonSchemas(types, opts) {
4451
5332
  const mergedDefs = {};
4452
5333
  const schemas = {};
4453
5334
  for (const type of types) {
4454
5335
  const name = type.id;
4455
5336
  if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
4456
- const { $defs: defs, ...schema } = buildJsonSchema(type);
5337
+ const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
4457
5338
  if (!defs) {
4458
5339
  schemas[name] = schema;
4459
5340
  continue;
@@ -4528,27 +5409,31 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4528
5409
  }
4529
5410
  if (mode === "db") {
4530
5411
  const dbValue = prop.metadata.get("db.default");
4531
- if (dbValue !== void 0) {
4532
- const parsed = parseRawValue(dbValue, prop);
4533
- if (parsed !== void 0 && prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
4534
- return;
4535
- }
5412
+ if (dbValue !== void 0) return validRawValue(dbValue, prop);
4536
5413
  if (prop.metadata.has("db.default.increment")) return { value: "increment" };
4537
5414
  if (prop.metadata.has("db.default.uuid")) return { value: "uuid" };
4538
5415
  if (prop.metadata.has("db.default.now")) return { value: "now" };
4539
5416
  return;
4540
5417
  }
4541
5418
  const metaKey = mode === "default" ? "meta.default" : "meta.example";
4542
- const rawStr = prop.metadata.get(metaKey);
4543
- if (rawStr === void 0) return;
4544
- const parsed = parseRawValue(rawStr, prop);
4545
- if (parsed === void 0) return;
4546
- if (prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
5419
+ const metaValue = prop.metadata.get(metaKey);
5420
+ if (metaValue === void 0) return;
5421
+ return validRawValue(metaValue, prop);
5422
+ }
5423
+ /**
5424
+ * An annotation's raw value as a valid value of `prop` (see {@link parseRawValue}); a string the
5425
+ * JSON reading does not fit is tried as the string itself (a `decimal` field, `decimal | null`).
5426
+ */ function validRawValue(raw, prop) {
5427
+ const validator = prop.validator({ unknownProps: "ignore" });
5428
+ const parsed = parseRawValue(raw, prop);
5429
+ if (parsed !== void 0 && validator.validate(parsed, true)) return { value: parsed };
5430
+ if (typeof raw === "string" && parsed !== raw && validator.validate(raw, true)) return { value: raw };
4547
5431
  }
4548
5432
  /**
4549
- * Parses a raw annotation string into a JS value.
4550
- * Strings are returned as-is for string types; everything else goes through JSON.parse.
5433
+ * Parses a raw annotation value into a JS value: a number / boolean literal (a `value`
5434
+ * argument) as it is; a string as-is for string types, else through JSON.parse.
4551
5435
  */ function parseRawValue(raw, prop) {
5436
+ if (typeof raw !== "string") return raw;
4552
5437
  if (prop.type.kind === "" && prop.type.designType === "string") return raw;
4553
5438
  try {
4554
5439
  return JSON.parse(raw);
@@ -4563,7 +5448,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4563
5448
  case "number": return 0;
4564
5449
  case "boolean": return false;
4565
5450
  case "undefined": return;
4566
- case "null": return null;
5451
+ case "null":
5452
+ case "any": return null;
4567
5453
  default: return;
4568
5454
  }
4569
5455
  }
@@ -4661,7 +5547,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4661
5547
  const items = [];
4662
5548
  for (const item of type.items) items.push(yield build(item, path, mode, walk));
4663
5549
  if (items.some(stops)) return STOPPED;
4664
- const values = items.filter((item) => item !== STOPPED);
5550
+ const isAny = (i) => {
5551
+ const t = type.items[i].type;
5552
+ return t.kind === "" && t.designType === "any";
5553
+ };
5554
+ const kept = items.filter((item, i) => item !== STOPPED && !isAny(i));
5555
+ const values = kept.length > 0 ? kept : items.filter((item) => item !== STOPPED);
4665
5556
  return values.length > 0 && values.every(isPlainObject) ? Object.assign({}, ...values) : values[0];
4666
5557
  }
4667
5558
  default: throw new Error(`Unknown type kind "${type.kind}"`);
@@ -4692,12 +5583,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4692
5583
  /**
4693
5584
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
4694
5585
  * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
4695
- * (`static toJsonSchema()`).
4696
- */ function lazyJsonSchema(type) {
5586
+ * (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
5587
+ * of a type).
5588
+ */ function lazyJsonSchema(type, opts) {
4697
5589
  const known = lazy.get(type);
4698
5590
  const writes = metadataWriteCount();
4699
5591
  if (known?.writes === writes) return known.schema;
4700
- const schema = buildJsonSchema(type);
5592
+ const schema = buildJsonSchema(type, opts);
4701
5593
  lazy.set(type, {
4702
5594
  writes,
4703
5595
  schema
@@ -4709,14 +5601,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4709
5601
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
4710
5602
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
4711
5603
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
4712
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
4713
- */ function bundledSchemaOf(type, literal, modules = []) {
5604
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
5605
+ * `jsonSchemaOptions` of the build (the literal was built with them).
5606
+ */ function bundledSchemaOf(type, literal, modules = [], opts) {
4714
5607
  const applied = appliedBlockModules();
4715
5608
  const known = bundled.get(type);
4716
5609
  if (known?.size === applied.size) return known.schema;
4717
5610
  const accounted = new Set(modules);
4718
5611
  const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
4719
- const schema = same ? literal() : buildJsonSchema(type);
5612
+ const schema = same ? literal() : buildJsonSchema(type, opts);
4720
5613
  bundled.set(type, {
4721
5614
  size: applied.size,
4722
5615
  schema,
@@ -4859,7 +5752,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4859
5752
 
4860
5753
  //#endregion
4861
5754
  //#region packages/typescript/src/runtime/serialize.ts
4862
- function _define_property$2(obj, key, value) {
5755
+ function _define_property$3(obj, key, value) {
4863
5756
  if (key in obj) Object.defineProperty(obj, key, {
4864
5757
  value,
4865
5758
  enumerable: true,
@@ -4931,17 +5824,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4931
5824
  return id;
4932
5825
  }
4933
5826
  constructor() {
4934
- _define_property$2(this, "own", /* @__PURE__ */ new Map());
5827
+ _define_property$3(this, "own", /* @__PURE__ */ new Map());
4935
5828
  /**
4936
5829
  * The nodes without an id met more than once (see `indexPayload`): serialized once, with a
4937
5830
  * payload id, and referenced (`$ref`, `anon`) wherever else they are.
4938
- */ _define_property$2(this, "repeated", /* @__PURE__ */ new Set());
4939
- _define_property$2(this, "firstKeys", /* @__PURE__ */ new Map());
4940
- _define_property$2(this, "identities", /* @__PURE__ */ new WeakMap());
4941
- _define_property$2(this, "nextId", 0);
4942
- /** Payload ids by type def (see {@link keyOf}). */ _define_property$2(this, "keys", /* @__PURE__ */ new WeakMap());
4943
- /** The payload ids given so far. */ _define_property$2(this, "taken", /* @__PURE__ */ new Set());
4944
- /** The `cut` payload of defs (see `indexPayload`). */ _define_property$2(this, "cutKeys", /* @__PURE__ */ new WeakMap());
5831
+ */ _define_property$3(this, "repeated", /* @__PURE__ */ new Set());
5832
+ _define_property$3(this, "firstKeys", /* @__PURE__ */ new Map());
5833
+ _define_property$3(this, "identities", /* @__PURE__ */ new WeakMap());
5834
+ _define_property$3(this, "nextId", 0);
5835
+ /** Payload ids by type def (see {@link keyOf}). */ _define_property$3(this, "keys", /* @__PURE__ */ new WeakMap());
5836
+ /** The payload ids given so far. */ _define_property$3(this, "taken", /* @__PURE__ */ new Set());
5837
+ /** The `cut` payload of defs (see `indexPayload`). */ _define_property$3(this, "cutKeys", /* @__PURE__ */ new WeakMap());
4945
5838
  }
4946
5839
  };
4947
5840
  /**
@@ -5398,6 +6291,306 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5398
6291
  }
5399
6292
  }
5400
6293
 
6294
+ //#endregion
6295
+ //#region packages/typescript/src/runtime/user-text.ts
6296
+ /**
6297
+ * The annotations holding user-facing text (labels, descriptions, error messages): the arguments
6298
+ * their specs flag `userText`. Core's are known from the start ({@link CORE_USER_TEXT}); a plugin's
6299
+ * are registered by the generated modules that write them (`$ut`), or by the plugin itself
6300
+ * ({@link registerUserText}), so a translator finds them at runtime without the specs.
6301
+ */ /**
6302
+ * `true`: the value itself is the text; `'expression'`: the value is the source of a function the
6303
+ * client evaluates, its string literals the texts; a list: those fields of the value object are
6304
+ * (a name ending in `()`: that field is an expression).
6305
+ */ /**
6306
+ * The user-facing text of `@atscript/core`'s annotations (its specs' `userText` arguments; a test
6307
+ * keeps them equal).
6308
+ */ const CORE_USER_TEXT = new Map([
6309
+ ["meta.label", true],
6310
+ ["meta.description", true],
6311
+ ["meta.required", ["message"]],
6312
+ ["expect.minLength", ["message"]],
6313
+ ["expect.maxLength", ["message"]],
6314
+ ["expect.min", ["message"]],
6315
+ ["expect.max", ["message"]],
6316
+ ["expect.exclusiveMin", ["message"]],
6317
+ ["expect.exclusiveMax", ["message"]],
6318
+ ["expect.int", ["message"]],
6319
+ ["expect.minKeys", ["message"]],
6320
+ ["expect.maxKeys", ["message"]],
6321
+ ["expect.message", true],
6322
+ ["expect.pattern", ["message"]],
6323
+ ["expect.array.uniqueItems", ["message"]],
6324
+ ["expect.array.key", ["message"]]
6325
+ ]);
6326
+ const USER_TEXT = new Map(CORE_USER_TEXT);
6327
+ /**
6328
+ * Registers metadata key `key` as holding user-facing text (see {@link TUserTextFields}; `true` by
6329
+ * default). Fields add up across calls; a whole-value kind replaces a field list, and an
6330
+ * expression wins over text (`name()` over `name`), whatever the order of the calls.
6331
+ * For plugins that write such metadata at runtime; generated modules register what they write.
6332
+ */ function registerUserText(key, fields = true) {
6333
+ const known = USER_TEXT.get(key);
6334
+ if (known === "expression" || known === true && typeof fields === "object") return;
6335
+ if (typeof fields !== "object") {
6336
+ USER_TEXT.set(key, fields);
6337
+ return;
6338
+ }
6339
+ const all = new Set([...typeof known === "object" ? known : [], ...fields]);
6340
+ USER_TEXT.set(key, [...all].filter((f) => !all.has(`${f}()`)));
6341
+ }
6342
+ /**
6343
+ * Registers user-text keys written by a generated module (see {@link registerUserText}): `key` —
6344
+ * the value itself; `key()` — the value is an expression; `key:field` — that field of the value
6345
+ * object; `key:field()` — that field is an expression.
6346
+ */ function $ut(...entries) {
6347
+ for (const entry of entries) {
6348
+ const at = entry.indexOf(":");
6349
+ if (at !== -1) registerUserText(entry.slice(0, at), [entry.slice(at + 1)]);
6350
+ else if (entry.endsWith("()")) registerUserText(entry.slice(0, -2), "expression");
6351
+ else registerUserText(entry);
6352
+ }
6353
+ }
6354
+ /**
6355
+ * Where metadata key `key` holds user-facing text (see {@link TUserTextFields}; for a `multiple`
6356
+ * annotation, each item of its list), `undefined` when it holds none. Core keys are known from the
6357
+ * start; a plugin's once a module writing them is loaded (or the plugin registered them).
6358
+ */ function userTextOf(key) {
6359
+ return USER_TEXT.get(key);
6360
+ }
6361
+ /** Every metadata key holding user-facing text known so far (see {@link userTextOf}). */ function userTextKeys() {
6362
+ return USER_TEXT;
6363
+ }
6364
+
6365
+ //#endregion
6366
+ //#region packages/typescript/src/runtime/translate-served.ts
6367
+ /**
6368
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
6369
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
6370
+ * collected for the client.
6371
+ */ function _define_property$2(obj, key, value) {
6372
+ if (key in obj) Object.defineProperty(obj, key, {
6373
+ value,
6374
+ enumerable: true,
6375
+ configurable: true,
6376
+ writable: true
6377
+ });
6378
+ else obj[key] = value;
6379
+ return obj;
6380
+ }
6381
+ /**
6382
+ * Translates the user-facing text of serialized annotated types (the output of
6383
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
6384
+ * found at any depth is read with {@link userTextOf}:
6385
+ *
6386
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
6387
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
6388
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
6389
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
6390
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
6391
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
6392
+ * translates the expressions' results by exact match.
6393
+ *
6394
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
6395
+ * result shares every part with no translated text, and is `json` itself when nothing was
6396
+ * translated.
6397
+ *
6398
+ * @example
6399
+ * ```ts
6400
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
6401
+ * i18n.exists(text) ? i18n.t(text) : undefined
6402
+ * )
6403
+ * ```
6404
+ */ function translateServed(json, t) {
6405
+ const texts = {};
6406
+ return {
6407
+ value: walk(json, void 0, {
6408
+ t,
6409
+ texts
6410
+ }),
6411
+ texts
6412
+ };
6413
+ }
6414
+ /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
6415
+ if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
6416
+ if (typeof value === "string") {
6417
+ if (mode === "expression") collectLiterals(value, ctx);
6418
+ else if (mode === true && formatCodeOf(value) === void 0) return translate(value, ctx) ?? value;
6419
+ return value;
6420
+ }
6421
+ if (typeof value !== "object" || value === null) return value;
6422
+ return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
6423
+ }
6424
+ /**
6425
+ * The mode of the value at `key` of an object of `mode`: a metadata key's user text, a field of a
6426
+ * value object's, else `metadata` objects only (a non-string text value — a `ref` target — has
6427
+ * metadata).
6428
+ */ function modeOf(key, mode) {
6429
+ if (typeof mode === "object") return mode.includes(`${key}()`) ? "expression" : mode.includes(key) || void 0;
6430
+ return mode === "metadata" && userTextOf(key) || (key === "metadata" ? "metadata" : void 0);
6431
+ }
6432
+ /** `t(text)` when it is a string (a plain-object dictionary also has `constructor`, …). */ function translate(text, ctx) {
6433
+ const out = ctx.t(text);
6434
+ return typeof out === "string" ? out : void 0;
6435
+ }
6436
+ /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
6437
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
6438
+ const translated = translate(literal, ctx);
6439
+ if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
6440
+ }
6441
+ }
6442
+ /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
6443
+ "n": "\n",
6444
+ "t": " ",
6445
+ "r": "\r",
6446
+ "b": "\b",
6447
+ "f": "\f",
6448
+ "v": "\v",
6449
+ "0": "\0",
6450
+ "\n": "",
6451
+ "\r": "",
6452
+ "\r\n": ""
6453
+ };
6454
+ /** 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;
6455
+ /** The string a literal's raw text (between its quotes) evaluates to. */ function decode(raw) {
6456
+ return raw.includes("\\") ? raw.replace(ESCAPE, (_, c) => {
6457
+ if (c.length < 3) return Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : c;
6458
+ const code = Number.parseInt(c.replace(/[ux{}]/g, ""), 16);
6459
+ return code > 1114111 ? "" : String.fromCodePoint(code);
6460
+ }) : raw;
6461
+ }
6462
+ /** A character of an identifier or a number. */ const IDENT = RegExp("[\\p{ID_Continue}$]", "u");
6463
+ /** A run of {@link IDENT} characters at `lastIndex`. */ const IDENT_RUN = RegExp("[\\p{ID_Continue}$]+", "uy");
6464
+ /** Keywords whose `(…)` a statement follows: a `/` after the `)` starts a regular expression. */ const CONTROL = new Set([
6465
+ "if",
6466
+ "while",
6467
+ "for",
6468
+ "with"
6469
+ ]);
6470
+ /** Keywords after which `/` starts a regular expression rather than a division. */ const REGEX_AFTER_WORD = new Set([
6471
+ "return",
6472
+ "typeof",
6473
+ "instanceof",
6474
+ "in",
6475
+ "of",
6476
+ "new",
6477
+ "delete",
6478
+ "void",
6479
+ "throw",
6480
+ "case",
6481
+ "do",
6482
+ "else",
6483
+ "yield",
6484
+ "await"
6485
+ ]);
6486
+ let LiteralScanner = class LiteralScanner {
6487
+ /** Scans code up to the end, or to the `}` closing a template's `${`. */ code() {
6488
+ const src = this.src;
6489
+ while (this.i < src.length) {
6490
+ const c = src[this.i];
6491
+ if (c === "/" && src[this.i + 1] === "/") {
6492
+ const end = src.indexOf("\n", this.i);
6493
+ this.i = end === -1 ? src.length : end;
6494
+ } else if (c === "/" && src[this.i + 1] === "*") {
6495
+ const end = src.indexOf("*/", this.i + 2);
6496
+ this.i = end === -1 ? src.length : end + 2;
6497
+ } else if (c === "'" || c === "\"" || c === "`") {
6498
+ const text = this.literal(c);
6499
+ if (text !== void 0 && text.trim() !== "") this.out.add(text);
6500
+ this.regexOk = false;
6501
+ } else if (c === "/" && this.regexOk) {
6502
+ this.regex();
6503
+ this.regexOk = false;
6504
+ } else if (IDENT.test(c)) this.word();
6505
+ else if ((c === "+" || c === "-") && src[this.i + 1] === c) {
6506
+ this.i += 2;
6507
+ this.regexOk = false;
6508
+ } else {
6509
+ this.i++;
6510
+ if (/\s/.test(c)) continue;
6511
+ if (c === "(" || c === "{") this.open.push(c === "(" ? "p" : c);
6512
+ else if (c === ")" || c === "}") {
6513
+ const top = this.open.pop();
6514
+ if (top === "$") return;
6515
+ this.regexOk = top === "c";
6516
+ continue;
6517
+ }
6518
+ this.regexOk = c !== "]";
6519
+ }
6520
+ }
6521
+ }
6522
+ /** An identifier, keyword or number at `i`; `i` past it (and past a control keyword's `(`). */ word() {
6523
+ const src = this.src;
6524
+ IDENT_RUN.lastIndex = this.i;
6525
+ IDENT_RUN.test(src);
6526
+ const word = src.slice(this.i, IDENT_RUN.lastIndex);
6527
+ this.i = IDENT_RUN.lastIndex;
6528
+ this.regexOk = REGEX_AFTER_WORD.has(word);
6529
+ if (CONTROL.has(word)) {
6530
+ while (/\s/.test(src[this.i] ?? "")) this.i++;
6531
+ if (src[this.i] === "(") {
6532
+ this.i++;
6533
+ this.open.push("c");
6534
+ this.regexOk = true;
6535
+ }
6536
+ }
6537
+ }
6538
+ /**
6539
+ * A `'…'` / `"…"` / `` `…` `` literal at `i`, decoded (`undefined`: a template with `${…}`, whose
6540
+ * code is scanned); `i` past it.
6541
+ */ literal(quote) {
6542
+ const src = this.src;
6543
+ const start = ++this.i;
6544
+ let plain = true;
6545
+ while (this.i < src.length && src[this.i] !== quote) if (src[this.i] === "\\") this.i += src.startsWith("\r\n", this.i + 1) ? 3 : 2;
6546
+ else if (quote === "`" && src.startsWith("${", this.i)) {
6547
+ plain = false;
6548
+ this.i += 2;
6549
+ this.open.push("$");
6550
+ this.code();
6551
+ } else this.i++;
6552
+ const end = this.i++;
6553
+ return plain ? decode(src.slice(start, end)) : void 0;
6554
+ }
6555
+ /** A regular expression literal starting at `i`; `i` past its flags. */ regex() {
6556
+ const src = this.src;
6557
+ let inClass = false;
6558
+ this.i++;
6559
+ while (this.i < src.length && src[this.i] !== "\n") {
6560
+ const c = src[this.i++];
6561
+ if (c === "\\") this.i++;
6562
+ else if (c === "[") inClass = true;
6563
+ else if (c === "]") inClass = false;
6564
+ else if (c === "/" && !inClass) break;
6565
+ }
6566
+ while (this.i < src.length && /[a-z]/i.test(src[this.i])) this.i++;
6567
+ }
6568
+ constructor(src, out) {
6569
+ _define_property$2(this, "src", void 0);
6570
+ _define_property$2(this, "out", void 0);
6571
+ _define_property$2(this, "i", void 0);
6572
+ /** A `/` here starts a regular expression (no operand just ended), not a division. */ _define_property$2(this, "regexOk", void 0);
6573
+ /**
6574
+ * The open brackets: `c` — the `(` of an `if` / `while` / `for` / `with` (a `/` after its `)` is
6575
+ * a regex); `p` — another `(`; `{`; `$` — a template's `${`.
6576
+ */ _define_property$2(this, "open", void 0);
6577
+ this.src = src;
6578
+ this.out = out;
6579
+ this.i = 0;
6580
+ this.regexOk = true;
6581
+ this.open = [];
6582
+ }
6583
+ };
6584
+ /**
6585
+ * The string literals of JavaScript `source`, as the strings they evaluate to: `'…'`, `"…"` and
6586
+ * `` `…` `` templates without `${…}` (the literals inside a `${…}` count). Comments and regular
6587
+ * expression literals are skipped; empty and blank literals are left out.
6588
+ */ function stringLiterals(source) {
6589
+ const out = /* @__PURE__ */ new Set();
6590
+ new LiteralScanner(source, out).code();
6591
+ return [...out];
6592
+ }
6593
+
5401
6594
  //#endregion
5402
6595
  //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
5403
6596
  /**
@@ -5559,7 +6752,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5559
6752
  body.push(...this.extra);
5560
6753
  const root = this.layout[1];
5561
6754
  const rootDef = root[2] >= 0 ? this.defs[root[2]][0] : -1;
5562
- if (root[0] === 0 && this.fn[root[2]] && (rootDef === D_OBJECT || rootDef === D_OBJECT_PATTERNS || rootDef === D_TUPLE || rootDef === D_INTERSECTION)) body.push(`return d${root[2]}`);
6755
+ if (root[0] === 0 && (root[1] & OBJECT_BITS) === 0 && this.fn[root[2]] && (rootDef === D_OBJECT || rootDef === D_OBJECT_PATTERNS || rootDef === D_TUPLE || rootDef === D_INTERSECTION)) body.push(`return d${root[2]}`);
5563
6756
  else {
5564
6757
  body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
5565
6758
  body.push("return r");
@@ -5815,7 +7008,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5815
7008
  def(d, mask, shape, at, x, ctx) {
5816
7009
  const def = this.defs[d];
5817
7010
  const kind = def[0];
5818
- if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) return this.call(`d${d}`, x, ctx);
7011
+ if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) {
7012
+ if (kind === D_OBJECT && (mask & OBJECT_BITS) !== 0) {
7013
+ const ks = keySlots(mask, shape, at);
7014
+ return [...this.call(`d${d}`, x, ctx), ...this.keyCountChecks(ks, x, ctx.fail, def)];
7015
+ }
7016
+ return this.call(`d${d}`, x, ctx);
7017
+ }
5819
7018
  switch (kind) {
5820
7019
  case D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
5821
7020
  case D_ARRAY: return [
@@ -5857,7 +7056,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5857
7056
  if (mask & B_REQUIRED) conds.push(`${x} !== true`);
5858
7057
  return [`if (${conds.join(" || ")}) ${fail}`];
5859
7058
  }
5860
- case "any": return [];
7059
+ case "any": return [`if (${x} === undefined) ${fail}`];
5861
7060
  case "never": return [fail];
5862
7061
  case "undefined": return [`if (${x} !== undefined) ${fail}`];
5863
7062
  case "null": return [`if (${x} !== null) ${fail}`];
@@ -5890,6 +7089,37 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5890
7089
  if (mask & B_UNIQUE) lines.push("return 2");
5891
7090
  return lines;
5892
7091
  }
7092
+ /**
7093
+ * `@expect.minKeys` / `maxKeys` of object `x` matched as object def `def`: the keys the result
7094
+ * keeps (with `unknownProps: 'strip'` the declared ones, else every own key: with 'error' the
7095
+ * def already failed an object with an unknown key).
7096
+ */ keyCountChecks(ks, x, fail, def) {
7097
+ if (ks.minKeys < 0 && ks.maxKeys < 0) return [];
7098
+ const n = this.next("n");
7099
+ const conds = [];
7100
+ if (ks.minKeys >= 0) conds.push(`${n} < k${ks.minKeys}`);
7101
+ if (ks.maxKeys >= 0) conds.push(`${n} > k${ks.maxKeys}`);
7102
+ const known = this.objectProps(def).map((p) => p.key);
7103
+ const scan = known.length === 0 ? [] : [
7104
+ ` for (const k in ${x}) {`,
7105
+ ` if (!ho.call(${x}, k)) continue`,
7106
+ " switch (k) {",
7107
+ ...known.map((key) => ` case ${literalSource(key)}:`),
7108
+ ` ${n}++`,
7109
+ " }",
7110
+ " }"
7111
+ ];
7112
+ return [
7113
+ `let ${n}`,
7114
+ `if ((f & ${F_STRIP}) === 0) {`,
7115
+ ` ${n} = Object.keys(${x}).length`,
7116
+ "} else {",
7117
+ ` ${n} = 0`,
7118
+ ...scan,
7119
+ "}",
7120
+ `if (${conds.join(" || ")}) ${fail}`
7121
+ ];
7122
+ }
5893
7123
  /** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
5894
7124
  const ks = keySlots(mask, shape, at);
5895
7125
  const branches = [];
@@ -5897,6 +7127,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5897
7127
  if (mask & NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
5898
7128
  if (mask & B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
5899
7129
  if (mask & ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
7130
+ if (mask & OBJECT_BITS) branches.push([`!(${notObject(x)})`, ["return 2"]]);
5900
7131
  const lines = [];
5901
7132
  branches.forEach(([cond, body], i) => {
5902
7133
  lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
@@ -5913,6 +7144,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5913
7144
  if (optional) return constraints;
5914
7145
  const ks = keySlots(mask, shape, at);
5915
7146
  if (def[0] === D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
7147
+ if (def[0] === D_OBJECT) return this.keyCountChecks(ks, x, fail, def);
5916
7148
  if (def[0] !== D_FINAL) return constraints;
5917
7149
  switch (def[1]) {
5918
7150
  case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
@@ -6292,8 +7524,11 @@ exports.$nr = $nr;
6292
7524
  exports.$ps = $ps;
6293
7525
  exports.$q = $q;
6294
7526
  exports.$sh = $sh;
7527
+ exports.$ut = $ut;
6295
7528
  exports.LayerMap = LayerMap;
6296
7529
  exports.SERIALIZE_VERSION = SERIALIZE_VERSION;
7530
+ exports.VALIDATOR_ERROR_CODES = VALIDATOR_ERROR_CODES;
7531
+ exports.VALIDATOR_MESSAGES = VALIDATOR_MESSAGES;
6297
7532
  exports.Validator = Validator;
6298
7533
  exports.ValidatorError = ValidatorError;
6299
7534
  exports.annotate = annotate;
@@ -6310,6 +7545,7 @@ exports.deserializeAnnotatedType = deserializeAnnotatedType;
6310
7545
  exports.detectDiscriminator = detectDiscriminator;
6311
7546
  exports.flattenAnnotatedType = flattenAnnotatedType;
6312
7547
  exports.forAnnotatedType = forAnnotatedType;
7548
+ exports.formatValidatorMessage = formatValidatorMessage;
6313
7549
  exports.fromJsonSchema = fromJsonSchema;
6314
7550
  exports.invalidateCompiledValidators = invalidateCompiledValidators;
6315
7551
  exports.isAnnotatedType = isAnnotatedType;
@@ -6317,12 +7553,20 @@ exports.isAnnotatedTypeOfPrimitive = isAnnotatedTypeOfPrimitive;
6317
7553
  exports.isPhantomType = isPhantomType;
6318
7554
  exports.isWait = isWait;
6319
7555
  exports.lazyJsonSchema = lazyJsonSchema;
7556
+ exports.localizeErrors = localizeErrors;
6320
7557
  exports.mergeJsonSchemas = mergeJsonSchemas;
7558
+ exports.messagesTranslator = messagesTranslator;
6321
7559
  exports.metaEmpty = metaEmpty;
7560
+ exports.normalizeForType = normalizeForType;
6322
7561
  exports.pendingStatements = pendingStatements;
6323
7562
  exports.registerCompiledCheck = registerCompiledCheck;
7563
+ exports.registerUserText = registerUserText;
6324
7564
  exports.serializeAnnotatedType = serializeAnnotatedType;
6325
7565
  exports.throwFeatureDisabled = throwFeatureDisabled;
7566
+ exports.translateServed = translateServed;
7567
+ exports.unionDiscriminator = unionDiscriminator;
7568
+ exports.userTextKeys = userTextKeys;
7569
+ exports.userTextOf = userTextOf;
6326
7570
  exports.watchLayer = watchLayer;
6327
7571
  return exports;
6328
7572
  })({});