@atscript/typescript 0.2.8 → 0.2.9

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.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
2
- const require_plugin = require('./plugin-lDfE9qm8.cjs');
3
- const require_user_text = require('./user-text-BvyErcKK.cjs');
2
+ const require_plugin = require('./plugin-e4R5zAfw.cjs');
3
+ const require_user_text = require('./user-text-C9ov-aSv.cjs');
4
4
 
5
5
  exports.JS_COMPILED_FORMAT = require_plugin.JS_COMPILED_FORMAT;
6
6
  exports.JS_INTERPRETED_FORMAT = require_plugin.JS_INTERPRETED_FORMAT;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as withLoadCheck, i as importCycle, n as JS_INTERPRETED_FORMAT, r as tsPlugin, t as JS_COMPILED_FORMAT } from "./plugin-DUInOy5v.mjs";
2
- import { Y as invalidateCompiledValidators } from "./user-text-DZR5hfLa.mjs";
1
+ import { a as withLoadCheck, i as importCycle, n as JS_INTERPRETED_FORMAT, r as tsPlugin, t as JS_COMPILED_FORMAT } from "./plugin-0ZgIMt1Y.mjs";
2
+ import { X as invalidateCompiledValidators } from "./user-text-fz-TpY_H.mjs";
3
3
 
4
4
  export { JS_COMPILED_FORMAT, JS_INTERPRETED_FORMAT, tsPlugin as default, tsPlugin, importCycle, invalidateCompiledValidators, withLoadCheck };
@@ -1,4 +1,4 @@
1
- import { n as CORE_USER_TEXT, o as uniqueName, v as stageEnds } from "./user-text-DZR5hfLa.mjs";
1
+ import { n as CORE_USER_TEXT, o as uniqueName, v as stageEnds } from "./user-text-fz-TpY_H.mjs";
2
2
  import path from "path";
3
3
  import { ANNOTATE_RESET, DEFAULT_FORMAT, MERGE_TOO_COMPLEX, NAV_PROP_ANNOTATIONS, SemanticGroup, andExprs, annotatedValueKinds, componentOf, components, defPosition, documentsEpoch, entryParts, flatDefinitions, forEachAnnotationSpec, getRelPath, hasMutatingAnnotates, hasNavPropAnnotation, isAnnotate, isArray, isAsView, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isInterface, isNull, isPhantomNode, isPrimitive, isQueryLogical, isRef, isStructure, isTuple, moduleId, pastViews, resolveAtscriptFromPath, unshell, userTextFields, withoutAsExtension } from "@atscript/core";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -25,7 +25,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  }) : target, mod));
26
26
 
27
27
  //#endregion
28
- const require_user_text = require('./user-text-BvyErcKK.cjs');
28
+ const require_user_text = require('./user-text-C9ov-aSv.cjs');
29
29
  let path = require("path");
30
30
  path = __toESM(path);
31
31
  let _atscript_core = require("@atscript/core");
@@ -4012,13 +4012,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4012
4012
  for (let i = 0; i < keys.length; i++) {
4013
4013
  const key = keys[i];
4014
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
- }
4015
+ const def = propOf(type, key);
4022
4016
  const mapped = def ? step(def, input, ctx) : input;
4023
4017
  if (mapped === NO_MATCH) return NO_MATCH;
4024
4018
  if (out) setOwn(out, key, mapped);
@@ -4030,6 +4024,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4030
4024
  }
4031
4025
  return out ?? value;
4032
4026
  }
4027
+ /** The def of prop `key` of object `type`: its declared prop, else the first pattern `key` matches. */ function propOf(type, key) {
4028
+ const def = type.props.get(key);
4029
+ if (def) return def;
4030
+ for (const p of type.propsPatterns) if (p.pattern.test(key)) return p.def;
4031
+ }
4033
4032
  /**
4034
4033
  * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
4035
4034
  * items). Copy-on-first-change, as {@link mapProps}.
@@ -4449,12 +4448,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4449
4448
  * backtracking). A scalar branch takes what it parses; an object (tuple)
4450
4449
  * branch takes a plain object (an array of its length) unless a literal
4451
4450
  * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
4452
- * does not coerce to it, a string compared after the normalizers of the
4453
- * literal and of the unions it is in. An object takes the branch its
4454
- * discriminator names (as the validator does: the literal itself first, else
4455
- * `"2"` names a `2` literal), else the first whose shape it has (required
4456
- * props present, no undeclared key), else the first that takes it. When no
4457
- * branch takes the value, it is returned untouched.
4451
+ * does not coerce to it (`"2"` coerces to a `2` literal), a string compared
4452
+ * after the normalizers of the literal and of the unions it is in. A scalar
4453
+ * takes the first branch that takes it. An object or array takes the only
4454
+ * branch that takes it, else the one it fits best, judged in this order
4455
+ * (never looking deeper than its own keys and items): its props (items) hold
4456
+ * values of their kinds (a string that parses for a `number` prop, `null`
4457
+ * where `null` is allowed); it has no undeclared key; it has every required
4458
+ * prop (the last two can be waived by `partial` / `unknownProps`, a wrong
4459
+ * kind cannot); a nested union's branches count as the union's own. Ties go
4460
+ * to the branch an object's discriminator names by the literal itself, then
4461
+ * to declared order. When no branch takes the value, it is returned
4462
+ * untouched.
4458
4463
  * - Objects recurse into props when the input is a plain object (covers
4459
4464
  * `@Query()` DTOs where every field arrives as a string), whatever their
4460
4465
  * literal props hold unless tried as a union branch.
@@ -4539,34 +4544,161 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4539
4544
  }
4540
4545
  }
4541
4546
  /**
4542
- * The branch of union `items` that takes `value` (see {@link takes}): the one an object's
4543
- * discriminator names; else, for an object, the first that takes it and whose shape it has (see
4544
- * {@link fits}); else the first that takes it, in declared order (a partial patch); `undefined`
4545
- * when none does.
4547
+ * The score bits of a union branch for an object (array), most weighty first (see {@link score} and
4548
+ * {@link coerceForType}): props (items) hold their kinds; no undeclared key; required props present.
4549
+ */ const HOLDS = 4;
4550
+ const DECLARED = 2;
4551
+ const COMPLETE = 1;
4552
+ const BEST = DECLARED | 5;
4553
+ /** The score of a branch not scored yet (the only taker so far, see {@link TPick}). */ const UNSCORED = -1;
4554
+ /**
4555
+ * The branch of union `items` that takes `value` (see {@link takes}); `undefined` when none does.
4556
+ * A scalar: the first taker. An object or array: of the leaf branches (see {@link leavesOf}), the
4557
+ * only taker, else the best scored one (see {@link score}); the branch the discriminator names is
4558
+ * tried first, then declared order, and a tie keeps the earlier one.
4546
4559
  */ function branchOf(items, value) {
4547
- let first;
4548
- if (isPlainObject$1(value)) {
4549
- const named = discriminatedBranch(items, value);
4550
- if (named && takes(named, value)) return named;
4551
- for (const item of items) if (takes(item, value)) {
4552
- if (fits(item, value)) return item;
4553
- first ?? (first = item);
4554
- }
4555
- return first;
4560
+ if (!isPlainObject$1(value) && !Array.isArray(value)) return items.find((item) => takes(item, value));
4561
+ const leaves = leavesOf(items);
4562
+ const pick = {
4563
+ branch: void 0,
4564
+ score: UNSCORED,
4565
+ keys: void 0,
4566
+ values: void 0
4567
+ };
4568
+ const named = Array.isArray(value) ? void 0 : discriminatedBranch(leaves, value);
4569
+ if (named) consider(named, value, pick);
4570
+ for (const leaf of leaves) {
4571
+ if (pick.score === BEST) break;
4572
+ if (leaf !== named) consider(leaf, value, pick);
4573
+ }
4574
+ return pick.branch;
4575
+ }
4576
+ /** {@link leavesOf} by union items: valid until the next type tree write (see `typeWriteCount`). */ let leavesCache = /* @__PURE__ */ new WeakMap();
4577
+ let leavesStamp = -1;
4578
+ /**
4579
+ * The branches of union `items` that are not unions, a nested union's in its place, in declared
4580
+ * order, so `(A | B) | C` and `A | B | C` rank alike: `items` itself when none is a union, else
4581
+ * the same array for the same items (the discriminator over them is decided once).
4582
+ */ function leavesOf(items) {
4583
+ if (!items.some(isUnion)) return items;
4584
+ const writes = typeWriteCount();
4585
+ if (writes !== leavesStamp) {
4586
+ leavesStamp = writes;
4587
+ leavesCache = /* @__PURE__ */ new WeakMap();
4588
+ }
4589
+ let leaves = leavesCache.get(items);
4590
+ if (!leaves) {
4591
+ leaves = [];
4592
+ collectLeaves(items, leaves);
4593
+ leavesCache.set(items, leaves);
4594
+ }
4595
+ return leaves;
4596
+ }
4597
+ function isUnion(def) {
4598
+ return def.type.kind === "union";
4599
+ }
4600
+ function collectLeaves(items, out) {
4601
+ for (const item of items) if (isUnion(item)) collectLeaves(item.type.items, out);
4602
+ else out.push(item);
4603
+ }
4604
+ /** Takes leaf branch `def` for `pick` when it takes `value` and scores above the best so far. */ function consider(def, value, pick) {
4605
+ if (!takes(def, value)) return;
4606
+ if (!pick.branch) {
4607
+ pick.branch = def;
4608
+ return;
4609
+ }
4610
+ if (pick.score === UNSCORED) {
4611
+ pick.score = score(pick.branch, value, pick);
4612
+ if (pick.score === BEST) return;
4613
+ }
4614
+ const s = score(def, value, pick);
4615
+ if (s > pick.score) {
4616
+ pick.branch = def;
4617
+ pick.score = s;
4556
4618
  }
4557
- return items.find((item) => takes(item, value));
4558
4619
  }
4559
4620
  /**
4560
- * Whether object `value` has the shape of branch `def`, by its own keys alone: every required
4561
- * prop is one of them, and each of them is a prop (or matches a prop pattern) of the branch. A
4562
- * union: one of its branches; a branch that is not an object (nor an intersection of objects)
4563
- * has any shape.
4564
- */ function fits(def, value) {
4565
- if (def.type.kind === "union") return def.type.items.some((item) => fits(item, value));
4621
+ * The bits (see {@link HOLDS}) leaf branch `def`, which takes object (array) `value`, scores; once
4622
+ * it cannot beat `pick.score`, any score not above it. Only an object branch can miss
4623
+ * {@link DECLARED} or {@link COMPLETE}.
4624
+ */ function score(def, value, pick) {
4625
+ var _pick, _pick1;
4566
4626
  const objects = [];
4567
- if (!objectsOf(def, objects)) return true;
4568
- for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return false;
4569
- return Object.keys(value).every((key) => objects.some((o) => o.props.has(key) || o.propsPatterns.some((p) => p.pattern.test(key))));
4627
+ if (Array.isArray(value) || !objectsOf(def, objects)) return (holdsAll(def, value) ? HOLDS : 0) | 3;
4628
+ const floor = pick.score;
4629
+ let bits = BEST;
4630
+ const keys = (_pick = pick).keys ?? (_pick.keys = Object.keys(value));
4631
+ const values = (_pick1 = pick).values ?? (_pick1.values = keys.map((key) => value[key]));
4632
+ for (let i = 0; i < keys.length; i++) {
4633
+ const key = keys[i];
4634
+ let declared = false;
4635
+ for (const o of objects) {
4636
+ const prop = propOf(o, key);
4637
+ if (prop) {
4638
+ declared = true;
4639
+ if (bits & HOLDS && !holds(prop, values[i])) bits &= ~HOLDS;
4640
+ }
4641
+ }
4642
+ if (!declared) bits &= ~DECLARED;
4643
+ if (bits <= floor) return bits;
4644
+ if (bits <= COMPLETE) break;
4645
+ }
4646
+ for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return bits & ~COMPLETE;
4647
+ return bits;
4648
+ }
4649
+ /**
4650
+ * Whether each prop (pattern prop) of branch `def` that object `value` has, or each item of array
4651
+ * `value`, holds a value of its kind (see {@link holds}). Looks at `value`'s own keys and items
4652
+ * only. `def` takes `value` (see {@link takes}).
4653
+ */ function holdsAll(def, value) {
4654
+ const type = def.type;
4655
+ switch (type.kind) {
4656
+ case "object": {
4657
+ const o = type;
4658
+ const record = value;
4659
+ return Object.keys(record).every((key) => {
4660
+ const prop = propOf(o, key);
4661
+ return !prop || holds(prop, record[key]);
4662
+ });
4663
+ }
4664
+ case "array": {
4665
+ const of = type.of;
4666
+ return value.every((item) => holds(of, item));
4667
+ }
4668
+ case "tuple": return type.items.every((item, i) => holds(item, value[i]));
4669
+ case "union": return type.items.some((item) => takes(item, value) && holdsAll(item, value));
4670
+ case "intersection": return type.items.every((item) => holdsAll(item, value));
4671
+ default: return true;
4672
+ }
4673
+ }
4674
+ /**
4675
+ * Whether `input` is of the kind of prop (item) `def`, never looking inside it: a scalar that
4676
+ * coerces to the prop's scalar type, or to one of its literals (a string after the normalizers on
4677
+ * the literal's way, see `literalNodes`); a plain object for an object, an array for an array (of
4678
+ * the tuple's length); `null` where the prop takes `null` (optional or a nullable type).
4679
+ * `inherited`: the normalizer flags of the unions `def` is in.
4680
+ */ function holds(def, input, inherited = 0) {
4681
+ if (input === void 0) return true;
4682
+ if (input === null) return def.optional === true || acceptsNull$1(def);
4683
+ const type = def.type;
4684
+ switch (type.kind) {
4685
+ case "": {
4686
+ const final = type;
4687
+ return final.value === void 0 ? scalar(final.designType, input) !== NO_MATCH : coercesTo(def, flagsOf(def, inherited), input);
4688
+ }
4689
+ case "object": return isPlainObject$1(input);
4690
+ case "array": return Array.isArray(input);
4691
+ case "tuple": return Array.isArray(input) && input.length === type.items.length;
4692
+ case "union": {
4693
+ const flags = flagsOf(def, inherited);
4694
+ return type.items.some((item) => holds(item, input, flags));
4695
+ }
4696
+ case "intersection": {
4697
+ const flags = flagsOf(def, inherited);
4698
+ return type.items.every((item) => holds(item, input, flags));
4699
+ }
4700
+ default: return false;
4701
+ }
4570
4702
  }
4571
4703
  /** Collects the objects `def` is (an object, an intersection of objects); `false` for others. */ function objectsOf(def, out) {
4572
4704
  const type = def.type;
@@ -4588,7 +4720,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4588
4720
  case "": return coerce(def, value) !== NO_MATCH;
4589
4721
  case "object":
4590
4722
  if (!isPlainObject$1(value)) return false;
4591
- for (const [key, prop] of type.props) if (Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
4723
+ for (const [key, prop] of type.props) if (mayBeLiteral(prop) && Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
4592
4724
  return true;
4593
4725
  case "array": return Array.isArray(value);
4594
4726
  case "tuple": {
@@ -4600,6 +4732,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4600
4732
  default: return false;
4601
4733
  }
4602
4734
  }
4735
+ /** Whether `def` can be a literal prop (see `literalNodes`): a literal or a union. */ function mayBeLiteral(def) {
4736
+ const type = def.type;
4737
+ return type.kind === "" ? type.value !== void 0 : type.kind === "union";
4738
+ }
4603
4739
  /**
4604
4740
  * Whether prop (item) `def` of a union branch can hold `input`: anything, but a literal prop
4605
4741
  * (see `literalNodes`: `kind: 'cat'`, `kind: 'cat' | null`) only a value that coerces to one of
@@ -4608,26 +4744,23 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4608
4744
  */ function holdsLiteral(def, input) {
4609
4745
  if (input === void 0 || input === null) return true;
4610
4746
  const literals = literalNodes(def);
4611
- return !literals || literals.some((literal) => coercesTo(literal, input));
4747
+ return !literals || literals.some((literal) => coercesTo(literal.node, literal.flags, input));
4612
4748
  }
4613
- /** Whether `input` coerces to the value of `literal` (see `holdsLiteral`). */ function coercesTo(literal, input) {
4614
- const value = typeof input === "string" ? applyFlags(input, literal.flags) : input;
4615
- return coerce(literal.node, value) !== NO_MATCH;
4749
+ /**
4750
+ * Whether `input` coerces to the value of literal `node`, a string after normalizer `flags` (see
4751
+ * `holdsLiteral`).
4752
+ */ function coercesTo(node, flags, input) {
4753
+ return coerce(node, typeof input === "string" ? applyFlags(input, flags) : input) !== NO_MATCH;
4616
4754
  }
4617
4755
  /**
4618
- * The branch of union `items` the discriminator of object `value` names: its literal itself,
4619
- * else the one its value coerces to (`"2"` names `2`, see {@link coercesTo}); `undefined` when the
4620
- * union has no discriminator or the value names no branch.
4756
+ * The branch of union `items` whose discriminator literal is exactly the one object `value` holds
4757
+ * (`"1"` names a `'1'` literal, not a `1`, though it makes a `1` branch a taker, see {@link takes});
4758
+ * `undefined` when the union has no discriminator or no branch's literal is that value.
4621
4759
  */ function discriminatedBranch(items, value) {
4622
4760
  const disc = unionDiscriminator(items);
4623
- if (disc === void 0) return;
4624
- const tag = Object.hasOwn(value, disc.property) ? value[disc.property] : void 0;
4625
- if (tag === void 0 || tag === null) return;
4761
+ if (disc === void 0 || !Object.hasOwn(value, disc.property)) return;
4762
+ const tag = value[disc.property];
4626
4763
  for (const [index, literal] of disc.branches) if (literal === tag) return items[index];
4627
- for (const [index] of disc.branches) {
4628
- const prop = items[index].type.props.get(disc.property);
4629
- if (prop && holdsLiteral(prop, tag)) return items[index];
4630
- }
4631
4764
  }
4632
4765
  /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
4633
4766
  const result = coerce(def, input);
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_plugin = require('./plugin-lDfE9qm8.cjs');
3
- const require_user_text = require('./user-text-BvyErcKK.cjs');
2
+ const require_plugin = require('./plugin-e4R5zAfw.cjs');
3
+ const require_user_text = require('./user-text-C9ov-aSv.cjs');
4
4
  let path = require("path");
5
5
  path = require_plugin.__toESM(path);
6
6
  let _atscript_core = require("@atscript/core");
@@ -1,5 +1,5 @@
1
- import { r as tsPlugin } from "./plugin-DUInOy5v.mjs";
2
- import { j as Validator } from "./user-text-DZR5hfLa.mjs";
1
+ import { r as tsPlugin } from "./plugin-0ZgIMt1Y.mjs";
2
+ import { j as Validator } from "./user-text-fz-TpY_H.mjs";
3
3
  import path from "path";
4
4
  import { build } from "@atscript/core";
5
5
  import { readFileSync, writeFileSync } from "fs";
@@ -4142,6 +4142,12 @@ Object.defineProperty(exports, 'ValidatorError', {
4142
4142
  return ValidatorError;
4143
4143
  }
4144
4144
  });
4145
+ Object.defineProperty(exports, 'acceptsNull', {
4146
+ enumerable: true,
4147
+ get: function () {
4148
+ return acceptsNull;
4149
+ }
4150
+ });
4145
4151
  Object.defineProperty(exports, 'annotate', {
4146
4152
  enumerable: true,
4147
4153
  get: function () {
@@ -4021,4 +4021,4 @@ const USER_TEXT = new Map(CORE_USER_TEXT);
4021
4021
  }
4022
4022
 
4023
4023
  //#endregion
4024
- export { VALIDATOR_KEYS as $, propAtChain as A, registerCompiledCheck as B, createAnnotatedTypeNode as C, isAnnotatedType as D, defineAnnotatedType as E, VALIDATOR_MESSAGES as F, $nr as G, jsonSchemaPattern as H, formatCodeOf as I, watchLayer as J, LayerMap as K, formatValidatorMessage as L, ValidatorError as M, unionDiscriminator as N, isAnnotatedTypeOfPrimitive as O, VALIDATOR_ERROR_CODES as P, DECIMAL_RE as Q, localizeErrors as R, annotate as S, createObjectTypeDef as T, statelessRegExp as U, detectDiscriminator as V, $ak as W, touched as X, invalidateCompiledValidators as Y, typeWriteCount as Z, pendingStatements as _, userTextOf as a, cutKey as b, $blk as c, $fc as d, arrayKeyProps as et, $ft as f, appliedBlockModules as g, $sh as h, userTextKeys as i, Validator as j, isPhantomType as k, $end as l, $q as m, CORE_USER_TEXT as n, uniqueName as o, $ps as p, metaEmpty as q, registerUserText as r, $alias as s, $ut as t, boundOf as tt, $f as u, stageEnds as v, createMetadataMap as w, enterCut as x, cutAs as y, messagesTranslator as z };
4024
+ export { DECIMAL_RE as $, propAtChain as A, acceptsNull as B, createAnnotatedTypeNode as C, isAnnotatedType as D, defineAnnotatedType as E, VALIDATOR_MESSAGES as F, $ak as G, detectDiscriminator as H, formatCodeOf as I, metaEmpty as J, $nr as K, formatValidatorMessage as L, ValidatorError as M, unionDiscriminator as N, isAnnotatedTypeOfPrimitive as O, VALIDATOR_ERROR_CODES as P, typeWriteCount as Q, localizeErrors as R, annotate as S, createObjectTypeDef as T, jsonSchemaPattern as U, registerCompiledCheck as V, statelessRegExp as W, invalidateCompiledValidators as X, watchLayer as Y, touched as Z, pendingStatements as _, userTextOf as a, cutKey as b, $blk as c, $fc as d, VALIDATOR_KEYS as et, $ft as f, appliedBlockModules as g, $sh as h, userTextKeys as i, Validator as j, isPhantomType as k, $end as l, $q as m, CORE_USER_TEXT as n, boundOf as nt, uniqueName as o, $ps as p, LayerMap as q, registerUserText as r, $alias as s, $ut as t, arrayKeyProps as tt, $f as u, stageEnds as v, createMetadataMap as w, enterCut as x, cutAs as y, messagesTranslator as z };
package/dist/utils.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_user_text = require('./user-text-BvyErcKK.cjs');
2
+ const require_user_text = require('./user-text-C9ov-aSv.cjs');
3
3
 
4
4
  //#region packages/typescript/src/runtime/copy-on-change.ts
5
5
  /**
@@ -17,13 +17,7 @@ const require_user_text = require('./user-text-BvyErcKK.cjs');
17
17
  for (let i = 0; i < keys.length; i++) {
18
18
  const key = keys[i];
19
19
  const input = value[key];
20
- let def = type.props.get(key);
21
- if (!def) {
22
- for (const { pattern, def: patternDef } of type.propsPatterns) if (pattern.test(key)) {
23
- def = patternDef;
24
- break;
25
- }
26
- }
20
+ const def = propOf(type, key);
27
21
  const mapped = def ? step(def, input, ctx) : input;
28
22
  if (mapped === NO_MATCH) return NO_MATCH;
29
23
  if (out) setOwn(out, key, mapped);
@@ -35,6 +29,11 @@ const require_user_text = require('./user-text-BvyErcKK.cjs');
35
29
  }
36
30
  return out ?? value;
37
31
  }
32
+ /** The def of prop `key` of object `type`: its declared prop, else the first pattern `key` matches. */ function propOf(type, key) {
33
+ const def = type.props.get(key);
34
+ if (def) return def;
35
+ for (const p of type.propsPatterns) if (p.pattern.test(key)) return p.def;
36
+ }
38
37
  /**
39
38
  * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
40
39
  * items). Copy-on-first-change, as {@link mapProps}.
@@ -454,12 +453,18 @@ function judgesFor(opts) {
454
453
  * backtracking). A scalar branch takes what it parses; an object (tuple)
455
454
  * branch takes a plain object (an array of its length) unless a literal
456
455
  * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
457
- * does not coerce to it, a string compared after the normalizers of the
458
- * literal and of the unions it is in. An object takes the branch its
459
- * discriminator names (as the validator does: the literal itself first, else
460
- * `"2"` names a `2` literal), else the first whose shape it has (required
461
- * props present, no undeclared key), else the first that takes it. When no
462
- * branch takes the value, it is returned untouched.
456
+ * does not coerce to it (`"2"` coerces to a `2` literal), a string compared
457
+ * after the normalizers of the literal and of the unions it is in. A scalar
458
+ * takes the first branch that takes it. An object or array takes the only
459
+ * branch that takes it, else the one it fits best, judged in this order
460
+ * (never looking deeper than its own keys and items): its props (items) hold
461
+ * values of their kinds (a string that parses for a `number` prop, `null`
462
+ * where `null` is allowed); it has no undeclared key; it has every required
463
+ * prop (the last two can be waived by `partial` / `unknownProps`, a wrong
464
+ * kind cannot); a nested union's branches count as the union's own. Ties go
465
+ * to the branch an object's discriminator names by the literal itself, then
466
+ * to declared order. When no branch takes the value, it is returned
467
+ * untouched.
463
468
  * - Objects recurse into props when the input is a plain object (covers
464
469
  * `@Query()` DTOs where every field arrives as a string), whatever their
465
470
  * literal props hold unless tried as a union branch.
@@ -544,34 +549,161 @@ function scalar(designType, value) {
544
549
  }
545
550
  }
546
551
  /**
547
- * The branch of union `items` that takes `value` (see {@link takes}): the one an object's
548
- * discriminator names; else, for an object, the first that takes it and whose shape it has (see
549
- * {@link fits}); else the first that takes it, in declared order (a partial patch); `undefined`
550
- * when none does.
552
+ * The score bits of a union branch for an object (array), most weighty first (see {@link score} and
553
+ * {@link coerceForType}): props (items) hold their kinds; no undeclared key; required props present.
554
+ */ const HOLDS = 4;
555
+ const DECLARED = 2;
556
+ const COMPLETE = 1;
557
+ const BEST = DECLARED | 5;
558
+ /** The score of a branch not scored yet (the only taker so far, see {@link TPick}). */ const UNSCORED = -1;
559
+ /**
560
+ * The branch of union `items` that takes `value` (see {@link takes}); `undefined` when none does.
561
+ * A scalar: the first taker. An object or array: of the leaf branches (see {@link leavesOf}), the
562
+ * only taker, else the best scored one (see {@link score}); the branch the discriminator names is
563
+ * tried first, then declared order, and a tie keeps the earlier one.
551
564
  */ function branchOf(items, value) {
552
- let first;
553
- if (isPlainObject$1(value)) {
554
- const named = discriminatedBranch(items, value);
555
- if (named && takes(named, value)) return named;
556
- for (const item of items) if (takes(item, value)) {
557
- if (fits(item, value)) return item;
558
- first ?? (first = item);
559
- }
560
- return first;
565
+ if (!isPlainObject$1(value) && !Array.isArray(value)) return items.find((item) => takes(item, value));
566
+ const leaves = leavesOf(items);
567
+ const pick = {
568
+ branch: void 0,
569
+ score: UNSCORED,
570
+ keys: void 0,
571
+ values: void 0
572
+ };
573
+ const named = Array.isArray(value) ? void 0 : discriminatedBranch(leaves, value);
574
+ if (named) consider(named, value, pick);
575
+ for (const leaf of leaves) {
576
+ if (pick.score === BEST) break;
577
+ if (leaf !== named) consider(leaf, value, pick);
561
578
  }
562
- return items.find((item) => takes(item, value));
579
+ return pick.branch;
563
580
  }
581
+ /** {@link leavesOf} by union items: valid until the next type tree write (see `typeWriteCount`). */ let leavesCache = /* @__PURE__ */ new WeakMap();
582
+ let leavesStamp = -1;
564
583
  /**
565
- * Whether object `value` has the shape of branch `def`, by its own keys alone: every required
566
- * prop is one of them, and each of them is a prop (or matches a prop pattern) of the branch. A
567
- * union: one of its branches; a branch that is not an object (nor an intersection of objects)
568
- * has any shape.
569
- */ function fits(def, value) {
570
- if (def.type.kind === "union") return def.type.items.some((item) => fits(item, value));
584
+ * The branches of union `items` that are not unions, a nested union's in its place, in declared
585
+ * order, so `(A | B) | C` and `A | B | C` rank alike: `items` itself when none is a union, else
586
+ * the same array for the same items (the discriminator over them is decided once).
587
+ */ function leavesOf(items) {
588
+ if (!items.some(isUnion)) return items;
589
+ const writes = require_user_text.typeWriteCount();
590
+ if (writes !== leavesStamp) {
591
+ leavesStamp = writes;
592
+ leavesCache = /* @__PURE__ */ new WeakMap();
593
+ }
594
+ let leaves = leavesCache.get(items);
595
+ if (!leaves) {
596
+ leaves = [];
597
+ collectLeaves(items, leaves);
598
+ leavesCache.set(items, leaves);
599
+ }
600
+ return leaves;
601
+ }
602
+ function isUnion(def) {
603
+ return def.type.kind === "union";
604
+ }
605
+ function collectLeaves(items, out) {
606
+ for (const item of items) if (isUnion(item)) collectLeaves(item.type.items, out);
607
+ else out.push(item);
608
+ }
609
+ /** Takes leaf branch `def` for `pick` when it takes `value` and scores above the best so far. */ function consider(def, value, pick) {
610
+ if (!takes(def, value)) return;
611
+ if (!pick.branch) {
612
+ pick.branch = def;
613
+ return;
614
+ }
615
+ if (pick.score === UNSCORED) {
616
+ pick.score = score(pick.branch, value, pick);
617
+ if (pick.score === BEST) return;
618
+ }
619
+ const s = score(def, value, pick);
620
+ if (s > pick.score) {
621
+ pick.branch = def;
622
+ pick.score = s;
623
+ }
624
+ }
625
+ /**
626
+ * The bits (see {@link HOLDS}) leaf branch `def`, which takes object (array) `value`, scores; once
627
+ * it cannot beat `pick.score`, any score not above it. Only an object branch can miss
628
+ * {@link DECLARED} or {@link COMPLETE}.
629
+ */ function score(def, value, pick) {
630
+ var _pick, _pick1;
571
631
  const objects = [];
572
- if (!objectsOf(def, objects)) return true;
573
- for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return false;
574
- return Object.keys(value).every((key) => objects.some((o) => o.props.has(key) || o.propsPatterns.some((p) => p.pattern.test(key))));
632
+ if (Array.isArray(value) || !objectsOf(def, objects)) return (holdsAll(def, value) ? HOLDS : 0) | 3;
633
+ const floor = pick.score;
634
+ let bits = BEST;
635
+ const keys = (_pick = pick).keys ?? (_pick.keys = Object.keys(value));
636
+ const values = (_pick1 = pick).values ?? (_pick1.values = keys.map((key) => value[key]));
637
+ for (let i = 0; i < keys.length; i++) {
638
+ const key = keys[i];
639
+ let declared = false;
640
+ for (const o of objects) {
641
+ const prop = propOf(o, key);
642
+ if (prop) {
643
+ declared = true;
644
+ if (bits & HOLDS && !holds(prop, values[i])) bits &= ~HOLDS;
645
+ }
646
+ }
647
+ if (!declared) bits &= ~DECLARED;
648
+ if (bits <= floor) return bits;
649
+ if (bits <= COMPLETE) break;
650
+ }
651
+ for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return bits & ~COMPLETE;
652
+ return bits;
653
+ }
654
+ /**
655
+ * Whether each prop (pattern prop) of branch `def` that object `value` has, or each item of array
656
+ * `value`, holds a value of its kind (see {@link holds}). Looks at `value`'s own keys and items
657
+ * only. `def` takes `value` (see {@link takes}).
658
+ */ function holdsAll(def, value) {
659
+ const type = def.type;
660
+ switch (type.kind) {
661
+ case "object": {
662
+ const o = type;
663
+ const record = value;
664
+ return Object.keys(record).every((key) => {
665
+ const prop = propOf(o, key);
666
+ return !prop || holds(prop, record[key]);
667
+ });
668
+ }
669
+ case "array": {
670
+ const of = type.of;
671
+ return value.every((item) => holds(of, item));
672
+ }
673
+ case "tuple": return type.items.every((item, i) => holds(item, value[i]));
674
+ case "union": return type.items.some((item) => takes(item, value) && holdsAll(item, value));
675
+ case "intersection": return type.items.every((item) => holdsAll(item, value));
676
+ default: return true;
677
+ }
678
+ }
679
+ /**
680
+ * Whether `input` is of the kind of prop (item) `def`, never looking inside it: a scalar that
681
+ * coerces to the prop's scalar type, or to one of its literals (a string after the normalizers on
682
+ * the literal's way, see `literalNodes`); a plain object for an object, an array for an array (of
683
+ * the tuple's length); `null` where the prop takes `null` (optional or a nullable type).
684
+ * `inherited`: the normalizer flags of the unions `def` is in.
685
+ */ function holds(def, input, inherited = 0) {
686
+ if (input === void 0) return true;
687
+ if (input === null) return def.optional === true || require_user_text.acceptsNull(def);
688
+ const type = def.type;
689
+ switch (type.kind) {
690
+ case "": {
691
+ const final = type;
692
+ return final.value === void 0 ? scalar(final.designType, input) !== NO_MATCH : coercesTo(def, flagsOf(def, inherited), input);
693
+ }
694
+ case "object": return isPlainObject$1(input);
695
+ case "array": return Array.isArray(input);
696
+ case "tuple": return Array.isArray(input) && input.length === type.items.length;
697
+ case "union": {
698
+ const flags = flagsOf(def, inherited);
699
+ return type.items.some((item) => holds(item, input, flags));
700
+ }
701
+ case "intersection": {
702
+ const flags = flagsOf(def, inherited);
703
+ return type.items.every((item) => holds(item, input, flags));
704
+ }
705
+ default: return false;
706
+ }
575
707
  }
576
708
  /** Collects the objects `def` is (an object, an intersection of objects); `false` for others. */ function objectsOf(def, out) {
577
709
  const type = def.type;
@@ -593,7 +725,7 @@ function scalar(designType, value) {
593
725
  case "": return coerce(def, value) !== NO_MATCH;
594
726
  case "object":
595
727
  if (!isPlainObject$1(value)) return false;
596
- for (const [key, prop] of type.props) if (Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
728
+ for (const [key, prop] of type.props) if (mayBeLiteral(prop) && Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
597
729
  return true;
598
730
  case "array": return Array.isArray(value);
599
731
  case "tuple": {
@@ -605,6 +737,10 @@ function scalar(designType, value) {
605
737
  default: return false;
606
738
  }
607
739
  }
740
+ /** Whether `def` can be a literal prop (see `literalNodes`): a literal or a union. */ function mayBeLiteral(def) {
741
+ const type = def.type;
742
+ return type.kind === "" ? type.value !== void 0 : type.kind === "union";
743
+ }
608
744
  /**
609
745
  * Whether prop (item) `def` of a union branch can hold `input`: anything, but a literal prop
610
746
  * (see `literalNodes`: `kind: 'cat'`, `kind: 'cat' | null`) only a value that coerces to one of
@@ -613,26 +749,23 @@ function scalar(designType, value) {
613
749
  */ function holdsLiteral(def, input) {
614
750
  if (input === void 0 || input === null) return true;
615
751
  const literals = literalNodes(def);
616
- return !literals || literals.some((literal) => coercesTo(literal, input));
752
+ return !literals || literals.some((literal) => coercesTo(literal.node, literal.flags, input));
617
753
  }
618
- /** Whether `input` coerces to the value of `literal` (see `holdsLiteral`). */ function coercesTo(literal, input) {
619
- const value = typeof input === "string" ? applyFlags(input, literal.flags) : input;
620
- return coerce(literal.node, value) !== NO_MATCH;
754
+ /**
755
+ * Whether `input` coerces to the value of literal `node`, a string after normalizer `flags` (see
756
+ * `holdsLiteral`).
757
+ */ function coercesTo(node, flags, input) {
758
+ return coerce(node, typeof input === "string" ? applyFlags(input, flags) : input) !== NO_MATCH;
621
759
  }
622
760
  /**
623
- * The branch of union `items` the discriminator of object `value` names: its literal itself,
624
- * else the one its value coerces to (`"2"` names `2`, see {@link coercesTo}); `undefined` when the
625
- * union has no discriminator or the value names no branch.
761
+ * The branch of union `items` whose discriminator literal is exactly the one object `value` holds
762
+ * (`"1"` names a `'1'` literal, not a `1`, though it makes a `1` branch a taker, see {@link takes});
763
+ * `undefined` when the union has no discriminator or no branch's literal is that value.
626
764
  */ function discriminatedBranch(items, value) {
627
765
  const disc = require_user_text.unionDiscriminator(items);
628
- if (disc === void 0) return;
629
- const tag = Object.hasOwn(value, disc.property) ? value[disc.property] : void 0;
630
- if (tag === void 0 || tag === null) return;
766
+ if (disc === void 0 || !Object.hasOwn(value, disc.property)) return;
767
+ const tag = value[disc.property];
631
768
  for (const [index, literal] of disc.branches) if (literal === tag) return items[index];
632
- for (const [index] of disc.branches) {
633
- const prop = items[index].type.props.get(disc.property);
634
- if (prop && holdsLiteral(prop, tag)) return items[index];
635
- }
636
769
  }
637
770
  /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
638
771
  const result = coerce(def, input);
package/dist/utils.d.ts CHANGED
@@ -671,12 +671,18 @@ declare function isAnnotatedTypeOfPrimitive(t: TAtscriptAnnotatedType): boolean;
671
671
  * backtracking). A scalar branch takes what it parses; an object (tuple)
672
672
  * branch takes a plain object (an array of its length) unless a literal
673
673
  * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
674
- * does not coerce to it, a string compared after the normalizers of the
675
- * literal and of the unions it is in. An object takes the branch its
676
- * discriminator names (as the validator does: the literal itself first, else
677
- * `"2"` names a `2` literal), else the first whose shape it has (required
678
- * props present, no undeclared key), else the first that takes it. When no
679
- * branch takes the value, it is returned untouched.
674
+ * does not coerce to it (`"2"` coerces to a `2` literal), a string compared
675
+ * after the normalizers of the literal and of the unions it is in. A scalar
676
+ * takes the first branch that takes it. An object or array takes the only
677
+ * branch that takes it, else the one it fits best, judged in this order
678
+ * (never looking deeper than its own keys and items): its props (items) hold
679
+ * values of their kinds (a string that parses for a `number` prop, `null`
680
+ * where `null` is allowed); it has no undeclared key; it has every required
681
+ * prop (the last two can be waived by `partial` / `unknownProps`, a wrong
682
+ * kind cannot); a nested union's branches count as the union's own. Ties go
683
+ * to the branch an object's discriminator names by the literal itself, then
684
+ * to declared order. When no branch takes the value, it is returned
685
+ * untouched.
680
686
  * - Objects recurse into props when the input is a plain object (covers
681
687
  * `@Query()` DTOs where every field arrives as a string), whatever their
682
688
  * literal props hold unless tried as a union branch.
package/dist/utils.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as VALIDATOR_KEYS, A as propAtChain, B as registerCompiledCheck, C as createAnnotatedTypeNode, D as isAnnotatedType, E as defineAnnotatedType, F as VALIDATOR_MESSAGES, G as $nr, H as jsonSchemaPattern, I as formatCodeOf, J as watchLayer, K as LayerMap, L as formatValidatorMessage, M as ValidatorError, N as unionDiscriminator, O as isAnnotatedTypeOfPrimitive, P as VALIDATOR_ERROR_CODES, Q as DECIMAL_RE, R as localizeErrors, S as annotate, T as createObjectTypeDef, U as statelessRegExp, V as detectDiscriminator, W as $ak, X as touched, Y as invalidateCompiledValidators, Z as typeWriteCount, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, et as arrayKeyProps, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, o as uniqueName, p as $ps, q as metaEmpty, r as registerUserText, s as $alias, t as $ut, tt as boundOf, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as messagesTranslator } from "./user-text-DZR5hfLa.mjs";
1
+ import { $ as DECIMAL_RE, A as propAtChain, B as acceptsNull$1, C as createAnnotatedTypeNode, D as isAnnotatedType, E as defineAnnotatedType, F as VALIDATOR_MESSAGES, G as $ak, H as detectDiscriminator, I as formatCodeOf, J as metaEmpty, K as $nr, L as formatValidatorMessage, M as ValidatorError, N as unionDiscriminator, O as isAnnotatedTypeOfPrimitive, P as VALIDATOR_ERROR_CODES, Q as typeWriteCount, R as localizeErrors, S as annotate, T as createObjectTypeDef, U as jsonSchemaPattern, V as registerCompiledCheck, W as statelessRegExp, X as invalidateCompiledValidators, Y as watchLayer, Z as touched, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, et as VALIDATOR_KEYS, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, nt as boundOf, o as uniqueName, p as $ps, q as LayerMap, r as registerUserText, s as $alias, t as $ut, tt as arrayKeyProps, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as messagesTranslator } from "./user-text-fz-TpY_H.mjs";
2
2
 
3
3
  //#region packages/typescript/src/runtime/copy-on-change.ts
4
4
  /**
@@ -16,13 +16,7 @@ import { $ as VALIDATOR_KEYS, A as propAtChain, B as registerCompiledCheck, C as
16
16
  for (let i = 0; i < keys.length; i++) {
17
17
  const key = keys[i];
18
18
  const input = value[key];
19
- let def = type.props.get(key);
20
- if (!def) {
21
- for (const { pattern, def: patternDef } of type.propsPatterns) if (pattern.test(key)) {
22
- def = patternDef;
23
- break;
24
- }
25
- }
19
+ const def = propOf(type, key);
26
20
  const mapped = def ? step(def, input, ctx) : input;
27
21
  if (mapped === NO_MATCH) return NO_MATCH;
28
22
  if (out) setOwn(out, key, mapped);
@@ -34,6 +28,11 @@ import { $ as VALIDATOR_KEYS, A as propAtChain, B as registerCompiledCheck, C as
34
28
  }
35
29
  return out ?? value;
36
30
  }
31
+ /** The def of prop `key` of object `type`: its declared prop, else the first pattern `key` matches. */ function propOf(type, key) {
32
+ const def = type.props.get(key);
33
+ if (def) return def;
34
+ for (const p of type.propsPatterns) if (p.pattern.test(key)) return p.def;
35
+ }
37
36
  /**
38
37
  * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
39
38
  * items). Copy-on-first-change, as {@link mapProps}.
@@ -453,12 +452,18 @@ function judgesFor(opts) {
453
452
  * backtracking). A scalar branch takes what it parses; an object (tuple)
454
453
  * branch takes a plain object (an array of its length) unless a literal
455
454
  * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
456
- * does not coerce to it, a string compared after the normalizers of the
457
- * literal and of the unions it is in. An object takes the branch its
458
- * discriminator names (as the validator does: the literal itself first, else
459
- * `"2"` names a `2` literal), else the first whose shape it has (required
460
- * props present, no undeclared key), else the first that takes it. When no
461
- * branch takes the value, it is returned untouched.
455
+ * does not coerce to it (`"2"` coerces to a `2` literal), a string compared
456
+ * after the normalizers of the literal and of the unions it is in. A scalar
457
+ * takes the first branch that takes it. An object or array takes the only
458
+ * branch that takes it, else the one it fits best, judged in this order
459
+ * (never looking deeper than its own keys and items): its props (items) hold
460
+ * values of their kinds (a string that parses for a `number` prop, `null`
461
+ * where `null` is allowed); it has no undeclared key; it has every required
462
+ * prop (the last two can be waived by `partial` / `unknownProps`, a wrong
463
+ * kind cannot); a nested union's branches count as the union's own. Ties go
464
+ * to the branch an object's discriminator names by the literal itself, then
465
+ * to declared order. When no branch takes the value, it is returned
466
+ * untouched.
462
467
  * - Objects recurse into props when the input is a plain object (covers
463
468
  * `@Query()` DTOs where every field arrives as a string), whatever their
464
469
  * literal props hold unless tried as a union branch.
@@ -543,34 +548,161 @@ function scalar(designType, value) {
543
548
  }
544
549
  }
545
550
  /**
546
- * The branch of union `items` that takes `value` (see {@link takes}): the one an object's
547
- * discriminator names; else, for an object, the first that takes it and whose shape it has (see
548
- * {@link fits}); else the first that takes it, in declared order (a partial patch); `undefined`
549
- * when none does.
551
+ * The score bits of a union branch for an object (array), most weighty first (see {@link score} and
552
+ * {@link coerceForType}): props (items) hold their kinds; no undeclared key; required props present.
553
+ */ const HOLDS = 4;
554
+ const DECLARED = 2;
555
+ const COMPLETE = 1;
556
+ const BEST = DECLARED | 5;
557
+ /** The score of a branch not scored yet (the only taker so far, see {@link TPick}). */ const UNSCORED = -1;
558
+ /**
559
+ * The branch of union `items` that takes `value` (see {@link takes}); `undefined` when none does.
560
+ * A scalar: the first taker. An object or array: of the leaf branches (see {@link leavesOf}), the
561
+ * only taker, else the best scored one (see {@link score}); the branch the discriminator names is
562
+ * tried first, then declared order, and a tie keeps the earlier one.
550
563
  */ function branchOf(items, value) {
551
- let first;
552
- if (isPlainObject$1(value)) {
553
- const named = discriminatedBranch(items, value);
554
- if (named && takes(named, value)) return named;
555
- for (const item of items) if (takes(item, value)) {
556
- if (fits(item, value)) return item;
557
- first ?? (first = item);
558
- }
559
- return first;
564
+ if (!isPlainObject$1(value) && !Array.isArray(value)) return items.find((item) => takes(item, value));
565
+ const leaves = leavesOf(items);
566
+ const pick = {
567
+ branch: void 0,
568
+ score: UNSCORED,
569
+ keys: void 0,
570
+ values: void 0
571
+ };
572
+ const named = Array.isArray(value) ? void 0 : discriminatedBranch(leaves, value);
573
+ if (named) consider(named, value, pick);
574
+ for (const leaf of leaves) {
575
+ if (pick.score === BEST) break;
576
+ if (leaf !== named) consider(leaf, value, pick);
560
577
  }
561
- return items.find((item) => takes(item, value));
578
+ return pick.branch;
562
579
  }
580
+ /** {@link leavesOf} by union items: valid until the next type tree write (see `typeWriteCount`). */ let leavesCache = /* @__PURE__ */ new WeakMap();
581
+ let leavesStamp = -1;
563
582
  /**
564
- * Whether object `value` has the shape of branch `def`, by its own keys alone: every required
565
- * prop is one of them, and each of them is a prop (or matches a prop pattern) of the branch. A
566
- * union: one of its branches; a branch that is not an object (nor an intersection of objects)
567
- * has any shape.
568
- */ function fits(def, value) {
569
- if (def.type.kind === "union") return def.type.items.some((item) => fits(item, value));
583
+ * The branches of union `items` that are not unions, a nested union's in its place, in declared
584
+ * order, so `(A | B) | C` and `A | B | C` rank alike: `items` itself when none is a union, else
585
+ * the same array for the same items (the discriminator over them is decided once).
586
+ */ function leavesOf(items) {
587
+ if (!items.some(isUnion)) return items;
588
+ const writes = typeWriteCount();
589
+ if (writes !== leavesStamp) {
590
+ leavesStamp = writes;
591
+ leavesCache = /* @__PURE__ */ new WeakMap();
592
+ }
593
+ let leaves = leavesCache.get(items);
594
+ if (!leaves) {
595
+ leaves = [];
596
+ collectLeaves(items, leaves);
597
+ leavesCache.set(items, leaves);
598
+ }
599
+ return leaves;
600
+ }
601
+ function isUnion(def) {
602
+ return def.type.kind === "union";
603
+ }
604
+ function collectLeaves(items, out) {
605
+ for (const item of items) if (isUnion(item)) collectLeaves(item.type.items, out);
606
+ else out.push(item);
607
+ }
608
+ /** Takes leaf branch `def` for `pick` when it takes `value` and scores above the best so far. */ function consider(def, value, pick) {
609
+ if (!takes(def, value)) return;
610
+ if (!pick.branch) {
611
+ pick.branch = def;
612
+ return;
613
+ }
614
+ if (pick.score === UNSCORED) {
615
+ pick.score = score(pick.branch, value, pick);
616
+ if (pick.score === BEST) return;
617
+ }
618
+ const s = score(def, value, pick);
619
+ if (s > pick.score) {
620
+ pick.branch = def;
621
+ pick.score = s;
622
+ }
623
+ }
624
+ /**
625
+ * The bits (see {@link HOLDS}) leaf branch `def`, which takes object (array) `value`, scores; once
626
+ * it cannot beat `pick.score`, any score not above it. Only an object branch can miss
627
+ * {@link DECLARED} or {@link COMPLETE}.
628
+ */ function score(def, value, pick) {
629
+ var _pick, _pick1;
570
630
  const objects = [];
571
- if (!objectsOf(def, objects)) return true;
572
- for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return false;
573
- return Object.keys(value).every((key) => objects.some((o) => o.props.has(key) || o.propsPatterns.some((p) => p.pattern.test(key))));
631
+ if (Array.isArray(value) || !objectsOf(def, objects)) return (holdsAll(def, value) ? HOLDS : 0) | 3;
632
+ const floor = pick.score;
633
+ let bits = BEST;
634
+ const keys = (_pick = pick).keys ?? (_pick.keys = Object.keys(value));
635
+ const values = (_pick1 = pick).values ?? (_pick1.values = keys.map((key) => value[key]));
636
+ for (let i = 0; i < keys.length; i++) {
637
+ const key = keys[i];
638
+ let declared = false;
639
+ for (const o of objects) {
640
+ const prop = propOf(o, key);
641
+ if (prop) {
642
+ declared = true;
643
+ if (bits & HOLDS && !holds(prop, values[i])) bits &= ~HOLDS;
644
+ }
645
+ }
646
+ if (!declared) bits &= ~DECLARED;
647
+ if (bits <= floor) return bits;
648
+ if (bits <= COMPLETE) break;
649
+ }
650
+ for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return bits & ~COMPLETE;
651
+ return bits;
652
+ }
653
+ /**
654
+ * Whether each prop (pattern prop) of branch `def` that object `value` has, or each item of array
655
+ * `value`, holds a value of its kind (see {@link holds}). Looks at `value`'s own keys and items
656
+ * only. `def` takes `value` (see {@link takes}).
657
+ */ function holdsAll(def, value) {
658
+ const type = def.type;
659
+ switch (type.kind) {
660
+ case "object": {
661
+ const o = type;
662
+ const record = value;
663
+ return Object.keys(record).every((key) => {
664
+ const prop = propOf(o, key);
665
+ return !prop || holds(prop, record[key]);
666
+ });
667
+ }
668
+ case "array": {
669
+ const of = type.of;
670
+ return value.every((item) => holds(of, item));
671
+ }
672
+ case "tuple": return type.items.every((item, i) => holds(item, value[i]));
673
+ case "union": return type.items.some((item) => takes(item, value) && holdsAll(item, value));
674
+ case "intersection": return type.items.every((item) => holdsAll(item, value));
675
+ default: return true;
676
+ }
677
+ }
678
+ /**
679
+ * Whether `input` is of the kind of prop (item) `def`, never looking inside it: a scalar that
680
+ * coerces to the prop's scalar type, or to one of its literals (a string after the normalizers on
681
+ * the literal's way, see `literalNodes`); a plain object for an object, an array for an array (of
682
+ * the tuple's length); `null` where the prop takes `null` (optional or a nullable type).
683
+ * `inherited`: the normalizer flags of the unions `def` is in.
684
+ */ function holds(def, input, inherited = 0) {
685
+ if (input === void 0) return true;
686
+ if (input === null) return def.optional === true || acceptsNull$1(def);
687
+ const type = def.type;
688
+ switch (type.kind) {
689
+ case "": {
690
+ const final = type;
691
+ return final.value === void 0 ? scalar(final.designType, input) !== NO_MATCH : coercesTo(def, flagsOf(def, inherited), input);
692
+ }
693
+ case "object": return isPlainObject$1(input);
694
+ case "array": return Array.isArray(input);
695
+ case "tuple": return Array.isArray(input) && input.length === type.items.length;
696
+ case "union": {
697
+ const flags = flagsOf(def, inherited);
698
+ return type.items.some((item) => holds(item, input, flags));
699
+ }
700
+ case "intersection": {
701
+ const flags = flagsOf(def, inherited);
702
+ return type.items.every((item) => holds(item, input, flags));
703
+ }
704
+ default: return false;
705
+ }
574
706
  }
575
707
  /** Collects the objects `def` is (an object, an intersection of objects); `false` for others. */ function objectsOf(def, out) {
576
708
  const type = def.type;
@@ -592,7 +724,7 @@ function scalar(designType, value) {
592
724
  case "": return coerce(def, value) !== NO_MATCH;
593
725
  case "object":
594
726
  if (!isPlainObject$1(value)) return false;
595
- for (const [key, prop] of type.props) if (Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
727
+ for (const [key, prop] of type.props) if (mayBeLiteral(prop) && Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
596
728
  return true;
597
729
  case "array": return Array.isArray(value);
598
730
  case "tuple": {
@@ -604,6 +736,10 @@ function scalar(designType, value) {
604
736
  default: return false;
605
737
  }
606
738
  }
739
+ /** Whether `def` can be a literal prop (see `literalNodes`): a literal or a union. */ function mayBeLiteral(def) {
740
+ const type = def.type;
741
+ return type.kind === "" ? type.value !== void 0 : type.kind === "union";
742
+ }
607
743
  /**
608
744
  * Whether prop (item) `def` of a union branch can hold `input`: anything, but a literal prop
609
745
  * (see `literalNodes`: `kind: 'cat'`, `kind: 'cat' | null`) only a value that coerces to one of
@@ -612,26 +748,23 @@ function scalar(designType, value) {
612
748
  */ function holdsLiteral(def, input) {
613
749
  if (input === void 0 || input === null) return true;
614
750
  const literals = literalNodes(def);
615
- return !literals || literals.some((literal) => coercesTo(literal, input));
751
+ return !literals || literals.some((literal) => coercesTo(literal.node, literal.flags, input));
616
752
  }
617
- /** Whether `input` coerces to the value of `literal` (see `holdsLiteral`). */ function coercesTo(literal, input) {
618
- const value = typeof input === "string" ? applyFlags(input, literal.flags) : input;
619
- return coerce(literal.node, value) !== NO_MATCH;
753
+ /**
754
+ * Whether `input` coerces to the value of literal `node`, a string after normalizer `flags` (see
755
+ * `holdsLiteral`).
756
+ */ function coercesTo(node, flags, input) {
757
+ return coerce(node, typeof input === "string" ? applyFlags(input, flags) : input) !== NO_MATCH;
620
758
  }
621
759
  /**
622
- * The branch of union `items` the discriminator of object `value` names: its literal itself,
623
- * else the one its value coerces to (`"2"` names `2`, see {@link coercesTo}); `undefined` when the
624
- * union has no discriminator or the value names no branch.
760
+ * The branch of union `items` whose discriminator literal is exactly the one object `value` holds
761
+ * (`"1"` names a `'1'` literal, not a `1`, though it makes a `1` branch a taker, see {@link takes});
762
+ * `undefined` when the union has no discriminator or no branch's literal is that value.
625
763
  */ function discriminatedBranch(items, value) {
626
764
  const disc = unionDiscriminator(items);
627
- if (disc === void 0) return;
628
- const tag = Object.hasOwn(value, disc.property) ? value[disc.property] : void 0;
629
- if (tag === void 0 || tag === null) return;
765
+ if (disc === void 0 || !Object.hasOwn(value, disc.property)) return;
766
+ const tag = value[disc.property];
630
767
  for (const [index, literal] of disc.branches) if (literal === tag) return items[index];
631
- for (const [index] of disc.branches) {
632
- const prop = items[index].type.props.get(disc.property);
633
- if (prop && holdsLiteral(prop, tag)) return items[index];
634
- }
635
768
  }
636
769
  /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
637
770
  const result = coerce(def, input);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/typescript",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "description": "Atscript: typescript-gen support.",
5
5
  "keywords": [
6
6
  "annotations",
@@ -63,18 +63,18 @@
63
63
  "./package.json": "./package.json"
64
64
  },
65
65
  "dependencies": {
66
- "@moostjs/event-cli": "^0.7.3",
67
- "moost": "^0.7.3"
66
+ "@moostjs/event-cli": "^0.7.4",
67
+ "moost": "^0.7.4"
68
68
  },
69
69
  "devDependencies": {
70
- "@atscript/db": "^0.1.170",
70
+ "@atscript/db": "^0.1.172",
71
71
  "@uniqu/core": "^0.2.1",
72
72
  "ajv": "8.20.0",
73
73
  "vitest": "4.1.12"
74
74
  },
75
75
  "peerDependencies": {
76
76
  "@atscript/db": "^0.1.159",
77
- "@atscript/core": "^0.2.8"
77
+ "@atscript/core": "^0.2.9"
78
78
  },
79
79
  "peerDependenciesMeta": {
80
80
  "@atscript/db": {