@atscript/typescript 0.2.2 → 0.2.4

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
@@ -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]();
@@ -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 = {};
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) {
@@ -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;
@@ -2244,7 +2423,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
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`.
2426
+ * max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`;
2427
+ * object `expect.minKeys, maxKeys`.
2248
2428
  */ _define_property$4(this, "k0", void 0);
2249
2429
  _define_property$4(this, "k1", void 0);
2250
2430
  _define_property$4(this, "k2", void 0);
@@ -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,6 +2737,147 @@ 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
2883
  function _define_property$3(obj, key, value) {
@@ -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,14 +3561,59 @@ 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
3618
  _define_property$3(this, "def", void 0);
3183
3619
  _define_property$3(this, "opts", void 0);
@@ -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` (reported errors only: a union's discriminator is
3676
+ * looked for once its value failed). An entry is reused while the items, their type defs and the
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
@@ -3709,48 +4213,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3709
4213
  //#endregion
3710
4214
  //#region packages/typescript/src/runtime/json-schema.ts
3711
4215
  /**
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
- }
3753
- /**
3754
4216
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
3755
4217
  *
3756
4218
  * Translates the atscript type structure and validation metadata
@@ -3878,7 +4340,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3878
4340
  defs.get(typeDef).schema = yield buildObject(def);
3879
4341
  building = outer;
3880
4342
  }
3881
- return ref(typeDef);
4343
+ return withKeyCounts(ref(typeDef), def.metadata);
3882
4344
  }
3883
4345
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
3884
4346
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -3926,7 +4388,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3926
4388
  return out;
3927
4389
  };
3928
4390
  const kind = def.type.kind;
3929
- if (kind === "object") return yield buildObject(def);
4391
+ if (kind === "object") {
4392
+ const schema = yield buildObject(def);
4393
+ applyKeyCounts(schema, meta);
4394
+ return schema;
4395
+ }
3930
4396
  if (kind === "array") {
3931
4397
  const d = def;
3932
4398
  const schema = {
@@ -3948,6 +4414,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3948
4414
  maxItems: items.length
3949
4415
  };
3950
4416
  const disc = detectDiscriminator(items);
4417
+ let schema;
3951
4418
  if (disc) {
3952
4419
  const mapping = {};
3953
4420
  for (const [val, idx] of Object.entries(disc.indexMapping)) {
@@ -3959,16 +4426,19 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3959
4426
  ]);
3960
4427
  else mapping[val] = `#/oneOf/${idx}`;
3961
4428
  }
3962
- return {
4429
+ schema = {
3963
4430
  oneOf: built,
3964
4431
  discriminator: {
3965
4432
  propertyName: disc.propertyName,
3966
4433
  mapping
3967
4434
  }
3968
4435
  };
4436
+ } else {
4437
+ if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
4438
+ schema = { anyOf: built };
3969
4439
  }
3970
- if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
3971
- return { anyOf: built };
4440
+ applyKeyCounts(schema, meta);
4441
+ return schema;
3972
4442
  }
3973
4443
  return forAnnotatedType(def, {
3974
4444
  phantom() {
@@ -4209,6 +4679,23 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4209
4679
  const maxLength = meta.get("expect.maxLength");
4210
4680
  if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
4211
4681
  }
4682
+ /**
4683
+ * `@expect.minKeys` / `maxKeys` → `minProperties` / `maxProperties` (they constrain objects
4684
+ * only, so they also sit on a union's schema as they are).
4685
+ */ function applyKeyCounts(schema, meta) {
4686
+ const minKeys = meta.get("expect.minKeys");
4687
+ if (minKeys !== void 0) schema.minProperties = boundOf(minKeys, "count");
4688
+ const maxKeys = meta.get("expect.maxKeys");
4689
+ if (maxKeys !== void 0) schema.maxProperties = boundOf(maxKeys, "count");
4690
+ }
4691
+ /** `schema` (a `$ref`) with the key counts of `meta`, if any (beside it, in an `allOf`). */ function withKeyCounts(schema, meta) {
4692
+ const counts = {};
4693
+ applyKeyCounts(counts, meta);
4694
+ return Object.keys(counts).length > 0 ? {
4695
+ allOf: [schema],
4696
+ ...counts
4697
+ } : schema;
4698
+ }
4212
4699
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
4213
4700
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
4214
4701
  if (schema.type === "string") {
@@ -4364,6 +4851,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4364
4851
  handle.prop(key, propType);
4365
4852
  }
4366
4853
  for (const [pattern, propSchema] of Object.entries(s.patternProperties ?? {})) handle.propPattern(compilePattern(pattern), convert(propSchema));
4854
+ if (typeof s.minProperties === "number") handle.annotate("expect.minKeys", { count: s.minProperties });
4855
+ if (typeof s.maxProperties === "number") handle.annotate("expect.maxKeys", { count: s.maxProperties });
4367
4856
  return handle.$type;
4368
4857
  }
4369
4858
  if (s.type === "array") {
@@ -4528,27 +5017,31 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4528
5017
  }
4529
5018
  if (mode === "db") {
4530
5019
  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
- }
5020
+ if (dbValue !== void 0) return validRawValue(dbValue, prop);
4536
5021
  if (prop.metadata.has("db.default.increment")) return { value: "increment" };
4537
5022
  if (prop.metadata.has("db.default.uuid")) return { value: "uuid" };
4538
5023
  if (prop.metadata.has("db.default.now")) return { value: "now" };
4539
5024
  return;
4540
5025
  }
4541
5026
  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 };
5027
+ const metaValue = prop.metadata.get(metaKey);
5028
+ if (metaValue === void 0) return;
5029
+ return validRawValue(metaValue, prop);
5030
+ }
5031
+ /**
5032
+ * An annotation's raw value as a valid value of `prop` (see {@link parseRawValue}); a string the
5033
+ * JSON reading does not fit is tried as the string itself (a `decimal` field, `decimal | null`).
5034
+ */ function validRawValue(raw, prop) {
5035
+ const validator = prop.validator({ unknownProps: "ignore" });
5036
+ const parsed = parseRawValue(raw, prop);
5037
+ if (parsed !== void 0 && validator.validate(parsed, true)) return { value: parsed };
5038
+ if (typeof raw === "string" && parsed !== raw && validator.validate(raw, true)) return { value: raw };
4547
5039
  }
4548
5040
  /**
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.
5041
+ * Parses a raw annotation value into a JS value: a number / boolean literal (a `value`
5042
+ * argument) as it is; a string as-is for string types, else through JSON.parse.
4551
5043
  */ function parseRawValue(raw, prop) {
5044
+ if (typeof raw !== "string") return raw;
4552
5045
  if (prop.type.kind === "" && prop.type.designType === "string") return raw;
4553
5046
  try {
4554
5047
  return JSON.parse(raw);
@@ -4563,7 +5056,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4563
5056
  case "number": return 0;
4564
5057
  case "boolean": return false;
4565
5058
  case "undefined": return;
4566
- case "null": return null;
5059
+ case "null":
5060
+ case "any": return null;
4567
5061
  default: return;
4568
5062
  }
4569
5063
  }
@@ -4661,7 +5155,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4661
5155
  const items = [];
4662
5156
  for (const item of type.items) items.push(yield build(item, path, mode, walk));
4663
5157
  if (items.some(stops)) return STOPPED;
4664
- const values = items.filter((item) => item !== STOPPED);
5158
+ const isAny = (i) => {
5159
+ const t = type.items[i].type;
5160
+ return t.kind === "" && t.designType === "any";
5161
+ };
5162
+ const kept = items.filter((item, i) => item !== STOPPED && !isAny(i));
5163
+ const values = kept.length > 0 ? kept : items.filter((item) => item !== STOPPED);
4665
5164
  return values.length > 0 && values.every(isPlainObject) ? Object.assign({}, ...values) : values[0];
4666
5165
  }
4667
5166
  default: throw new Error(`Unknown type kind "${type.kind}"`);
@@ -5398,6 +5897,70 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5398
5897
  }
5399
5898
  }
5400
5899
 
5900
+ //#endregion
5901
+ //#region packages/typescript/src/runtime/user-text.ts
5902
+ /**
5903
+ * The annotations holding user-facing text (labels, descriptions, error messages): the arguments
5904
+ * their specs flag `userText`. Core's are known from the start ({@link CORE_USER_TEXT}); a plugin's
5905
+ * are registered by the generated modules that write them (`$ut`), or by the plugin itself
5906
+ * ({@link registerUserText}), so a translator finds them at runtime without the specs.
5907
+ */ /** `true`: the value itself is the text; a list: those fields of the value object are. */ /**
5908
+ * The user-facing text of `@atscript/core`'s annotations (its specs' `userText` arguments; a test
5909
+ * keeps them equal).
5910
+ */ const CORE_USER_TEXT = new Map([
5911
+ ["meta.label", true],
5912
+ ["meta.description", true],
5913
+ ["meta.required", ["message"]],
5914
+ ["expect.minLength", ["message"]],
5915
+ ["expect.maxLength", ["message"]],
5916
+ ["expect.min", ["message"]],
5917
+ ["expect.max", ["message"]],
5918
+ ["expect.exclusiveMin", ["message"]],
5919
+ ["expect.exclusiveMax", ["message"]],
5920
+ ["expect.int", ["message"]],
5921
+ ["expect.minKeys", ["message"]],
5922
+ ["expect.maxKeys", ["message"]],
5923
+ ["expect.message", true],
5924
+ ["expect.pattern", ["message"]],
5925
+ ["expect.array.uniqueItems", ["message"]],
5926
+ ["expect.array.key", ["message"]]
5927
+ ]);
5928
+ const USER_TEXT = new Map(CORE_USER_TEXT);
5929
+ /**
5930
+ * Registers metadata key `key` as holding user-facing text: `true` (default) — its value is the
5931
+ * text; a list of field names — those fields of its value object are. Fields add up across calls.
5932
+ * For plugins that write such metadata at runtime; generated modules register what they write.
5933
+ */ function registerUserText(key, fields = true) {
5934
+ const known = USER_TEXT.get(key);
5935
+ if (known === true || fields === true) {
5936
+ USER_TEXT.set(key, true);
5937
+ return;
5938
+ }
5939
+ const added = fields.filter((f) => !known?.includes(f));
5940
+ if (added.length > 0 || !known) USER_TEXT.set(key, [...known ?? [], ...added]);
5941
+ }
5942
+ /**
5943
+ * Registers user-text keys written by a generated module (see {@link registerUserText}): `key` —
5944
+ * the value itself; `key:field` — that field of the value object.
5945
+ */ function $ut(...entries) {
5946
+ for (const entry of entries) {
5947
+ const at = entry.indexOf(":");
5948
+ if (at === -1) registerUserText(entry);
5949
+ else registerUserText(entry.slice(0, at), [entry.slice(at + 1)]);
5950
+ }
5951
+ }
5952
+ /**
5953
+ * Where metadata key `key` holds user-facing text: `true` — its value is the text (a string; for
5954
+ * a `multiple` annotation, each item of the list); a list of field names — those fields of its
5955
+ * value object (each item's, for a list); `undefined` — no user-facing text. Core keys are known
5956
+ * from the start; a plugin's once a module writing them is loaded (or the plugin registered them).
5957
+ */ function userTextOf(key) {
5958
+ return USER_TEXT.get(key);
5959
+ }
5960
+ /** Every metadata key holding user-facing text known so far (see {@link userTextOf}). */ function userTextKeys() {
5961
+ return USER_TEXT;
5962
+ }
5963
+
5401
5964
  //#endregion
5402
5965
  //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
5403
5966
  /**
@@ -5559,7 +6122,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5559
6122
  body.push(...this.extra);
5560
6123
  const root = this.layout[1];
5561
6124
  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]}`);
6125
+ 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
6126
  else {
5564
6127
  body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
5565
6128
  body.push("return r");
@@ -5815,7 +6378,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5815
6378
  def(d, mask, shape, at, x, ctx) {
5816
6379
  const def = this.defs[d];
5817
6380
  const kind = def[0];
5818
- if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) return this.call(`d${d}`, x, ctx);
6381
+ if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) {
6382
+ if (kind === D_OBJECT && (mask & OBJECT_BITS) !== 0) {
6383
+ const ks = keySlots(mask, shape, at);
6384
+ return [...this.call(`d${d}`, x, ctx), ...this.keyCountChecks(ks, x, ctx.fail, def)];
6385
+ }
6386
+ return this.call(`d${d}`, x, ctx);
6387
+ }
5819
6388
  switch (kind) {
5820
6389
  case D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
5821
6390
  case D_ARRAY: return [
@@ -5857,7 +6426,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5857
6426
  if (mask & B_REQUIRED) conds.push(`${x} !== true`);
5858
6427
  return [`if (${conds.join(" || ")}) ${fail}`];
5859
6428
  }
5860
- case "any": return [];
6429
+ case "any": return [`if (${x} === undefined) ${fail}`];
5861
6430
  case "never": return [fail];
5862
6431
  case "undefined": return [`if (${x} !== undefined) ${fail}`];
5863
6432
  case "null": return [`if (${x} !== null) ${fail}`];
@@ -5890,6 +6459,37 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5890
6459
  if (mask & B_UNIQUE) lines.push("return 2");
5891
6460
  return lines;
5892
6461
  }
6462
+ /**
6463
+ * `@expect.minKeys` / `maxKeys` of object `x` matched as object def `def`: the keys the result
6464
+ * keeps (with `unknownProps: 'strip'` the declared ones, else every own key: with 'error' the
6465
+ * def already failed an object with an unknown key).
6466
+ */ keyCountChecks(ks, x, fail, def) {
6467
+ if (ks.minKeys < 0 && ks.maxKeys < 0) return [];
6468
+ const n = this.next("n");
6469
+ const conds = [];
6470
+ if (ks.minKeys >= 0) conds.push(`${n} < k${ks.minKeys}`);
6471
+ if (ks.maxKeys >= 0) conds.push(`${n} > k${ks.maxKeys}`);
6472
+ const known = this.objectProps(def).map((p) => p.key);
6473
+ const scan = known.length === 0 ? [] : [
6474
+ ` for (const k in ${x}) {`,
6475
+ ` if (!ho.call(${x}, k)) continue`,
6476
+ " switch (k) {",
6477
+ ...known.map((key) => ` case ${literalSource(key)}:`),
6478
+ ` ${n}++`,
6479
+ " }",
6480
+ " }"
6481
+ ];
6482
+ return [
6483
+ `let ${n}`,
6484
+ `if ((f & ${F_STRIP}) === 0) {`,
6485
+ ` ${n} = Object.keys(${x}).length`,
6486
+ "} else {",
6487
+ ` ${n} = 0`,
6488
+ ...scan,
6489
+ "}",
6490
+ `if (${conds.join(" || ")}) ${fail}`
6491
+ ];
6492
+ }
5893
6493
  /** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
5894
6494
  const ks = keySlots(mask, shape, at);
5895
6495
  const branches = [];
@@ -5897,6 +6497,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5897
6497
  if (mask & NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
5898
6498
  if (mask & B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
5899
6499
  if (mask & ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
6500
+ if (mask & OBJECT_BITS) branches.push([`!(${notObject(x)})`, ["return 2"]]);
5900
6501
  const lines = [];
5901
6502
  branches.forEach(([cond, body], i) => {
5902
6503
  lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
@@ -5913,6 +6514,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5913
6514
  if (optional) return constraints;
5914
6515
  const ks = keySlots(mask, shape, at);
5915
6516
  if (def[0] === D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
6517
+ if (def[0] === D_OBJECT) return this.keyCountChecks(ks, x, fail, def);
5916
6518
  if (def[0] !== D_FINAL) return constraints;
5917
6519
  switch (def[1]) {
5918
6520
  case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
@@ -6292,8 +6894,11 @@ exports.$nr = $nr;
6292
6894
  exports.$ps = $ps;
6293
6895
  exports.$q = $q;
6294
6896
  exports.$sh = $sh;
6897
+ exports.$ut = $ut;
6295
6898
  exports.LayerMap = LayerMap;
6296
6899
  exports.SERIALIZE_VERSION = SERIALIZE_VERSION;
6900
+ exports.VALIDATOR_ERROR_CODES = VALIDATOR_ERROR_CODES;
6901
+ exports.VALIDATOR_MESSAGES = VALIDATOR_MESSAGES;
6297
6902
  exports.Validator = Validator;
6298
6903
  exports.ValidatorError = ValidatorError;
6299
6904
  exports.annotate = annotate;
@@ -6310,6 +6915,7 @@ exports.deserializeAnnotatedType = deserializeAnnotatedType;
6310
6915
  exports.detectDiscriminator = detectDiscriminator;
6311
6916
  exports.flattenAnnotatedType = flattenAnnotatedType;
6312
6917
  exports.forAnnotatedType = forAnnotatedType;
6918
+ exports.formatValidatorMessage = formatValidatorMessage;
6313
6919
  exports.fromJsonSchema = fromJsonSchema;
6314
6920
  exports.invalidateCompiledValidators = invalidateCompiledValidators;
6315
6921
  exports.isAnnotatedType = isAnnotatedType;
@@ -6317,12 +6923,17 @@ exports.isAnnotatedTypeOfPrimitive = isAnnotatedTypeOfPrimitive;
6317
6923
  exports.isPhantomType = isPhantomType;
6318
6924
  exports.isWait = isWait;
6319
6925
  exports.lazyJsonSchema = lazyJsonSchema;
6926
+ exports.localizeErrors = localizeErrors;
6320
6927
  exports.mergeJsonSchemas = mergeJsonSchemas;
6928
+ exports.messagesTranslator = messagesTranslator;
6321
6929
  exports.metaEmpty = metaEmpty;
6322
6930
  exports.pendingStatements = pendingStatements;
6323
6931
  exports.registerCompiledCheck = registerCompiledCheck;
6932
+ exports.registerUserText = registerUserText;
6324
6933
  exports.serializeAnnotatedType = serializeAnnotatedType;
6325
6934
  exports.throwFeatureDisabled = throwFeatureDisabled;
6935
+ exports.userTextKeys = userTextKeys;
6936
+ exports.userTextOf = userTextOf;
6326
6937
  exports.watchLayer = watchLayer;
6327
6938
  return exports;
6328
6939
  })({});