@atscript/typescript 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -227,7 +227,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
227
227
  * sees); otherwise the reads are live. A raw write the counter does not see (a node's map swapped,
228
228
  * `node.metadata = X`, or edited in place) must be followed by `invalidateCompiledValidators()`,
229
229
  * as compiled checks require (PERF-2).
230
- */ function _define_property$5(obj, key, value) {
230
+ */ function _define_property$6(obj, key, value) {
231
231
  if (key in obj) Object.defineProperty(obj, key, {
232
232
  value,
233
233
  enumerable: true,
@@ -437,7 +437,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
437
437
  for (const k of this.effectiveKeys()) cb.call(thisArg, this.get(k), k, this);
438
438
  }
439
439
  constructor(bases, reference = false, own) {
440
- super(own), _define_property$5(this, "b", void 0), _define_property$5(this, "r", void 0), _define_property$5(this, "f", void 0), _define_property$5(this, "w", void 0);
440
+ super(own), _define_property$6(this, "b", void 0), _define_property$6(this, "r", void 0), _define_property$6(this, "f", void 0), _define_property$6(this, "w", void 0);
441
441
  this.b = bases;
442
442
  this.r = reference;
443
443
  this.f = void 0;
@@ -1450,7 +1450,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1450
1450
  let result = null;
1451
1451
  for (const candidate of candidates) {
1452
1452
  const values = /* @__PURE__ */ new Set();
1453
- const indexMapping = {};
1453
+ const indexMapping = Object.create(null);
1454
1454
  let valid = true;
1455
1455
  for (let i = 0; i < items.length; i++) {
1456
1456
  const prop = items[i].type.props.get(candidate);
@@ -1904,7 +1904,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1904
1904
 
1905
1905
  //#endregion
1906
1906
  //#region packages/typescript/src/runtime/validator-fast-check.ts
1907
- function _define_property$4(obj, key, value) {
1907
+ function _define_property$5(obj, key, value) {
1908
1908
  if (key in obj) Object.defineProperty(obj, key, {
1909
1909
  value,
1910
1910
  enumerable: true,
@@ -2409,42 +2409,42 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2409
2409
  const plans = /* @__PURE__ */ new WeakMap();
2410
2410
  /** One shape for every plan, so plan field access stays monomorphic. */ let Plan = class Plan {
2411
2411
  constructor(def) {
2412
- _define_property$4(this, "def", void 0);
2413
- /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$4(this, "stamp", void 0);
2414
- /** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$4(this, "metaStamp", void 0);
2415
- _define_property$4(this, "op", void 0);
2416
- _define_property$4(this, "type", void 0);
2417
- _define_property$4(this, "optional", void 0);
2418
- _define_property$4(this, "metadata", void 0);
2419
- _define_property$4(this, "kind", void 0);
2420
- _define_property$4(this, "designType", void 0);
2421
- _define_property$4(this, "literal", void 0);
2422
- /** String plans: compiled `@expect.pattern` regexes by position (checked against the live entry). */ _define_property$4(this, "regexes", void 0);
2412
+ _define_property$5(this, "def", void 0);
2413
+ /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$5(this, "stamp", void 0);
2414
+ /** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$5(this, "metaStamp", void 0);
2415
+ _define_property$5(this, "op", void 0);
2416
+ _define_property$5(this, "type", void 0);
2417
+ _define_property$5(this, "optional", void 0);
2418
+ _define_property$5(this, "metadata", void 0);
2419
+ _define_property$5(this, "kind", void 0);
2420
+ _define_property$5(this, "designType", void 0);
2421
+ _define_property$5(this, "literal", void 0);
2422
+ /** String plans: compiled `@expect.pattern` regexes by position (checked against the live entry). */ _define_property$5(this, "regexes", void 0);
2423
2423
  /**
2424
2424
  * Annotation keys the node's check reads, and their values (`undefined` when absent):
2425
2425
  * string `meta.required, expect.minLength, maxLength, pattern`; number `expect.int, min,
2426
2426
  * max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`;
2427
2427
  * object `expect.minKeys, maxKeys`.
2428
- */ _define_property$4(this, "k0", void 0);
2429
- _define_property$4(this, "k1", void 0);
2430
- _define_property$4(this, "k2", void 0);
2431
- _define_property$4(this, "k3", void 0);
2432
- _define_property$4(this, "k4", void 0);
2433
- _define_property$4(this, "m0", void 0);
2434
- _define_property$4(this, "m1", void 0);
2435
- _define_property$4(this, "m2", void 0);
2436
- _define_property$4(this, "m3", void 0);
2437
- _define_property$4(this, "m4", void 0);
2438
- _define_property$4(this, "props", void 0);
2439
- _define_property$4(this, "propsPatterns", void 0);
2440
- _define_property$4(this, "keys", void 0);
2441
- /** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$4(this, "edges", void 0);
2442
- /** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$4(this, "byKey", void 0);
2443
- _define_property$4(this, "nodes", void 0);
2444
- _define_property$4(this, "children", void 0);
2445
- _define_property$4(this, "of", void 0);
2446
- _define_property$4(this, "ofPlan", void 0);
2447
- _define_property$4(this, "items", void 0);
2428
+ */ _define_property$5(this, "k0", void 0);
2429
+ _define_property$5(this, "k1", void 0);
2430
+ _define_property$5(this, "k2", void 0);
2431
+ _define_property$5(this, "k3", void 0);
2432
+ _define_property$5(this, "k4", void 0);
2433
+ _define_property$5(this, "m0", void 0);
2434
+ _define_property$5(this, "m1", void 0);
2435
+ _define_property$5(this, "m2", void 0);
2436
+ _define_property$5(this, "m3", void 0);
2437
+ _define_property$5(this, "m4", void 0);
2438
+ _define_property$5(this, "props", void 0);
2439
+ _define_property$5(this, "propsPatterns", void 0);
2440
+ _define_property$5(this, "keys", void 0);
2441
+ /** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$5(this, "edges", void 0);
2442
+ /** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$5(this, "byKey", void 0);
2443
+ _define_property$5(this, "nodes", void 0);
2444
+ _define_property$5(this, "children", void 0);
2445
+ _define_property$5(this, "of", void 0);
2446
+ _define_property$5(this, "ofPlan", void 0);
2447
+ _define_property$5(this, "items", void 0);
2448
2448
  this.def = def;
2449
2449
  this.stamp = -1;
2450
2450
  this.metaStamp = -1;
@@ -2880,7 +2880,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2880
2880
 
2881
2881
  //#endregion
2882
2882
  //#region packages/typescript/src/runtime/validator.ts
2883
- function _define_property$3(obj, key, value) {
2883
+ function _define_property$4(obj, key, value) {
2884
2884
  if (key in obj) Object.defineProperty(obj, key, {
2885
2885
  value,
2886
2886
  enumerable: true,
@@ -3615,17 +3615,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3615
3615
  return count;
3616
3616
  }
3617
3617
  constructor(def, opts) {
3618
- _define_property$3(this, "def", void 0);
3619
- _define_property$3(this, "opts", void 0);
3620
- _define_property$3(this, "hasPlugins", void 0);
3621
- _define_property$3(this, "hasReplace", void 0);
3622
- _define_property$3(this, "replaceCache", void 0);
3623
- /** Validation errors collected during the last {@link validate} call. */ _define_property$3(this, "errors", void 0);
3624
- _define_property$3(this, "stackErrors", void 0);
3625
- _define_property$3(this, "pathSegments", void 0);
3626
- _define_property$3(this, "depth", void 0);
3627
- _define_property$3(this, "limitExceeded", void 0);
3628
- _define_property$3(this, "context", void 0);
3618
+ _define_property$4(this, "def", void 0);
3619
+ _define_property$4(this, "opts", void 0);
3620
+ _define_property$4(this, "hasPlugins", void 0);
3621
+ _define_property$4(this, "hasReplace", void 0);
3622
+ _define_property$4(this, "replaceCache", void 0);
3623
+ /** Validation errors collected during the last {@link validate} call. */ _define_property$4(this, "errors", void 0);
3624
+ _define_property$4(this, "stackErrors", void 0);
3625
+ _define_property$4(this, "pathSegments", void 0);
3626
+ _define_property$4(this, "depth", void 0);
3627
+ _define_property$4(this, "limitExceeded", void 0);
3628
+ _define_property$4(this, "context", void 0);
3629
3629
  /**
3630
3630
  * The unions over objects this call decided inside union branches (value → outcomes). A union
3631
3631
  * nested in its own branches, many branches each, is reached again with the same value and path
@@ -3635,17 +3635,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3635
3635
  * never make it. It decides each such union once, with the same result and the same error object
3636
3636
  * (both depend only on these, the options and the input, which the walk never changes), and
3637
3637
  * records the same strips again.
3638
- */ _define_property$3(this, "unionMemo", void 0);
3639
- /** Union branches being checked (`> 0`: inside a union branch). */ _define_property$3(this, "unionDepth", void 0);
3640
- /** Failed branches of unions over objects inside union branches (see `unionMemo`). */ _define_property$3(this, "nestedFailures", void 0);
3641
- /** Wasted union branches since the outermost union was entered (see `unionMemo`). */ _define_property$3(this, "wasted", void 0);
3638
+ */ _define_property$4(this, "unionMemo", void 0);
3639
+ /** Union branches being checked (`> 0`: inside a union branch). */ _define_property$4(this, "unionDepth", void 0);
3640
+ /** Failed branches of unions over objects inside union branches (see `unionMemo`). */ _define_property$4(this, "nestedFailures", void 0);
3641
+ /** Wasted union branches since the outermost union was entered (see `unionMemo`). */ _define_property$4(this, "wasted", void 0);
3642
3642
  /**
3643
3643
  * `unknownProps: 'strip'`: the unknown keys of the objects that passed (`object, key, …`), in the
3644
3644
  * order the objects completed, then in key order. A rejected union branch, pattern property
3645
3645
  * attempt or plugin sub-validation drops what it recorded; the keys are deleted once the whole
3646
3646
  * call passes (`performStrips`).
3647
- */ _define_property$3(this, "strips", void 0);
3648
- /** The context the plugins get (see {@link pluginContext}), made on the first plugin call. */ _define_property$3(this, "pluginCtx", void 0);
3647
+ */ _define_property$4(this, "strips", void 0);
3648
+ /** The context the plugins get (see {@link pluginContext}), made on the first plugin call. */ _define_property$4(this, "pluginCtx", void 0);
3649
3649
  this.def = def;
3650
3650
  this.errors = [];
3651
3651
  this.stackErrors = [];
@@ -3672,8 +3672,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3672
3672
  return typeof annotation === "object" && annotation !== null ? annotation.message || void 0 : void 0;
3673
3673
  }
3674
3674
  /**
3675
- * Decided discriminators, by union `items` (reported errors only: a union's discriminator is
3676
- * looked for once its value failed). An entry is reused while the items, their type defs and the
3675
+ * Decided discriminators, by union `items` (the validator's reported errors, the branch
3676
+ * `normalizeForType` takes). An entry is reused while the items, their type defs and the
3677
3677
  * discriminator props are the same objects.
3678
3678
  */ const discCache = /* @__PURE__ */ new WeakMap();
3679
3679
  /**
@@ -3762,7 +3762,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3762
3762
  }
3763
3763
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */ var ValidatorError = class extends Error {
3764
3764
  constructor(errors) {
3765
- super(`${errors[0].path ? errors[0].path + ": " : ""}${errors[0].message}`), _define_property$3(this, "errors", void 0), _define_property$3(this, "name", void 0), this.errors = errors, this.name = "Validation Error";
3765
+ super(`${errors[0].path ? errors[0].path + ": " : ""}${errors[0].message}`), _define_property$4(this, "errors", void 0), _define_property$4(this, "name", void 0), this.errors = errors, this.name = "Validation Error";
3766
3766
  }
3767
3767
  };
3768
3768
 
@@ -3996,12 +3996,93 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3996
3996
  }
3997
3997
 
3998
3998
  //#endregion
3999
- //#region packages/typescript/src/runtime/coerce.ts
3999
+ //#region packages/typescript/src/runtime/copy-on-change.ts
4000
4000
  /**
4001
- * Internal sentinel returned when a value cannot be coerced to a type node.
4002
- * Drives union branch selection without allocating per-node result objects.
4003
- */ const NO_MATCH = Symbol("atscript.coerce.no-match");
4001
+ * Internal sentinel: the value cannot be taken by a type node (drives union branch selection in
4002
+ * `coerce.ts` and `normalize.ts`). A {@link mapProps} step returns it to reject the whole object.
4003
+ */ const NO_MATCH = Symbol("atscript.no-match");
4004
4004
  /**
4005
+ * Maps the props of plain object `value` with `step` (props without a def — declared or pattern —
4006
+ * are kept as they are). Copy-on-first-change: allocates the output only when some prop changed,
4007
+ * else returns `value`; an own `__proto__` key stays an own key (never the output's prototype).
4008
+ * NO_MATCH when a step returns it.
4009
+ */ function mapProps(type, value, step, ctx) {
4010
+ const keys = Object.keys(value);
4011
+ let out;
4012
+ for (let i = 0; i < keys.length; i++) {
4013
+ const key = keys[i];
4014
+ const input = value[key];
4015
+ let def = type.props.get(key);
4016
+ if (!def) {
4017
+ for (const { pattern, def: patternDef } of type.propsPatterns) if (pattern.test(key)) {
4018
+ def = patternDef;
4019
+ break;
4020
+ }
4021
+ }
4022
+ const mapped = def ? step(def, input, ctx) : input;
4023
+ if (mapped === NO_MATCH) return NO_MATCH;
4024
+ if (out) setOwn(out, key, mapped);
4025
+ else if (mapped !== input) {
4026
+ out = {};
4027
+ for (let j = 0; j < i; j++) setOwn(out, keys[j], value[keys[j]]);
4028
+ setOwn(out, key, mapped);
4029
+ }
4030
+ }
4031
+ return out ?? value;
4032
+ }
4033
+ /**
4034
+ * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
4035
+ * items). Copy-on-first-change, as {@link mapProps}.
4036
+ */ function mapItems(value, of, step, ctx) {
4037
+ return mapList(value, (input, i) => step(Array.isArray(of) ? of[i] : of, input, ctx));
4038
+ }
4039
+ /** Maps the items of `list` with `step`. Copy-on-first-change: `list` itself when none changed. */ function mapList(list, step) {
4040
+ let out;
4041
+ for (let i = 0; i < list.length; i++) {
4042
+ const mapped = step(list[i], i);
4043
+ if (out) out.push(mapped);
4044
+ else if (mapped !== list[i]) {
4045
+ out = list.slice(0, i);
4046
+ out.push(mapped);
4047
+ }
4048
+ }
4049
+ return out ?? list;
4050
+ }
4051
+ /**
4052
+ * Maps the own values of JSON object `obj` with `step`. Copy-on-first-change: `obj` itself when
4053
+ * none changed; an own `__proto__` key stays an own key.
4054
+ */ function mapEntries(obj, step) {
4055
+ let out;
4056
+ for (const key of Object.keys(obj)) {
4057
+ const mapped = step(key, obj[key]);
4058
+ if (mapped !== obj[key]) {
4059
+ out ?? (out = { ...obj });
4060
+ setOwn(out, key, mapped);
4061
+ }
4062
+ }
4063
+ return out ?? obj;
4064
+ }
4065
+ /** Whether `value` is a plain object (`{}` or prototype-less): class instances are not. */ function isPlainObject$1(value) {
4066
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4067
+ const proto = Object.getPrototypeOf(value);
4068
+ return proto === Object.prototype || proto === null;
4069
+ }
4070
+ /**
4071
+ * Sets own property `key` of `out`: `__proto__` as an own data property (an assignment would set
4072
+ * the object's prototype instead — input parsed from JSON may carry such a key).
4073
+ */ function setOwn(out, key, value) {
4074
+ if (key === "__proto__") Object.defineProperty(out, key, {
4075
+ value,
4076
+ writable: true,
4077
+ enumerable: true,
4078
+ configurable: true
4079
+ });
4080
+ else out[key] = value;
4081
+ }
4082
+
4083
+ //#endregion
4084
+ //#region packages/typescript/src/runtime/coerce.ts
4085
+ /**
4005
4086
  * Coerces string-transport input (route params, query strings) toward the
4006
4087
  * scalar shapes an annotated type expects.
4007
4088
  *
@@ -4050,11 +4131,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4050
4131
  }
4051
4132
  case "object":
4052
4133
  if (!isPlainObject$1(value)) return NO_MATCH;
4053
- return coerceProps(def, value);
4054
- case "array": return Array.isArray(value) ? coerceItems(value, type.of) : NO_MATCH;
4134
+ return mapProps(type, value, coerceChild, void 0);
4135
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
4055
4136
  case "tuple": {
4056
4137
  const items = type.items;
4057
- return Array.isArray(value) && value.length === items.length ? coerceItems(value, void 0, items) : NO_MATCH;
4138
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
4058
4139
  }
4059
4140
  case "union":
4060
4141
  for (const item of type.items) {
@@ -4099,57 +4180,289 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4099
4180
  default: return NO_MATCH;
4100
4181
  }
4101
4182
  }
4183
+ /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
4184
+ const result = coerce(def, input);
4185
+ return result === NO_MATCH ? input : result;
4186
+ }
4187
+
4188
+ //#endregion
4189
+ //#region packages/typescript/src/runtime/normalize.ts
4190
+ const TRIM = 1;
4191
+ const LOWERCASE = 2;
4192
+ const UPPERCASE = 4;
4102
4193
  /**
4103
- * Coerces the props of a plain object. Copy-on-first-change: allocates the
4104
- * output object only when some prop actually coerced, else returns the input.
4105
- */ function coerceProps(def, value) {
4106
- const keys = Object.keys(value);
4107
- let out;
4108
- for (let i = 0; i < keys.length; i++) {
4109
- const key = keys[i];
4110
- const input = value[key];
4111
- let propDef = def.type.props.get(key);
4112
- if (!propDef) {
4113
- for (const { pattern, def: patternDef } of def.type.propsPatterns) if (pattern.test(key)) {
4114
- propDef = patternDef;
4115
- break;
4194
+ * Whether each node's subtree has normalizers: valid until the next metadata write or
4195
+ * `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
4196
+ */ let reach = /* @__PURE__ */ new WeakMap();
4197
+ let stampWrites = -1;
4198
+ let stampEpoch = -1;
4199
+ /**
4200
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
4201
+ * `@normalize.lowercase` and `@normalize.uppercase`.
4202
+ *
4203
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
4204
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
4205
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
4206
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
4207
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
4208
+ * uppercase. Other values (including class instances such as `Date`) and strings without
4209
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
4210
+ *
4211
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
4212
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
4213
+ * value is left as it is. A union normalizes a value only when the result does not depend on
4214
+ * which branch takes it:
4215
+ * - an object union with a discriminator (a literal prop every object branch requires, see
4216
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
4217
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
4218
+ * only when the normalized string equals its literal): when they all give the same result it
4219
+ * is used; when they differ, the branches whose result their own validator accepts (default
4220
+ * options) are kept, and the result is used when they agree; else the value is returned
4221
+ * untouched (ambiguous).
4222
+ *
4223
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
4224
+ *
4225
+ * @example
4226
+ * ```ts
4227
+ * // @normalize.trim @normalize.lowercase email: string.email
4228
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
4229
+ * ```
4230
+ */ function normalizeForType(def, value) {
4231
+ const writes = metadataWriteCount();
4232
+ const epoch = currentEpoch();
4233
+ if (writes !== stampWrites || epoch !== stampEpoch) {
4234
+ stampWrites = writes;
4235
+ stampEpoch = epoch;
4236
+ reach = /* @__PURE__ */ new WeakMap();
4237
+ }
4238
+ if (!hasNormalizers(def)) return value;
4239
+ const result = normalize(def, value, 0, /* @__PURE__ */ new Map());
4240
+ return result === NO_MATCH ? value : result;
4241
+ }
4242
+ /** The nodes `def`'s value walk can enter (props, pattern props, items, elements). */ function childrenOf(def) {
4243
+ const type = def.type;
4244
+ switch (type.kind) {
4245
+ case "object": {
4246
+ const t = type;
4247
+ const out = [...t.props.values()];
4248
+ for (const p of t.propsPatterns) out.push(p.def);
4249
+ return out;
4250
+ }
4251
+ case "array": return [type.of];
4252
+ case "union":
4253
+ case "intersection":
4254
+ case "tuple": return type.items;
4255
+ default: return [];
4256
+ }
4257
+ }
4258
+ /**
4259
+ * Whether `def` or a node its walk reaches has normalizers. Answers (and caches) every node
4260
+ * reached, recursive types included: collects the reached nodes with their parents, then marks
4261
+ * the nodes with normalizers and, back along the parents, every node that reaches one.
4262
+ */ function hasNormalizers(def) {
4263
+ const known = reach.get(def);
4264
+ if (known !== void 0) return known;
4265
+ const parents = new Map([[def, []]]);
4266
+ const marked = [];
4267
+ const todo = [def];
4268
+ while (todo.length > 0) {
4269
+ const node = todo.pop();
4270
+ if (flagsOf(node, 0) !== 0) marked.push(node);
4271
+ for (const child of childrenOf(node)) {
4272
+ const cached = reach.get(child);
4273
+ if (cached !== void 0) {
4274
+ if (cached) marked.push(node);
4275
+ continue;
4276
+ }
4277
+ let of = parents.get(child);
4278
+ if (!of) {
4279
+ parents.set(child, of = []);
4280
+ todo.push(child);
4116
4281
  }
4282
+ of.push(node);
4117
4283
  }
4118
- let coerced = input;
4119
- if (propDef) {
4120
- const result = coerce(propDef, input);
4121
- if (result !== NO_MATCH) coerced = result;
4284
+ }
4285
+ for (const node of parents.keys()) reach.set(node, false);
4286
+ while (marked.length > 0) {
4287
+ const node = marked.pop();
4288
+ if (!reach.get(node)) {
4289
+ reach.set(node, true);
4290
+ marked.push(...parents.get(node));
4122
4291
  }
4123
- if (out) out[key] = coerced;
4124
- else if (coerced !== input) {
4125
- out = {};
4126
- for (let j = 0; j < i; j++) out[keys[j]] = value[keys[j]];
4127
- out[key] = coerced;
4292
+ }
4293
+ return reach.get(def);
4294
+ }
4295
+ /** The normalizer flags of `def`, on top of `inherited` (a union's, for its branches). */ function flagsOf(def, inherited) {
4296
+ const meta = def.metadata;
4297
+ if (metaEmpty(meta)) return inherited;
4298
+ let flags = inherited;
4299
+ if (meta.get("normalize.trim")) flags |= TRIM;
4300
+ if (meta.get("normalize.lowercase")) flags |= LOWERCASE;
4301
+ if (meta.get("normalize.uppercase")) flags |= UPPERCASE;
4302
+ return flags;
4303
+ }
4304
+ function applyFlags(value, flags) {
4305
+ let out = value;
4306
+ if (flags & TRIM) out = out.trim();
4307
+ if (flags & LOWERCASE) out = out.toLowerCase();
4308
+ if (flags & UPPERCASE) out = out.toUpperCase();
4309
+ return out;
4310
+ }
4311
+ /**
4312
+ * The normalized value, or NO_MATCH when `def` cannot take it (its kind does not fit the value).
4313
+ * `inherited`: the normalizer flags of the unions / intersections `def` is a member of.
4314
+ *
4315
+ * Objects and unions are memoized per call by input object: a recursive union without a
4316
+ * discriminator is tried for every branch at every level, which without it is exponential in
4317
+ * the depth of the value.
4318
+ */ function normalize(def, value, inherited, memo) {
4319
+ if (value === void 0 || value === null) return value;
4320
+ if (inherited === 0 && !hasNormalizers(def)) return takes(def, value) ? value : NO_MATCH;
4321
+ const type = def.type;
4322
+ switch (type.kind) {
4323
+ case "": {
4324
+ const out = typeof value === "string" && type.designType === "string" ? applyFlags(value, flagsOf(def, inherited)) : value;
4325
+ return takes(def, out) ? out : NO_MATCH;
4326
+ }
4327
+ case "object": {
4328
+ if (!isPlainObject$1(value)) return NO_MATCH;
4329
+ const entries = entriesOf(memo, value);
4330
+ return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, memo));
4128
4331
  }
4332
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, memo) : NO_MATCH;
4333
+ case "tuple": {
4334
+ const items = type.items;
4335
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, memo) : NO_MATCH;
4336
+ }
4337
+ case "union": {
4338
+ const flags = flagsOf(def, inherited);
4339
+ const items = type.items;
4340
+ if (typeof value !== "object") return normalizeUnion(items, value, flags, memo);
4341
+ const entries = entriesOf(memo, value);
4342
+ return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, memo));
4343
+ }
4344
+ case "intersection": {
4345
+ const flags = flagsOf(def, inherited);
4346
+ let current = value;
4347
+ for (const item of type.items) {
4348
+ const result = normalize(item, current, flags, memo);
4349
+ if (result === NO_MATCH) return NO_MATCH;
4350
+ current = result;
4351
+ }
4352
+ return current;
4353
+ }
4354
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
4129
4355
  }
4130
- return out ?? value;
4356
+ }
4357
+ /** The memoized results for input object `value` (see {@link normalize}). */ function entriesOf(memo, value) {
4358
+ let entries = memo.get(value);
4359
+ if (!entries) {
4360
+ entries = [];
4361
+ memo.set(value, entries);
4362
+ }
4363
+ return entries;
4364
+ }
4365
+ /** The memoized result for `type` and `flags`, `undefined` when none. */ function recall(entries, type, flags) {
4366
+ for (const [t, f, result] of entries) if (t === type && f === flags) return result;
4367
+ }
4368
+ /** Memoizes `result` for `type` and `flags` and returns it. */ function remember(entries, type, flags, result) {
4369
+ entries.push([
4370
+ type,
4371
+ flags,
4372
+ result
4373
+ ]);
4374
+ return result;
4375
+ }
4376
+ /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, memo) {
4377
+ if (!hasNormalizers(def)) return input;
4378
+ const result = normalize(def, input, 0, memo);
4379
+ return result === NO_MATCH ? input : result;
4131
4380
  }
4132
4381
  /**
4133
- * Coerces array/tuple items against `of` (arrays) or `items[i]` (tuples).
4134
- * Copy-on-first-change, same as {@link coerceProps}.
4135
- */ function coerceItems(value, of, items) {
4136
- let out;
4137
- for (let i = 0; i < value.length; i++) {
4138
- const input = value[i];
4139
- const result = coerce(of ?? items[i], input);
4140
- const coerced = result === NO_MATCH ? input : result;
4141
- if (out) out.push(coerced);
4142
- else if (coerced !== input) {
4143
- out = value.slice(0, i);
4144
- out.push(coerced);
4382
+ * A prop: as {@link normalizeItem}, but NO_MATCH (the object is not this type) when a literal prop
4383
+ * (`kind: 'cat'`) holds another value.
4384
+ */ function normalizeProp(def, input, memo) {
4385
+ const out = normalizeItem(def, input, memo);
4386
+ if (out === input && def.type.kind === "" && def.type.value !== void 0 && input !== def.type.value && input !== void 0 && input !== null) return NO_MATCH;
4387
+ return out;
4388
+ }
4389
+ /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes(def, value) {
4390
+ const type = def.type;
4391
+ switch (type.kind) {
4392
+ case "": {
4393
+ const final = type;
4394
+ switch (final.designType) {
4395
+ case "string":
4396
+ case "number":
4397
+ case "boolean": return typeof value === final.designType && (final.value === void 0 || value === final.value);
4398
+ case "decimal": return typeof value === "string";
4399
+ case "object": return typeof value === "object";
4400
+ case "any":
4401
+ case "phantom": return true;
4402
+ default: return false;
4403
+ }
4145
4404
  }
4405
+ case "object": return isPlainObject$1(value);
4406
+ case "array": return Array.isArray(value);
4407
+ case "tuple": return Array.isArray(value) && value.length === type.items.length;
4408
+ case "union": return type.items.some((item) => takes(item, value));
4409
+ case "intersection": return type.items.every((item) => takes(item, value));
4410
+ default: return false;
4146
4411
  }
4147
- return out ?? value;
4148
4412
  }
4149
- function isPlainObject$1(value) {
4150
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4151
- const proto = Object.getPrototypeOf(value);
4152
- return proto === Object.prototype || proto === null;
4413
+ /**
4414
+ * A union: the branch a discriminator names, else the one result every branch that can take
4415
+ * the value agrees on — or, when they differ, the one result of the branches whose validator
4416
+ * accepts their result (NO_MATCH when none can take the value or it stays ambiguous).
4417
+ */ function normalizeUnion(items, value, flags, memo) {
4418
+ if (isPlainObject$1(value)) {
4419
+ const disc = unionDiscriminator(items);
4420
+ if (disc) {
4421
+ const tag = value[disc.property];
4422
+ for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, memo);
4423
+ }
4424
+ }
4425
+ let first = NO_MATCH;
4426
+ let firstItem;
4427
+ let rest;
4428
+ for (const item of items) {
4429
+ const out = normalize(item, value, flags, memo);
4430
+ if (out === NO_MATCH) continue;
4431
+ if (first === NO_MATCH) {
4432
+ first = out;
4433
+ firstItem = item;
4434
+ } else (rest ?? (rest = [])).push([item, out]);
4435
+ }
4436
+ if (!rest || rest.every(([, out]) => sameValue(out, first))) return first;
4437
+ rest.unshift([firstItem, first]);
4438
+ let accepted = NO_MATCH;
4439
+ for (const [item, out] of rest) {
4440
+ if (!branchValidator(item).validate(out, true)) continue;
4441
+ if (accepted === NO_MATCH) accepted = out;
4442
+ else if (!sameValue(accepted, out)) return NO_MATCH;
4443
+ }
4444
+ return accepted;
4445
+ }
4446
+ /**
4447
+ * Each union branch's validator (default options; one error is enough to reject a result),
4448
+ * judging its own normalized result.
4449
+ */ const branchValidators = /* @__PURE__ */ new WeakMap();
4450
+ function branchValidator(def) {
4451
+ let validator = branchValidators.get(def);
4452
+ if (!validator) {
4453
+ validator = new Validator(def, { errorLimit: 1 });
4454
+ branchValidators.set(def, validator);
4455
+ }
4456
+ return validator;
4457
+ }
4458
+ /** Whether two results of the same input are equal (shared, untouched parts are identical). */ function sameValue(a, b) {
4459
+ if (a === b) return true;
4460
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
4461
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
4462
+ const keys = Object.keys(a);
4463
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
4464
+ }
4465
+ return false;
4153
4466
  }
4154
4467
 
4155
4468
  //#endregion
@@ -4212,7 +4525,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4212
4525
 
4213
4526
  //#endregion
4214
4527
  //#region packages/typescript/src/runtime/json-schema.ts
4215
- /**
4528
+ /** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
4529
+ /**
4216
4530
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
4217
4531
  *
4218
4532
  * Translates the atscript type structure and validation metadata
@@ -4227,8 +4541,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4227
4541
  * ```
4228
4542
  *
4229
4543
  * @param type - The annotated type to convert.
4544
+ * @param opts - {@link TJsonSchemaOptions}.
4230
4545
  * @returns A JSON Schema object.
4231
- */ function buildJsonSchema(type) {
4546
+ */ function buildJsonSchema(type, opts) {
4547
+ const closed = opts?.closed === true;
4548
+ const annotations = opts?.annotations !== false;
4549
+ const enums = opts?.enums !== false;
4232
4550
  /**
4233
4551
  * `$defs` entries by type def (identity): named objects (always extracted) and types found
4234
4552
  * recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
@@ -4256,8 +4574,35 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4256
4574
  ...schema,
4257
4575
  type: [schema.type, "null"]
4258
4576
  };
4259
- if (Object.keys(schema).length === 1 && Array.isArray(schema.anyOf)) return { anyOf: [...schema.anyOf, { type: "null" }] };
4260
- return { anyOf: [schema, { type: "null" }] };
4577
+ const notes = {};
4578
+ let body = schema;
4579
+ for (const [, keyword] of ANNOTATION_KEYWORDS) if (body[keyword] !== void 0) {
4580
+ if (body === schema) body = { ...schema };
4581
+ notes[keyword] = body[keyword];
4582
+ delete body[keyword];
4583
+ }
4584
+ if (body !== schema && Object.keys(body).length === 1 && body.allOf?.length === 1) body = body.allOf[0];
4585
+ if (Object.keys(body).length === 1 && Array.isArray(body.anyOf)) return {
4586
+ anyOf: [...body.anyOf, { type: "null" }],
4587
+ ...notes
4588
+ };
4589
+ return {
4590
+ anyOf: [body, { type: "null" }],
4591
+ ...notes
4592
+ };
4593
+ };
4594
+ /**
4595
+ * A use of a `$defs` entry: `schema` (its `$ref`) with what the use adds to the entry (built
4596
+ * from `own`, see `ownDef`): its key counts, and its title / description when they differ
4597
+ * from the entry's — beside the reference, in an `allOf`.
4598
+ */ const useOf = (schema, def, own, keyCounts = false) => {
4599
+ const extra = {};
4600
+ if (annotations) applyAnnotationKeywords(extra, def.metadata, own?.metadata);
4601
+ if (keyCounts) applyKeyCounts(extra, def.metadata);
4602
+ return Object.keys(extra).length > 0 ? {
4603
+ allOf: [schema],
4604
+ ...extra
4605
+ } : schema;
4261
4606
  };
4262
4607
  /**
4263
4608
  * Non-primitive type defs being built: `true` once re-entered (recursive). A named object
@@ -4294,7 +4639,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4294
4639
  * A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
4295
4640
  * them instead, its recursion referring to the shared definition.
4296
4641
  */ function* refTo(typeDef, def, own) {
4297
- if (def === own || inlining.has(def) || sameConstraints(def, own)) return ref(typeDef);
4642
+ if (def === own || inlining.has(def) || sameConstraints(def, own)) return useOf(ref(typeDef), def, own);
4298
4643
  inlining.add(def);
4299
4644
  const schema = yield buildDef(def);
4300
4645
  inlining.delete(def);
@@ -4324,6 +4669,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4324
4669
  for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
4325
4670
  schema.patternProperties = patternProperties(built, Object.keys(properties));
4326
4671
  }
4672
+ if (closed) schema.additionalProperties = false;
4327
4673
  return schema;
4328
4674
  }
4329
4675
  /** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
@@ -4333,14 +4679,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4333
4679
  const atRoot = def === type && !rootEntered;
4334
4680
  rootEntered = true;
4335
4681
  if (def.id && typeDef.kind === "object" && !atRoot) {
4682
+ const own = annotations ? ownDef(def, type) ?? def : void 0;
4336
4683
  if (!defs.has(typeDef)) {
4337
4684
  reserve(typeDef, def.id, true);
4338
4685
  const outer = building;
4339
4686
  building = /* @__PURE__ */ new Map();
4340
- defs.get(typeDef).schema = yield buildObject(def);
4687
+ const entry = yield buildObject(def);
4688
+ if (own) applyAnnotationKeywords(entry, own.metadata);
4689
+ defs.get(typeDef).schema = entry;
4341
4690
  building = outer;
4342
4691
  }
4343
- return withKeyCounts(ref(typeDef), def.metadata);
4692
+ return useOf(ref(typeDef), def, own, true);
4344
4693
  }
4345
4694
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
4346
4695
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -4369,7 +4718,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4369
4718
  const own = ownOf(def);
4370
4719
  const same = def === own || sameConstraints(def, own);
4371
4720
  defs.get(typeDef).schema = same ? schema : yield buildDef(own);
4372
- return def === type || !same ? schema : ref(typeDef);
4721
+ return def === type || !same ? schema : useOf(ref(typeDef), def, own);
4373
4722
  }
4374
4723
  /** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
4375
4724
  const ownOf = (def) => {
@@ -4380,7 +4729,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4380
4729
  }
4381
4730
  return own;
4382
4731
  };
4383
- /** The schema of `def`'s own type (see {@link build}). */ function* buildDef(def) {
4732
+ /** The schema of `def`'s own type (see {@link build}), with its title / description. */ function* buildDef(def) {
4733
+ const schema = yield buildBody(def);
4734
+ if (annotations) applyAnnotationKeywords(schema, def.metadata);
4735
+ return schema;
4736
+ }
4737
+ /** The schema of `def`'s own type, without its title / description (see {@link buildDef}). */ function* buildBody(def) {
4384
4738
  const meta = def.metadata;
4385
4739
  const all = function* (items) {
4386
4740
  const out = [];
@@ -4435,7 +4789,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4435
4789
  };
4436
4790
  } else {
4437
4791
  if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
4438
- schema = { anyOf: built };
4792
+ schema = enums && enumOf(built, refSchemas) || { anyOf: built };
4439
4793
  }
4440
4794
  applyKeyCounts(schema, meta);
4441
4795
  return schema;
@@ -4688,13 +5042,41 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4688
5042
  const maxKeys = meta.get("expect.maxKeys");
4689
5043
  if (maxKeys !== void 0) schema.maxProperties = boundOf(maxKeys, "count");
4690
5044
  }
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;
5045
+ /** `@meta.label` → `title`, `@meta.description` → `description` (see `annotations`). */ function applyAnnotationKeywords(schema, meta, except) {
5046
+ if (metaEmpty(meta)) return;
5047
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) {
5048
+ const value = meta.get(key);
5049
+ if (value !== void 0 && value !== except?.get(key)) schema[keyword] = value;
5050
+ }
5051
+ }
5052
+ /**
5053
+ * The `{ type, enum }` schema of a union whose members are all literals (`const`, a nested
5054
+ * union of literals' `enum`, or `null`), at least one of them not `null`; `undefined` for any
5055
+ * other union (a member with other keywords — a title, a constraint — keeps the `anyOf`).
5056
+ */ function enumOf(members, refs) {
5057
+ const values = [];
5058
+ const types = [];
5059
+ let literal = false;
5060
+ for (const member of members) {
5061
+ if (refs.has(member)) return;
5062
+ const keys = Object.keys(member);
5063
+ let memberValues;
5064
+ if ("const" in member && keys.every((k) => k === "const" || k === "type")) {
5065
+ memberValues = [member.const];
5066
+ literal = true;
5067
+ } else if (Array.isArray(member.enum) && keys.every((k) => k === "enum" || k === "type")) {
5068
+ memberValues = member.enum;
5069
+ literal = true;
5070
+ } else if (member.type === "null" && keys.length === 1) memberValues = [null];
5071
+ else return;
5072
+ for (const value of memberValues) if (!values.includes(value)) values.push(value);
5073
+ for (const t of [member.type ?? []].flat()) if (!types.includes(t)) types.push(t);
5074
+ }
5075
+ if (!literal) return;
5076
+ const schema = {};
5077
+ if (types.length > 0) schema.type = types.length === 1 ? types[0] : types;
5078
+ schema.enum = values;
5079
+ return schema;
4698
5080
  }
4699
5081
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
4700
5082
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
@@ -4748,7 +5130,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4748
5130
  applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
4749
5131
  continue;
4750
5132
  }
4751
- if (member.const !== void 0) continue;
5133
+ if (member.const !== void 0 || member.enum !== void 0) continue;
4752
5134
  const type = member.type;
4753
5135
  const extra = { type };
4754
5136
  if (type === "array") {
@@ -4791,7 +5173,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4791
5173
  */ function fromJsonSchema(schema) {
4792
5174
  const defsSource = schema.$defs || schema.definitions || {};
4793
5175
  const resolved = /* @__PURE__ */ new Map();
4794
- const convert = (s) => {
5176
+ /** `title` → `@meta.label`, `description` → `@meta.description` (not on a shared `$ref`). */ const convert = (s) => {
5177
+ const type = convertNode(s);
5178
+ if (s && !s.$ref) {
5179
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) if (typeof s[keyword] === "string") annotate(type.metadata, key, s[keyword]);
5180
+ }
5181
+ return type;
5182
+ };
5183
+ const convertNode = (s) => {
4795
5184
  if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
4796
5185
  if (s.$ref) {
4797
5186
  const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
@@ -4837,7 +5226,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4837
5226
  const handle = defineAnnotatedType("union");
4838
5227
  for (const t of s.type) handle.item(convert({
4839
5228
  ...s,
4840
- type: t
5229
+ type: t,
5230
+ title: void 0,
5231
+ description: void 0
4841
5232
  }));
4842
5233
  return handle.$type;
4843
5234
  }
@@ -4935,14 +5326,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4935
5326
  * to it are renamed.
4936
5327
  *
4937
5328
  * @param types - Array of annotated types, each with an `id`.
5329
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
4938
5330
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
4939
- */ function mergeJsonSchemas(types) {
5331
+ */ function mergeJsonSchemas(types, opts) {
4940
5332
  const mergedDefs = {};
4941
5333
  const schemas = {};
4942
5334
  for (const type of types) {
4943
5335
  const name = type.id;
4944
5336
  if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
4945
- const { $defs: defs, ...schema } = buildJsonSchema(type);
5337
+ const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
4946
5338
  if (!defs) {
4947
5339
  schemas[name] = schema;
4948
5340
  continue;
@@ -5191,12 +5583,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5191
5583
  /**
5192
5584
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
5193
5585
  * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
5194
- * (`static toJsonSchema()`).
5195
- */ function lazyJsonSchema(type) {
5586
+ * (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
5587
+ * of a type).
5588
+ */ function lazyJsonSchema(type, opts) {
5196
5589
  const known = lazy.get(type);
5197
5590
  const writes = metadataWriteCount();
5198
5591
  if (known?.writes === writes) return known.schema;
5199
- const schema = buildJsonSchema(type);
5592
+ const schema = buildJsonSchema(type, opts);
5200
5593
  lazy.set(type, {
5201
5594
  writes,
5202
5595
  schema
@@ -5208,14 +5601,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5208
5601
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
5209
5602
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
5210
5603
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
5211
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
5212
- */ function bundledSchemaOf(type, literal, modules = []) {
5604
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
5605
+ * `jsonSchemaOptions` of the build (the literal was built with them).
5606
+ */ function bundledSchemaOf(type, literal, modules = [], opts) {
5213
5607
  const applied = appliedBlockModules();
5214
5608
  const known = bundled.get(type);
5215
5609
  if (known?.size === applied.size) return known.schema;
5216
5610
  const accounted = new Set(modules);
5217
5611
  const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
5218
- const schema = same ? literal() : buildJsonSchema(type);
5612
+ const schema = same ? literal() : buildJsonSchema(type, opts);
5219
5613
  bundled.set(type, {
5220
5614
  size: applied.size,
5221
5615
  schema,
@@ -5358,7 +5752,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5358
5752
 
5359
5753
  //#endregion
5360
5754
  //#region packages/typescript/src/runtime/serialize.ts
5361
- function _define_property$2(obj, key, value) {
5755
+ function _define_property$3(obj, key, value) {
5362
5756
  if (key in obj) Object.defineProperty(obj, key, {
5363
5757
  value,
5364
5758
  enumerable: true,
@@ -5430,17 +5824,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5430
5824
  return id;
5431
5825
  }
5432
5826
  constructor() {
5433
- _define_property$2(this, "own", /* @__PURE__ */ new Map());
5827
+ _define_property$3(this, "own", /* @__PURE__ */ new Map());
5434
5828
  /**
5435
5829
  * The nodes without an id met more than once (see `indexPayload`): serialized once, with a
5436
5830
  * payload id, and referenced (`$ref`, `anon`) wherever else they are.
5437
- */ _define_property$2(this, "repeated", /* @__PURE__ */ new Set());
5438
- _define_property$2(this, "firstKeys", /* @__PURE__ */ new Map());
5439
- _define_property$2(this, "identities", /* @__PURE__ */ new WeakMap());
5440
- _define_property$2(this, "nextId", 0);
5441
- /** Payload ids by type def (see {@link keyOf}). */ _define_property$2(this, "keys", /* @__PURE__ */ new WeakMap());
5442
- /** The payload ids given so far. */ _define_property$2(this, "taken", /* @__PURE__ */ new Set());
5443
- /** The `cut` payload of defs (see `indexPayload`). */ _define_property$2(this, "cutKeys", /* @__PURE__ */ new WeakMap());
5831
+ */ _define_property$3(this, "repeated", /* @__PURE__ */ new Set());
5832
+ _define_property$3(this, "firstKeys", /* @__PURE__ */ new Map());
5833
+ _define_property$3(this, "identities", /* @__PURE__ */ new WeakMap());
5834
+ _define_property$3(this, "nextId", 0);
5835
+ /** Payload ids by type def (see {@link keyOf}). */ _define_property$3(this, "keys", /* @__PURE__ */ new WeakMap());
5836
+ /** The payload ids given so far. */ _define_property$3(this, "taken", /* @__PURE__ */ new Set());
5837
+ /** The `cut` payload of defs (see `indexPayload`). */ _define_property$3(this, "cutKeys", /* @__PURE__ */ new WeakMap());
5444
5838
  }
5445
5839
  };
5446
5840
  /**
@@ -5904,7 +6298,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5904
6298
  * their specs flag `userText`. Core's are known from the start ({@link CORE_USER_TEXT}); a plugin's
5905
6299
  * are registered by the generated modules that write them (`$ut`), or by the plugin itself
5906
6300
  * ({@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. */ /**
6301
+ */ /**
6302
+ * `true`: the value itself is the text; `'expression'`: the value is the source of a function the
6303
+ * client evaluates, its string literals the texts; a list: those fields of the value object are
6304
+ * (a name ending in `()`: that field is an expression).
6305
+ */ /**
5908
6306
  * The user-facing text of `@atscript/core`'s annotations (its specs' `userText` arguments; a test
5909
6307
  * keeps them equal).
5910
6308
  */ const CORE_USER_TEXT = new Map([
@@ -5927,33 +6325,36 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5927
6325
  ]);
5928
6326
  const USER_TEXT = new Map(CORE_USER_TEXT);
5929
6327
  /**
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.
6328
+ * Registers metadata key `key` as holding user-facing text (see {@link TUserTextFields}; `true` by
6329
+ * default). Fields add up across calls; a whole-value kind replaces a field list, and an
6330
+ * expression wins over text (`name()` over `name`), whatever the order of the calls.
5932
6331
  * For plugins that write such metadata at runtime; generated modules register what they write.
5933
6332
  */ function registerUserText(key, fields = true) {
5934
6333
  const known = USER_TEXT.get(key);
5935
- if (known === true || fields === true) {
5936
- USER_TEXT.set(key, true);
6334
+ if (known === "expression" || known === true && typeof fields === "object") return;
6335
+ if (typeof fields !== "object") {
6336
+ USER_TEXT.set(key, fields);
5937
6337
  return;
5938
6338
  }
5939
- const added = fields.filter((f) => !known?.includes(f));
5940
- if (added.length > 0 || !known) USER_TEXT.set(key, [...known ?? [], ...added]);
6339
+ const all = new Set([...typeof known === "object" ? known : [], ...fields]);
6340
+ USER_TEXT.set(key, [...all].filter((f) => !all.has(`${f}()`)));
5941
6341
  }
5942
6342
  /**
5943
6343
  * 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.
6344
+ * the value itself; `key()` — the value is an expression; `key:field` — that field of the value
6345
+ * object; `key:field()` — that field is an expression.
5945
6346
  */ function $ut(...entries) {
5946
6347
  for (const entry of entries) {
5947
6348
  const at = entry.indexOf(":");
5948
- if (at === -1) registerUserText(entry);
5949
- else registerUserText(entry.slice(0, at), [entry.slice(at + 1)]);
6349
+ if (at !== -1) registerUserText(entry.slice(0, at), [entry.slice(at + 1)]);
6350
+ else if (entry.endsWith("()")) registerUserText(entry.slice(0, -2), "expression");
6351
+ else registerUserText(entry);
5950
6352
  }
5951
6353
  }
5952
6354
  /**
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).
6355
+ * Where metadata key `key` holds user-facing text (see {@link TUserTextFields}; for a `multiple`
6356
+ * annotation, each item of its list), `undefined` when it holds none. Core keys are known from the
6357
+ * start; a plugin's once a module writing them is loaded (or the plugin registered them).
5957
6358
  */ function userTextOf(key) {
5958
6359
  return USER_TEXT.get(key);
5959
6360
  }
@@ -5961,6 +6362,235 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5961
6362
  return USER_TEXT;
5962
6363
  }
5963
6364
 
6365
+ //#endregion
6366
+ //#region packages/typescript/src/runtime/translate-served.ts
6367
+ /**
6368
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
6369
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
6370
+ * collected for the client.
6371
+ */ function _define_property$2(obj, key, value) {
6372
+ if (key in obj) Object.defineProperty(obj, key, {
6373
+ value,
6374
+ enumerable: true,
6375
+ configurable: true,
6376
+ writable: true
6377
+ });
6378
+ else obj[key] = value;
6379
+ return obj;
6380
+ }
6381
+ /**
6382
+ * Translates the user-facing text of serialized annotated types (the output of
6383
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
6384
+ * found at any depth is read with {@link userTextOf}:
6385
+ *
6386
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
6387
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
6388
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
6389
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
6390
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
6391
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
6392
+ * translates the expressions' results by exact match.
6393
+ *
6394
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
6395
+ * result shares every part with no translated text, and is `json` itself when nothing was
6396
+ * translated.
6397
+ *
6398
+ * @example
6399
+ * ```ts
6400
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
6401
+ * i18n.exists(text) ? i18n.t(text) : undefined
6402
+ * )
6403
+ * ```
6404
+ */ function translateServed(json, t) {
6405
+ const texts = {};
6406
+ return {
6407
+ value: walk(json, void 0, {
6408
+ t,
6409
+ texts
6410
+ }),
6411
+ texts
6412
+ };
6413
+ }
6414
+ /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
6415
+ if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
6416
+ if (typeof value === "string") {
6417
+ if (mode === "expression") collectLiterals(value, ctx);
6418
+ else if (mode === true && formatCodeOf(value) === void 0) return translate(value, ctx) ?? value;
6419
+ return value;
6420
+ }
6421
+ if (typeof value !== "object" || value === null) return value;
6422
+ return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
6423
+ }
6424
+ /**
6425
+ * The mode of the value at `key` of an object of `mode`: a metadata key's user text, a field of a
6426
+ * value object's, else `metadata` objects only (a non-string text value — a `ref` target — has
6427
+ * metadata).
6428
+ */ function modeOf(key, mode) {
6429
+ if (typeof mode === "object") return mode.includes(`${key}()`) ? "expression" : mode.includes(key) || void 0;
6430
+ return mode === "metadata" && userTextOf(key) || (key === "metadata" ? "metadata" : void 0);
6431
+ }
6432
+ /** `t(text)` when it is a string (a plain-object dictionary also has `constructor`, …). */ function translate(text, ctx) {
6433
+ const out = ctx.t(text);
6434
+ return typeof out === "string" ? out : void 0;
6435
+ }
6436
+ /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
6437
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
6438
+ const translated = translate(literal, ctx);
6439
+ if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
6440
+ }
6441
+ }
6442
+ /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
6443
+ "n": "\n",
6444
+ "t": " ",
6445
+ "r": "\r",
6446
+ "b": "\b",
6447
+ "f": "\f",
6448
+ "v": "\v",
6449
+ "0": "\0",
6450
+ "\n": "",
6451
+ "\r": "",
6452
+ "\r\n": ""
6453
+ };
6454
+ /** An escape of a literal's raw text: `\u{…}`, `\u….`, `\x..`, or a single character. */ const ESCAPE = /\\(u\{[\dA-Fa-f]+\}|u[\dA-Fa-f]{4}|x[\dA-Fa-f]{2}|\r\n|[\s\S])/gu;
6455
+ /** The string a literal's raw text (between its quotes) evaluates to. */ function decode(raw) {
6456
+ return raw.includes("\\") ? raw.replace(ESCAPE, (_, c) => {
6457
+ if (c.length < 3) return Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : c;
6458
+ const code = Number.parseInt(c.replace(/[ux{}]/g, ""), 16);
6459
+ return code > 1114111 ? "" : String.fromCodePoint(code);
6460
+ }) : raw;
6461
+ }
6462
+ /** A character of an identifier or a number. */ const IDENT = RegExp("[\\p{ID_Continue}$]", "u");
6463
+ /** A run of {@link IDENT} characters at `lastIndex`. */ const IDENT_RUN = RegExp("[\\p{ID_Continue}$]+", "uy");
6464
+ /** Keywords whose `(…)` a statement follows: a `/` after the `)` starts a regular expression. */ const CONTROL = new Set([
6465
+ "if",
6466
+ "while",
6467
+ "for",
6468
+ "with"
6469
+ ]);
6470
+ /** Keywords after which `/` starts a regular expression rather than a division. */ const REGEX_AFTER_WORD = new Set([
6471
+ "return",
6472
+ "typeof",
6473
+ "instanceof",
6474
+ "in",
6475
+ "of",
6476
+ "new",
6477
+ "delete",
6478
+ "void",
6479
+ "throw",
6480
+ "case",
6481
+ "do",
6482
+ "else",
6483
+ "yield",
6484
+ "await"
6485
+ ]);
6486
+ let LiteralScanner = class LiteralScanner {
6487
+ /** Scans code up to the end, or to the `}` closing a template's `${`. */ code() {
6488
+ const src = this.src;
6489
+ while (this.i < src.length) {
6490
+ const c = src[this.i];
6491
+ if (c === "/" && src[this.i + 1] === "/") {
6492
+ const end = src.indexOf("\n", this.i);
6493
+ this.i = end === -1 ? src.length : end;
6494
+ } else if (c === "/" && src[this.i + 1] === "*") {
6495
+ const end = src.indexOf("*/", this.i + 2);
6496
+ this.i = end === -1 ? src.length : end + 2;
6497
+ } else if (c === "'" || c === "\"" || c === "`") {
6498
+ const text = this.literal(c);
6499
+ if (text !== void 0 && text.trim() !== "") this.out.add(text);
6500
+ this.regexOk = false;
6501
+ } else if (c === "/" && this.regexOk) {
6502
+ this.regex();
6503
+ this.regexOk = false;
6504
+ } else if (IDENT.test(c)) this.word();
6505
+ else if ((c === "+" || c === "-") && src[this.i + 1] === c) {
6506
+ this.i += 2;
6507
+ this.regexOk = false;
6508
+ } else {
6509
+ this.i++;
6510
+ if (/\s/.test(c)) continue;
6511
+ if (c === "(" || c === "{") this.open.push(c === "(" ? "p" : c);
6512
+ else if (c === ")" || c === "}") {
6513
+ const top = this.open.pop();
6514
+ if (top === "$") return;
6515
+ this.regexOk = top === "c";
6516
+ continue;
6517
+ }
6518
+ this.regexOk = c !== "]";
6519
+ }
6520
+ }
6521
+ }
6522
+ /** An identifier, keyword or number at `i`; `i` past it (and past a control keyword's `(`). */ word() {
6523
+ const src = this.src;
6524
+ IDENT_RUN.lastIndex = this.i;
6525
+ IDENT_RUN.test(src);
6526
+ const word = src.slice(this.i, IDENT_RUN.lastIndex);
6527
+ this.i = IDENT_RUN.lastIndex;
6528
+ this.regexOk = REGEX_AFTER_WORD.has(word);
6529
+ if (CONTROL.has(word)) {
6530
+ while (/\s/.test(src[this.i] ?? "")) this.i++;
6531
+ if (src[this.i] === "(") {
6532
+ this.i++;
6533
+ this.open.push("c");
6534
+ this.regexOk = true;
6535
+ }
6536
+ }
6537
+ }
6538
+ /**
6539
+ * A `'…'` / `"…"` / `` `…` `` literal at `i`, decoded (`undefined`: a template with `${…}`, whose
6540
+ * code is scanned); `i` past it.
6541
+ */ literal(quote) {
6542
+ const src = this.src;
6543
+ const start = ++this.i;
6544
+ let plain = true;
6545
+ while (this.i < src.length && src[this.i] !== quote) if (src[this.i] === "\\") this.i += src.startsWith("\r\n", this.i + 1) ? 3 : 2;
6546
+ else if (quote === "`" && src.startsWith("${", this.i)) {
6547
+ plain = false;
6548
+ this.i += 2;
6549
+ this.open.push("$");
6550
+ this.code();
6551
+ } else this.i++;
6552
+ const end = this.i++;
6553
+ return plain ? decode(src.slice(start, end)) : void 0;
6554
+ }
6555
+ /** A regular expression literal starting at `i`; `i` past its flags. */ regex() {
6556
+ const src = this.src;
6557
+ let inClass = false;
6558
+ this.i++;
6559
+ while (this.i < src.length && src[this.i] !== "\n") {
6560
+ const c = src[this.i++];
6561
+ if (c === "\\") this.i++;
6562
+ else if (c === "[") inClass = true;
6563
+ else if (c === "]") inClass = false;
6564
+ else if (c === "/" && !inClass) break;
6565
+ }
6566
+ while (this.i < src.length && /[a-z]/i.test(src[this.i])) this.i++;
6567
+ }
6568
+ constructor(src, out) {
6569
+ _define_property$2(this, "src", void 0);
6570
+ _define_property$2(this, "out", void 0);
6571
+ _define_property$2(this, "i", void 0);
6572
+ /** A `/` here starts a regular expression (no operand just ended), not a division. */ _define_property$2(this, "regexOk", void 0);
6573
+ /**
6574
+ * The open brackets: `c` — the `(` of an `if` / `while` / `for` / `with` (a `/` after its `)` is
6575
+ * a regex); `p` — another `(`; `{`; `$` — a template's `${`.
6576
+ */ _define_property$2(this, "open", void 0);
6577
+ this.src = src;
6578
+ this.out = out;
6579
+ this.i = 0;
6580
+ this.regexOk = true;
6581
+ this.open = [];
6582
+ }
6583
+ };
6584
+ /**
6585
+ * The string literals of JavaScript `source`, as the strings they evaluate to: `'…'`, `"…"` and
6586
+ * `` `…` `` templates without `${…}` (the literals inside a `${…}` count). Comments and regular
6587
+ * expression literals are skipped; empty and blank literals are left out.
6588
+ */ function stringLiterals(source) {
6589
+ const out = /* @__PURE__ */ new Set();
6590
+ new LiteralScanner(source, out).code();
6591
+ return [...out];
6592
+ }
6593
+
5964
6594
  //#endregion
5965
6595
  //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
5966
6596
  /**
@@ -6927,11 +7557,14 @@ exports.localizeErrors = localizeErrors;
6927
7557
  exports.mergeJsonSchemas = mergeJsonSchemas;
6928
7558
  exports.messagesTranslator = messagesTranslator;
6929
7559
  exports.metaEmpty = metaEmpty;
7560
+ exports.normalizeForType = normalizeForType;
6930
7561
  exports.pendingStatements = pendingStatements;
6931
7562
  exports.registerCompiledCheck = registerCompiledCheck;
6932
7563
  exports.registerUserText = registerUserText;
6933
7564
  exports.serializeAnnotatedType = serializeAnnotatedType;
6934
7565
  exports.throwFeatureDisabled = throwFeatureDisabled;
7566
+ exports.translateServed = translateServed;
7567
+ exports.unionDiscriminator = unionDiscriminator;
6935
7568
  exports.userTextKeys = userTextKeys;
6936
7569
  exports.userTextOf = userTextOf;
6937
7570
  exports.watchLayer = watchLayer;