@atscript/typescript 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.cjs CHANGED
@@ -1,11 +1,435 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_user_text = require('./user-text-BddKk8EU.cjs');
2
+ const require_user_text = require('./user-text-BvyErcKK.cjs');
3
3
 
4
- //#region packages/typescript/src/runtime/coerce.ts
4
+ //#region packages/typescript/src/runtime/copy-on-change.ts
5
+ /**
6
+ * Internal sentinel: the value cannot be taken by a type node (drives union branch selection in
7
+ * `coerce.ts` and `normalize.ts`). A {@link mapProps} step returns it to reject the whole object.
8
+ */ const NO_MATCH = Symbol("atscript.no-match");
9
+ /**
10
+ * Maps the props of plain object `value` with `step` (props without a def — declared or pattern —
11
+ * are kept as they are). Copy-on-first-change: allocates the output only when some prop changed,
12
+ * else returns `value`; an own `__proto__` key stays an own key (never the output's prototype).
13
+ * NO_MATCH when a step returns it.
14
+ */ function mapProps(type, value, step, ctx) {
15
+ const keys = Object.keys(value);
16
+ let out;
17
+ for (let i = 0; i < keys.length; i++) {
18
+ const key = keys[i];
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
+ }
27
+ const mapped = def ? step(def, input, ctx) : input;
28
+ if (mapped === NO_MATCH) return NO_MATCH;
29
+ if (out) setOwn(out, key, mapped);
30
+ else if (mapped !== input) {
31
+ out = {};
32
+ for (let j = 0; j < i; j++) setOwn(out, keys[j], value[keys[j]]);
33
+ setOwn(out, key, mapped);
34
+ }
35
+ }
36
+ return out ?? value;
37
+ }
38
+ /**
39
+ * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
40
+ * items). Copy-on-first-change, as {@link mapProps}.
41
+ */ function mapItems(value, of, step, ctx) {
42
+ return mapList(value, (input, i) => step(Array.isArray(of) ? of[i] : of, input, ctx));
43
+ }
44
+ /** Maps the items of `list` with `step`. Copy-on-first-change: `list` itself when none changed. */ function mapList(list, step) {
45
+ let out;
46
+ for (let i = 0; i < list.length; i++) {
47
+ const mapped = step(list[i], i);
48
+ if (out) out.push(mapped);
49
+ else if (mapped !== list[i]) {
50
+ out = list.slice(0, i);
51
+ out.push(mapped);
52
+ }
53
+ }
54
+ return out ?? list;
55
+ }
56
+ /**
57
+ * Maps the own values of JSON object `obj` with `step`. Copy-on-first-change: `obj` itself when
58
+ * none changed; an own `__proto__` key stays an own key.
59
+ */ function mapEntries(obj, step) {
60
+ let out;
61
+ for (const key of Object.keys(obj)) {
62
+ const mapped = step(key, obj[key]);
63
+ if (mapped !== obj[key]) {
64
+ out ?? (out = { ...obj });
65
+ setOwn(out, key, mapped);
66
+ }
67
+ }
68
+ return out ?? obj;
69
+ }
70
+ /** Whether `value` is a plain object (`{}` or prototype-less): class instances are not. */ function isPlainObject$1(value) {
71
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
72
+ const proto = Object.getPrototypeOf(value);
73
+ return proto === Object.prototype || proto === null;
74
+ }
75
+ /**
76
+ * Sets own property `key` of `out`: `__proto__` as an own data property (an assignment would set
77
+ * the object's prototype instead — input parsed from JSON may carry such a key).
78
+ */ function setOwn(out, key, value) {
79
+ if (key === "__proto__") Object.defineProperty(out, key, {
80
+ value,
81
+ writable: true,
82
+ enumerable: true,
83
+ configurable: true
84
+ });
85
+ else out[key] = value;
86
+ }
87
+
88
+ //#endregion
89
+ //#region packages/typescript/src/runtime/normalize.ts
90
+ const TRIM = 1;
91
+ const LOWERCASE = 2;
92
+ const UPPERCASE = 4;
93
+ /**
94
+ * Whether each node's subtree has normalizers: valid until the next type tree write (metadata or
95
+ * shape) or `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
96
+ */ let reach = /* @__PURE__ */ new WeakMap();
97
+ let stampWrites = -1;
98
+ function newJudges(opts) {
99
+ const root = {
100
+ ...opts,
101
+ errorLimit: 1
102
+ };
103
+ delete root.translate;
104
+ if (root.unknownProps === "strip") root.unknownProps = "ignore";
105
+ const judge = {
106
+ opts: root,
107
+ validators: /* @__PURE__ */ new WeakMap()
108
+ };
109
+ return {
110
+ root: judge,
111
+ nested: root.partial === true ? {
112
+ opts: {
113
+ ...root,
114
+ partial: false
115
+ },
116
+ validators: /* @__PURE__ */ new WeakMap()
117
+ } : judge
118
+ };
119
+ }
120
+ const DEFAULT_JUDGES = newJudges({});
121
+ /** The judges by the options object passed (the same options: the same validators). */ const judgesByOpts = /* @__PURE__ */ new WeakMap();
122
+ function judgesFor(opts) {
123
+ if (!opts) return DEFAULT_JUDGES;
124
+ let found = judgesByOpts.get(opts);
125
+ if (!found) {
126
+ found = newJudges(opts);
127
+ judgesByOpts.set(opts, found);
128
+ }
129
+ return found;
130
+ }
131
+ /**
132
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
133
+ * `@normalize.lowercase` and `@normalize.uppercase`.
134
+ *
135
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
136
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
137
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
138
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
139
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
140
+ * uppercase. Other values (including class instances such as `Date`) and strings without
141
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
142
+ *
143
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
144
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
145
+ * value is left as it is. A union normalizes a value only when the result does not depend on
146
+ * which branch takes it:
147
+ * - an object union with a discriminator (a literal prop every object branch requires, see
148
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
149
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
150
+ * only when the normalized string equals its literal): when they all give the same result it
151
+ * is used; when they differ, the branches whose result their own validator accepts are kept,
152
+ * and the result is used when they agree; else the value is returned untouched (ambiguous).
153
+ * The branch validators take `opts` — pass the options the result will be validated with
154
+ * (`partial`, `unknownProps`, …) so a branch is judged as the validator will judge it; default
155
+ * options when omitted. (`unknownProps: 'strip'` judges as `'ignore'`: nothing is stripped.)
156
+ *
157
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * // @normalize.trim @normalize.lowercase email: string.email
162
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
163
+ * // judged as a partial update will be validated
164
+ * normalizeForType(Patch, body, { partial: true })
165
+ * ```
166
+ */ function normalizeForType(def, value, opts) {
167
+ const writes = require_user_text.typeWriteCount();
168
+ if (writes !== stampWrites) {
169
+ stampWrites = writes;
170
+ reach = /* @__PURE__ */ new WeakMap();
171
+ }
172
+ if (!hasNormalizers(def)) return value;
173
+ const result = normalize(def, value, 0, {
174
+ memo: /* @__PURE__ */ new Map(),
175
+ root: value,
176
+ opts
177
+ });
178
+ return result === NO_MATCH ? value : result;
179
+ }
180
+ /** The nodes `def`'s value walk can enter (props, pattern props, items, elements). */ function childrenOf(def) {
181
+ const type = def.type;
182
+ switch (type.kind) {
183
+ case "object": {
184
+ const t = type;
185
+ const out = [...t.props.values()];
186
+ for (const p of t.propsPatterns) out.push(p.def);
187
+ return out;
188
+ }
189
+ case "array": return [type.of];
190
+ case "union":
191
+ case "intersection":
192
+ case "tuple": return type.items;
193
+ default: return [];
194
+ }
195
+ }
5
196
  /**
6
- * Internal sentinel returned when a value cannot be coerced to a type node.
7
- * Drives union branch selection without allocating per-node result objects.
8
- */ const NO_MATCH = Symbol("atscript.coerce.no-match");
197
+ * Whether `def` or a node its walk reaches has normalizers. Answers (and caches) every node
198
+ * reached, recursive types included: collects the reached nodes with their parents, then marks
199
+ * the nodes with normalizers and, back along the parents, every node that reaches one.
200
+ */ function hasNormalizers(def) {
201
+ const known = reach.get(def);
202
+ if (known !== void 0) return known;
203
+ const parents = new Map([[def, []]]);
204
+ const marked = [];
205
+ const todo = [def];
206
+ while (todo.length > 0) {
207
+ const node = todo.pop();
208
+ if (flagsOf(node, 0) !== 0) marked.push(node);
209
+ for (const child of childrenOf(node)) {
210
+ const cached = reach.get(child);
211
+ if (cached !== void 0) {
212
+ if (cached) marked.push(node);
213
+ continue;
214
+ }
215
+ let of = parents.get(child);
216
+ if (!of) {
217
+ parents.set(child, of = []);
218
+ todo.push(child);
219
+ }
220
+ of.push(node);
221
+ }
222
+ }
223
+ for (const node of parents.keys()) reach.set(node, false);
224
+ while (marked.length > 0) {
225
+ const node = marked.pop();
226
+ if (!reach.get(node)) {
227
+ reach.set(node, true);
228
+ marked.push(...parents.get(node));
229
+ }
230
+ }
231
+ return reach.get(def);
232
+ }
233
+ /** The normalizer flags of `def`, on top of `inherited` (a union's, for its branches). */ function flagsOf(def, inherited) {
234
+ const meta = def.metadata;
235
+ if (require_user_text.metaEmpty(meta)) return inherited;
236
+ let flags = inherited;
237
+ if (meta.get("normalize.trim")) flags |= TRIM;
238
+ if (meta.get("normalize.lowercase")) flags |= LOWERCASE;
239
+ if (meta.get("normalize.uppercase")) flags |= UPPERCASE;
240
+ return flags;
241
+ }
242
+ /** `value` with normalizer `flags` applied, in their fixed order (see {@link flagsOf}). */ function applyFlags(value, flags) {
243
+ let out = value;
244
+ if (flags & TRIM) out = out.trim();
245
+ if (flags & LOWERCASE) out = out.toLowerCase();
246
+ if (flags & UPPERCASE) out = out.toUpperCase();
247
+ return out;
248
+ }
249
+ /**
250
+ * The normalized value, or NO_MATCH when `def` cannot take it (its kind does not fit the value).
251
+ * `inherited`: the normalizer flags of the unions / intersections `def` is a member of.
252
+ *
253
+ * Objects and unions are memoized per call by input object: a recursive union without a
254
+ * discriminator is tried for every branch at every level, which without it is exponential in
255
+ * the depth of the value.
256
+ */ function normalize(def, value, inherited, walk) {
257
+ if (value === void 0 || value === null) return value;
258
+ if (inherited === 0 && !hasNormalizers(def)) return takes$1(def, value) ? value : NO_MATCH;
259
+ const type = def.type;
260
+ switch (type.kind) {
261
+ case "": {
262
+ const out = typeof value === "string" && type.designType === "string" ? applyFlags(value, flagsOf(def, inherited)) : value;
263
+ return takes$1(def, out) ? out : NO_MATCH;
264
+ }
265
+ case "object": {
266
+ if (!isPlainObject$1(value)) return NO_MATCH;
267
+ const entries = entriesOf(walk.memo, value);
268
+ return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, walk));
269
+ }
270
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, walk) : NO_MATCH;
271
+ case "tuple": {
272
+ const items = type.items;
273
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, walk) : NO_MATCH;
274
+ }
275
+ case "union": {
276
+ const flags = flagsOf(def, inherited);
277
+ const items = type.items;
278
+ if (typeof value !== "object") return normalizeUnion(items, value, flags, walk);
279
+ const entries = entriesOf(walk.memo, value);
280
+ return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, walk));
281
+ }
282
+ case "intersection": {
283
+ const flags = flagsOf(def, inherited);
284
+ let current = value;
285
+ for (const item of type.items) {
286
+ const result = normalize(item, current, flags, walk);
287
+ if (result === NO_MATCH) return NO_MATCH;
288
+ current = result;
289
+ }
290
+ return current;
291
+ }
292
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
293
+ }
294
+ }
295
+ /** The memoized results for input object `value` (see {@link normalize}). */ function entriesOf(memo, value) {
296
+ let entries = memo.get(value);
297
+ if (!entries) {
298
+ entries = [];
299
+ memo.set(value, entries);
300
+ }
301
+ return entries;
302
+ }
303
+ /** The memoized result for `type` and `flags`, `undefined` when none. */ function recall(entries, type, flags) {
304
+ for (const [t, f, result] of entries) if (t === type && f === flags) return result;
305
+ }
306
+ /** Memoizes `result` for `type` and `flags` and returns it. */ function remember(entries, type, flags, result) {
307
+ entries.push([
308
+ type,
309
+ flags,
310
+ result
311
+ ]);
312
+ return result;
313
+ }
314
+ /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, walk) {
315
+ if (!hasNormalizers(def)) return input;
316
+ const result = normalize(def, input, 0, walk);
317
+ return result === NO_MATCH ? input : result;
318
+ }
319
+ /**
320
+ * A prop: as {@link normalizeItem}, but NO_MATCH (the object is not this type) when a literal prop
321
+ * (`kind: 'cat'`, `kind: 'cat' | null`, see {@link literalNodes}) holds another value.
322
+ */ function normalizeProp(def, input, walk) {
323
+ const out = normalizeItem(def, input, walk);
324
+ if (out === input && input !== void 0 && input !== null) {
325
+ const literals = literalNodes(def);
326
+ if (literals && !literals.some((l) => l.node.type.value === input)) return NO_MATCH;
327
+ }
328
+ return out;
329
+ }
330
+ /**
331
+ * The literals a literal prop can hold: `def` itself when it is a literal (`kind: 'cat'`), the
332
+ * literals of a union of literals, `null` and `undefined` (`kind: 'cat' | null`, nested unions and
333
+ * aliases too); `undefined` for any other type. Each with the normalizers of the nodes on its way
334
+ * (a union's apply to its members). A literal prop holding another value tells that an object is
335
+ * not of its type, for normalization and coercion alike (see `coerce.ts`).
336
+ */ function literalNodes(def, inherited = 0) {
337
+ const type = def.type;
338
+ if (type.kind === "") return type.value === void 0 ? void 0 : [{
339
+ node: def,
340
+ flags: flagsOf(def, inherited)
341
+ }];
342
+ if (type.kind !== "union") return;
343
+ const flags = flagsOf(def, inherited);
344
+ const out = [];
345
+ for (const item of type.items) {
346
+ const designType = item.type.designType;
347
+ if (item.type.kind === "" && (designType === "null" || designType === "undefined")) continue;
348
+ const inner = literalNodes(item, flags);
349
+ if (!inner) return;
350
+ out.push(...inner);
351
+ }
352
+ return out.length > 0 ? out : void 0;
353
+ }
354
+ /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes$1(def, value) {
355
+ const type = def.type;
356
+ switch (type.kind) {
357
+ case "": {
358
+ const final = type;
359
+ switch (final.designType) {
360
+ case "string":
361
+ case "number":
362
+ case "boolean": return typeof value === final.designType && (final.value === void 0 || value === final.value);
363
+ case "decimal": return typeof value === "string";
364
+ case "object": return typeof value === "object";
365
+ case "any":
366
+ case "phantom": return true;
367
+ default: return false;
368
+ }
369
+ }
370
+ case "object": return isPlainObject$1(value);
371
+ case "array": return Array.isArray(value);
372
+ case "tuple": return Array.isArray(value) && value.length === type.items.length;
373
+ case "union": return type.items.some((item) => takes$1(item, value));
374
+ case "intersection": return type.items.every((item) => takes$1(item, value));
375
+ default: return false;
376
+ }
377
+ }
378
+ /**
379
+ * A union: the branch a discriminator names, else the one result every branch that can take
380
+ * the value agrees on — or, when they differ, the one result of the branches whose validator
381
+ * accepts their result (NO_MATCH when none can take the value or it stays ambiguous).
382
+ */ function normalizeUnion(items, value, flags, walk) {
383
+ if (isPlainObject$1(value)) {
384
+ const disc = require_user_text.unionDiscriminator(items);
385
+ if (disc) {
386
+ const tag = value[disc.property];
387
+ for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, walk);
388
+ }
389
+ }
390
+ let first = NO_MATCH;
391
+ let firstItem;
392
+ let rest;
393
+ for (const item of items) {
394
+ const out = normalize(item, value, flags, walk);
395
+ if (out === NO_MATCH) continue;
396
+ if (first === NO_MATCH) {
397
+ first = out;
398
+ firstItem = item;
399
+ } else (rest ?? (rest = [])).push([item, out]);
400
+ }
401
+ if (!rest || rest.every(([, out]) => sameValue(out, first))) return first;
402
+ rest.unshift([firstItem, first]);
403
+ const judges = judgesFor(walk.opts);
404
+ const judge = value === walk.root ? judges.root : judges.nested;
405
+ let accepted = NO_MATCH;
406
+ for (const [item, out] of rest) {
407
+ if (!branchValidator(judge, item).validate(out, true)) continue;
408
+ if (accepted === NO_MATCH) accepted = out;
409
+ else if (!sameValue(accepted, out)) return NO_MATCH;
410
+ }
411
+ return accepted;
412
+ }
413
+ /** Union branch `def`'s validator, judging its own normalized result (see {@link TJudges}). */ function branchValidator(judge, def) {
414
+ let validator = judge.validators.get(def);
415
+ if (!validator) {
416
+ validator = new require_user_text.Validator(def, judge.opts);
417
+ judge.validators.set(def, validator);
418
+ }
419
+ return validator;
420
+ }
421
+ /** Whether two results of the same input are equal (shared, untouched parts are identical). */ function sameValue(a, b) {
422
+ if (a === b) return true;
423
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
424
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
425
+ const keys = Object.keys(a);
426
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
427
+ }
428
+ return false;
429
+ }
430
+
431
+ //#endregion
432
+ //#region packages/typescript/src/runtime/coerce.ts
9
433
  /**
10
434
  * Coerces string-transport input (route params, query strings) toward the
11
435
  * scalar shapes an annotated type expects.
@@ -19,9 +443,19 @@ const require_user_text = require('./user-text-BddKk8EU.cjs');
19
443
  * - Strings targeting `number` are trimmed and parsed via `Number()`; only
20
444
  * finite results are accepted.
21
445
  * - Strings targeting `boolean` accept `"true"/"1"` and `"false"/"0"`.
22
- * - Unions try each branch in declared order; the first successful parse wins.
446
+ * - Unions pick one branch and coerce the value against it only (linear, no
447
+ * backtracking). A scalar branch takes what it parses; an object (tuple)
448
+ * branch takes a plain object (an array of its length) unless a literal
449
+ * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
450
+ * does not coerce to it, a string compared after the normalizers of the
451
+ * literal and of the unions it is in. An object takes the branch its
452
+ * discriminator names (as the validator does: the literal itself first, else
453
+ * `"2"` names a `2` literal), else the first whose shape it has (required
454
+ * props present, no undeclared key), else the first that takes it. When no
455
+ * branch takes the value, it is returned untouched.
23
456
  * - Objects recurse into props when the input is a plain object (covers
24
- * `@Query()` DTOs where every field arrives as a string).
457
+ * `@Query()` DTOs where every field arrives as a string), whatever their
458
+ * literal props hold unless tried as a union branch.
25
459
  * - Arrays and tuples coerce items; intersections apply each member in order.
26
460
  * - `string` / `decimal` targets never change string input.
27
461
  *
@@ -55,18 +489,16 @@ const require_user_text = require('./user-text-BddKk8EU.cjs');
55
489
  }
56
490
  case "object":
57
491
  if (!isPlainObject$1(value)) return NO_MATCH;
58
- return coerceProps(def, value);
59
- case "array": return Array.isArray(value) ? coerceItems(value, type.of) : NO_MATCH;
492
+ return mapProps(type, value, coerceChild, void 0);
493
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
60
494
  case "tuple": {
61
495
  const items = type.items;
62
- return Array.isArray(value) && value.length === items.length ? coerceItems(value, void 0, items) : NO_MATCH;
496
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
497
+ }
498
+ case "union": {
499
+ const branch = branchOf(type.items, value);
500
+ return branch ? coerce(branch, value) : NO_MATCH;
63
501
  }
64
- case "union":
65
- for (const item of type.items) {
66
- const result = coerce(item, value);
67
- if (result !== NO_MATCH) return result;
68
- }
69
- return NO_MATCH;
70
502
  case "intersection": {
71
503
  let current = value;
72
504
  for (const item of type.items) {
@@ -105,56 +537,99 @@ function scalar(designType, value) {
105
537
  }
106
538
  }
107
539
  /**
108
- * Coerces the props of a plain object. Copy-on-first-change: allocates the
109
- * output object only when some prop actually coerced, else returns the input.
110
- */ function coerceProps(def, value) {
111
- const keys = Object.keys(value);
112
- let out;
113
- for (let i = 0; i < keys.length; i++) {
114
- const key = keys[i];
115
- const input = value[key];
116
- let propDef = def.type.props.get(key);
117
- if (!propDef) {
118
- for (const { pattern, def: patternDef } of def.type.propsPatterns) if (pattern.test(key)) {
119
- propDef = patternDef;
120
- break;
121
- }
122
- }
123
- let coerced = input;
124
- if (propDef) {
125
- const result = coerce(propDef, input);
126
- if (result !== NO_MATCH) coerced = result;
127
- }
128
- if (out) out[key] = coerced;
129
- else if (coerced !== input) {
130
- out = {};
131
- for (let j = 0; j < i; j++) out[keys[j]] = value[keys[j]];
132
- out[key] = coerced;
540
+ * The branch of union `items` that takes `value` (see {@link takes}): the one an object's
541
+ * discriminator names; else, for an object, the first that takes it and whose shape it has (see
542
+ * {@link fits}); else the first that takes it, in declared order (a partial patch); `undefined`
543
+ * when none does.
544
+ */ function branchOf(items, value) {
545
+ let first;
546
+ if (isPlainObject$1(value)) {
547
+ const named = discriminatedBranch(items, value);
548
+ if (named && takes(named, value)) return named;
549
+ for (const item of items) if (takes(item, value)) {
550
+ if (fits(item, value)) return item;
551
+ first ?? (first = item);
133
552
  }
553
+ return first;
134
554
  }
135
- return out ?? value;
555
+ return items.find((item) => takes(item, value));
136
556
  }
137
557
  /**
138
- * Coerces array/tuple items against `of` (arrays) or `items[i]` (tuples).
139
- * Copy-on-first-change, same as {@link coerceProps}.
140
- */ function coerceItems(value, of, items) {
141
- let out;
142
- for (let i = 0; i < value.length; i++) {
143
- const input = value[i];
144
- const result = coerce(of ?? items[i], input);
145
- const coerced = result === NO_MATCH ? input : result;
146
- if (out) out.push(coerced);
147
- else if (coerced !== input) {
148
- out = value.slice(0, i);
149
- out.push(coerced);
558
+ * Whether object `value` has the shape of branch `def`, by its own keys alone: every required
559
+ * prop is one of them, and each of them is a prop (or matches a prop pattern) of the branch. A
560
+ * union: one of its branches; a branch that is not an object (nor an intersection of objects)
561
+ * has any shape.
562
+ */ function fits(def, value) {
563
+ if (def.type.kind === "union") return def.type.items.some((item) => fits(item, value));
564
+ const objects = [];
565
+ if (!objectsOf(def, objects)) return true;
566
+ for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return false;
567
+ return Object.keys(value).every((key) => objects.some((o) => o.props.has(key) || o.propsPatterns.some((p) => p.pattern.test(key))));
568
+ }
569
+ /** Collects the objects `def` is (an object, an intersection of objects); `false` for others. */ function objectsOf(def, out) {
570
+ const type = def.type;
571
+ if (type.kind === "object") {
572
+ out.push(type);
573
+ return true;
574
+ }
575
+ return type.kind === "intersection" && type.items.every((item) => objectsOf(item, out));
576
+ }
577
+ /**
578
+ * Whether union branch `def` takes `value`: exactly when coercing `value` against it does not
579
+ * fail (a branch taken never fails after it), decided from `value` itself — its kind, its length,
580
+ * its direct literal props and items — never from what it holds deeper. A union takes one branch
581
+ * once, so coercion is linear in the value.
582
+ */ function takes(def, value) {
583
+ if (value === void 0 || value === null) return def.optional === true;
584
+ const type = def.type;
585
+ switch (type.kind) {
586
+ case "": return coerce(def, value) !== NO_MATCH;
587
+ case "object":
588
+ if (!isPlainObject$1(value)) return false;
589
+ for (const [key, prop] of type.props) if (Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
590
+ return true;
591
+ case "array": return Array.isArray(value);
592
+ case "tuple": {
593
+ const items = type.items;
594
+ return Array.isArray(value) && value.length === items.length && items.every((item, i) => holdsLiteral(item, value[i]));
150
595
  }
596
+ case "union": return type.items.some((item) => takes(item, value));
597
+ case "intersection": return type.items.every((item) => takes(item, value));
598
+ default: return false;
151
599
  }
152
- return out ?? value;
153
600
  }
154
- function isPlainObject$1(value) {
155
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
156
- const proto = Object.getPrototypeOf(value);
157
- return proto === Object.prototype || proto === null;
601
+ /**
602
+ * Whether prop (item) `def` of a union branch can hold `input`: anything, but a literal prop
603
+ * (see `literalNodes`: `kind: 'cat'`, `kind: 'cat' | null`) only a value that coerces to one of
604
+ * its literals — a string after the normalizers on the literal's way (`' Cat '` to `'cat'` with
605
+ * `@normalize.trim @normalize.lowercase`). `null` / `undefined` are left to the validator.
606
+ */ function holdsLiteral(def, input) {
607
+ if (input === void 0 || input === null) return true;
608
+ const literals = literalNodes(def);
609
+ return !literals || literals.some((literal) => coercesTo(literal, input));
610
+ }
611
+ /** Whether `input` coerces to the value of `literal` (see `holdsLiteral`). */ function coercesTo(literal, input) {
612
+ const value = typeof input === "string" ? applyFlags(input, literal.flags) : input;
613
+ return coerce(literal.node, value) !== NO_MATCH;
614
+ }
615
+ /**
616
+ * The branch of union `items` the discriminator of object `value` names: its literal itself,
617
+ * else the one its value coerces to (`"2"` names `2`, see {@link coercesTo}); `undefined` when the
618
+ * union has no discriminator or the value names no branch.
619
+ */ function discriminatedBranch(items, value) {
620
+ const disc = require_user_text.unionDiscriminator(items);
621
+ if (disc === void 0) return;
622
+ const tag = Object.hasOwn(value, disc.property) ? value[disc.property] : void 0;
623
+ if (tag === void 0 || tag === null) return;
624
+ for (const [index, literal] of disc.branches) if (literal === tag) return items[index];
625
+ for (const [index] of disc.branches) {
626
+ const prop = items[index].type.props.get(disc.property);
627
+ if (prop && holdsLiteral(prop, tag)) return items[index];
628
+ }
629
+ }
630
+ /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
631
+ const result = coerce(def, input);
632
+ return result === NO_MATCH ? input : result;
158
633
  }
159
634
 
160
635
  //#endregion
@@ -206,6 +681,7 @@ function isPlainObject$1(value) {
206
681
 
207
682
  //#endregion
208
683
  //#region packages/typescript/src/runtime/json-schema.ts
684
+ /** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
209
685
  /**
210
686
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
211
687
  *
@@ -221,8 +697,12 @@ function isPlainObject$1(value) {
221
697
  * ```
222
698
  *
223
699
  * @param type - The annotated type to convert.
700
+ * @param opts - {@link TJsonSchemaOptions}.
224
701
  * @returns A JSON Schema object.
225
- */ function buildJsonSchema(type) {
702
+ */ function buildJsonSchema(type, opts) {
703
+ const closed = opts?.closed === true;
704
+ const annotations = opts?.annotations !== false;
705
+ const enums = opts?.enums !== false;
226
706
  /**
227
707
  * `$defs` entries by type def (identity): named objects (always extracted) and types found
228
708
  * recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
@@ -250,8 +730,35 @@ function isPlainObject$1(value) {
250
730
  ...schema,
251
731
  type: [schema.type, "null"]
252
732
  };
253
- if (Object.keys(schema).length === 1 && Array.isArray(schema.anyOf)) return { anyOf: [...schema.anyOf, { type: "null" }] };
254
- return { anyOf: [schema, { type: "null" }] };
733
+ const notes = {};
734
+ let body = schema;
735
+ for (const [, keyword] of ANNOTATION_KEYWORDS) if (body[keyword] !== void 0) {
736
+ if (body === schema) body = { ...schema };
737
+ notes[keyword] = body[keyword];
738
+ delete body[keyword];
739
+ }
740
+ if (body !== schema && Object.keys(body).length === 1 && body.allOf?.length === 1) body = body.allOf[0];
741
+ if (Object.keys(body).length === 1 && Array.isArray(body.anyOf)) return {
742
+ anyOf: [...body.anyOf, { type: "null" }],
743
+ ...notes
744
+ };
745
+ return {
746
+ anyOf: [body, { type: "null" }],
747
+ ...notes
748
+ };
749
+ };
750
+ /**
751
+ * A use of a `$defs` entry: `schema` (its `$ref`) with what the use adds to the entry (built
752
+ * from `own`, see `ownDef`): its key counts, and its title / description when they differ
753
+ * from the entry's — beside the reference, in an `allOf`.
754
+ */ const useOf = (schema, def, own, keyCounts = false) => {
755
+ const extra = {};
756
+ if (annotations) applyAnnotationKeywords(extra, def.metadata, own?.metadata);
757
+ if (keyCounts) applyKeyCounts(extra, def.metadata);
758
+ return Object.keys(extra).length > 0 ? {
759
+ allOf: [schema],
760
+ ...extra
761
+ } : schema;
255
762
  };
256
763
  /**
257
764
  * Non-primitive type defs being built: `true` once re-entered (recursive). A named object
@@ -288,7 +795,7 @@ function isPlainObject$1(value) {
288
795
  * A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
289
796
  * them instead, its recursion referring to the shared definition.
290
797
  */ function* refTo(typeDef, def, own) {
291
- if (def === own || inlining.has(def) || sameConstraints(def, own)) return ref(typeDef);
798
+ if (def === own || inlining.has(def) || sameConstraints(def, own)) return useOf(ref(typeDef), def, own);
292
799
  inlining.add(def);
293
800
  const schema = yield buildDef(def);
294
801
  inlining.delete(def);
@@ -318,6 +825,7 @@ function isPlainObject$1(value) {
318
825
  for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
319
826
  schema.patternProperties = patternProperties(built, Object.keys(properties));
320
827
  }
828
+ if (closed) schema.additionalProperties = false;
321
829
  return schema;
322
830
  }
323
831
  /** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
@@ -327,14 +835,17 @@ function isPlainObject$1(value) {
327
835
  const atRoot = def === type && !rootEntered;
328
836
  rootEntered = true;
329
837
  if (def.id && typeDef.kind === "object" && !atRoot) {
838
+ const own = annotations ? ownDef(def, type) ?? def : void 0;
330
839
  if (!defs.has(typeDef)) {
331
840
  reserve(typeDef, def.id, true);
332
841
  const outer = building;
333
842
  building = /* @__PURE__ */ new Map();
334
- defs.get(typeDef).schema = yield buildObject(def);
843
+ const entry = yield buildObject(def);
844
+ if (own) applyAnnotationKeywords(entry, own.metadata);
845
+ defs.get(typeDef).schema = entry;
335
846
  building = outer;
336
847
  }
337
- return withKeyCounts(ref(typeDef), def.metadata);
848
+ return useOf(ref(typeDef), def, own, true);
338
849
  }
339
850
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
340
851
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -363,7 +874,7 @@ function isPlainObject$1(value) {
363
874
  const own = ownOf(def);
364
875
  const same = def === own || sameConstraints(def, own);
365
876
  defs.get(typeDef).schema = same ? schema : yield buildDef(own);
366
- return def === type || !same ? schema : ref(typeDef);
877
+ return def === type || !same ? schema : useOf(ref(typeDef), def, own);
367
878
  }
368
879
  /** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
369
880
  const ownOf = (def) => {
@@ -374,7 +885,12 @@ function isPlainObject$1(value) {
374
885
  }
375
886
  return own;
376
887
  };
377
- /** The schema of `def`'s own type (see {@link build}). */ function* buildDef(def) {
888
+ /** The schema of `def`'s own type (see {@link build}), with its title / description. */ function* buildDef(def) {
889
+ const schema = yield buildBody(def);
890
+ if (annotations) applyAnnotationKeywords(schema, def.metadata);
891
+ return schema;
892
+ }
893
+ /** The schema of `def`'s own type, without its title / description (see {@link buildDef}). */ function* buildBody(def) {
378
894
  const meta = def.metadata;
379
895
  const all = function* (items) {
380
896
  const out = [];
@@ -429,7 +945,7 @@ function isPlainObject$1(value) {
429
945
  };
430
946
  } else {
431
947
  if (!require_user_text.metaEmpty(meta)) applyUnionConstraints(built, meta, items);
432
- schema = { anyOf: built };
948
+ schema = enums && enumOf(built, refSchemas) || { anyOf: built };
433
949
  }
434
950
  applyKeyCounts(schema, meta);
435
951
  return schema;
@@ -682,13 +1198,41 @@ function withoutUniqueItems(meta) {
682
1198
  const maxKeys = meta.get("expect.maxKeys");
683
1199
  if (maxKeys !== void 0) schema.maxProperties = require_user_text.boundOf(maxKeys, "count");
684
1200
  }
685
- /** `schema` (a `$ref`) with the key counts of `meta`, if any (beside it, in an `allOf`). */ function withKeyCounts(schema, meta) {
686
- const counts = {};
687
- applyKeyCounts(counts, meta);
688
- return Object.keys(counts).length > 0 ? {
689
- allOf: [schema],
690
- ...counts
691
- } : schema;
1201
+ /** `@meta.label` → `title`, `@meta.description` → `description` (see `annotations`). */ function applyAnnotationKeywords(schema, meta, except) {
1202
+ if (require_user_text.metaEmpty(meta)) return;
1203
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) {
1204
+ const value = meta.get(key);
1205
+ if (value !== void 0 && value !== except?.get(key)) schema[keyword] = value;
1206
+ }
1207
+ }
1208
+ /**
1209
+ * The `{ type, enum }` schema of a union whose members are all literals (`const`, a nested
1210
+ * union of literals' `enum`, or `null`), at least one of them not `null`; `undefined` for any
1211
+ * other union (a member with other keywords — a title, a constraint — keeps the `anyOf`).
1212
+ */ function enumOf(members, refs) {
1213
+ const values = [];
1214
+ const types = [];
1215
+ let literal = false;
1216
+ for (const member of members) {
1217
+ if (refs.has(member)) return;
1218
+ const keys = Object.keys(member);
1219
+ let memberValues;
1220
+ if ("const" in member && keys.every((k) => k === "const" || k === "type")) {
1221
+ memberValues = [member.const];
1222
+ literal = true;
1223
+ } else if (Array.isArray(member.enum) && keys.every((k) => k === "enum" || k === "type")) {
1224
+ memberValues = member.enum;
1225
+ literal = true;
1226
+ } else if (member.type === "null" && keys.length === 1) memberValues = [null];
1227
+ else return;
1228
+ for (const value of memberValues) if (!values.includes(value)) values.push(value);
1229
+ for (const t of [member.type ?? []].flat()) if (!types.includes(t)) types.push(t);
1230
+ }
1231
+ if (!literal) return;
1232
+ const schema = {};
1233
+ if (types.length > 0) schema.type = types.length === 1 ? types[0] : types;
1234
+ schema.enum = values;
1235
+ return schema;
692
1236
  }
693
1237
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
694
1238
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
@@ -742,7 +1286,7 @@ const UPPER_BOUNDS = new Set([
742
1286
  applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
743
1287
  continue;
744
1288
  }
745
- if (member.const !== void 0) continue;
1289
+ if (member.const !== void 0 || member.enum !== void 0) continue;
746
1290
  const type = member.type;
747
1291
  const extra = { type };
748
1292
  if (type === "array") {
@@ -785,7 +1329,14 @@ const UPPER_BOUNDS = new Set([
785
1329
  */ function fromJsonSchema(schema) {
786
1330
  const defsSource = schema.$defs || schema.definitions || {};
787
1331
  const resolved = /* @__PURE__ */ new Map();
788
- const convert = (s) => {
1332
+ /** `title` → `@meta.label`, `description` → `@meta.description` (not on a shared `$ref`). */ const convert = (s) => {
1333
+ const type = convertNode(s);
1334
+ if (s && !s.$ref) {
1335
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) if (typeof s[keyword] === "string") require_user_text.annotate(type.metadata, key, s[keyword]);
1336
+ }
1337
+ return type;
1338
+ };
1339
+ const convertNode = (s) => {
789
1340
  if (!s || Object.keys(s).length === 0) return require_user_text.defineAnnotatedType().designType("any").$type;
790
1341
  if (s.$ref) {
791
1342
  const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
@@ -831,7 +1382,9 @@ const UPPER_BOUNDS = new Set([
831
1382
  const handle = require_user_text.defineAnnotatedType("union");
832
1383
  for (const t of s.type) handle.item(convert({
833
1384
  ...s,
834
- type: t
1385
+ type: t,
1386
+ title: void 0,
1387
+ description: void 0
835
1388
  }));
836
1389
  return handle.$type;
837
1390
  }
@@ -929,14 +1482,15 @@ const UPPER_BOUNDS = new Set([
929
1482
  * to it are renamed.
930
1483
  *
931
1484
  * @param types - Array of annotated types, each with an `id`.
1485
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
932
1486
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
933
- */ function mergeJsonSchemas(types) {
1487
+ */ function mergeJsonSchemas(types, opts) {
934
1488
  const mergedDefs = {};
935
1489
  const schemas = {};
936
1490
  for (const type of types) {
937
1491
  const name = type.id;
938
1492
  if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
939
- const { $defs: defs, ...schema } = buildJsonSchema(type);
1493
+ const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
940
1494
  if (!defs) {
941
1495
  schemas[name] = schema;
942
1496
  continue;
@@ -1184,13 +1738,14 @@ function isPlainObject(value) {
1184
1738
  /** The lazy JSON schema of each type, with the metadata write count it was built at. */ const lazy = /* @__PURE__ */ new WeakMap();
1185
1739
  /**
1186
1740
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
1187
- * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
1188
- * (`static toJsonSchema()`).
1189
- */ function lazyJsonSchema(type) {
1741
+ * a type tree write (a block, a runtime edit of metadata or shape: see `typeWrites`). Called by
1742
+ * generated code (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same
1743
+ * for every call of a type).
1744
+ */ function lazyJsonSchema(type, opts) {
1190
1745
  const known = lazy.get(type);
1191
- const writes = require_user_text.metadataWriteCount();
1746
+ const writes = require_user_text.typeWriteCount();
1192
1747
  if (known?.writes === writes) return known.schema;
1193
- const schema = buildJsonSchema(type);
1748
+ const schema = buildJsonSchema(type, opts);
1194
1749
  lazy.set(type, {
1195
1750
  writes,
1196
1751
  schema
@@ -1202,14 +1757,15 @@ function isPlainObject(value) {
1202
1757
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
1203
1758
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
1204
1759
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
1205
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
1206
- */ function bundledSchemaOf(type, literal, modules = []) {
1760
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
1761
+ * `jsonSchemaOptions` of the build (the literal was built with them).
1762
+ */ function bundledSchemaOf(type, literal, modules = [], opts) {
1207
1763
  const applied = require_user_text.appliedBlockModules();
1208
1764
  const known = bundled.get(type);
1209
1765
  if (known?.size === applied.size) return known.schema;
1210
1766
  const accounted = new Set(modules);
1211
1767
  const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
1212
- const schema = same ? literal() : buildJsonSchema(type);
1768
+ const schema = same ? literal() : buildJsonSchema(type, opts);
1213
1769
  bundled.set(type, {
1214
1770
  size: applied.size,
1215
1771
  schema,
@@ -1352,7 +1908,7 @@ function isPlainObject(value) {
1352
1908
 
1353
1909
  //#endregion
1354
1910
  //#region packages/typescript/src/runtime/serialize.ts
1355
- function _define_property(obj, key, value) {
1911
+ function _define_property$1(obj, key, value) {
1356
1912
  if (key in obj) Object.defineProperty(obj, key, {
1357
1913
  value,
1358
1914
  enumerable: true,
@@ -1424,17 +1980,17 @@ function _define_property(obj, key, value) {
1424
1980
  return id;
1425
1981
  }
1426
1982
  constructor() {
1427
- _define_property(this, "own", /* @__PURE__ */ new Map());
1983
+ _define_property$1(this, "own", /* @__PURE__ */ new Map());
1428
1984
  /**
1429
1985
  * The nodes without an id met more than once (see `indexPayload`): serialized once, with a
1430
1986
  * payload id, and referenced (`$ref`, `anon`) wherever else they are.
1431
- */ _define_property(this, "repeated", /* @__PURE__ */ new Set());
1432
- _define_property(this, "firstKeys", /* @__PURE__ */ new Map());
1433
- _define_property(this, "identities", /* @__PURE__ */ new WeakMap());
1434
- _define_property(this, "nextId", 0);
1435
- /** Payload ids by type def (see {@link keyOf}). */ _define_property(this, "keys", /* @__PURE__ */ new WeakMap());
1436
- /** The payload ids given so far. */ _define_property(this, "taken", /* @__PURE__ */ new Set());
1437
- /** The `cut` payload of defs (see `indexPayload`). */ _define_property(this, "cutKeys", /* @__PURE__ */ new WeakMap());
1987
+ */ _define_property$1(this, "repeated", /* @__PURE__ */ new Set());
1988
+ _define_property$1(this, "firstKeys", /* @__PURE__ */ new Map());
1989
+ _define_property$1(this, "identities", /* @__PURE__ */ new WeakMap());
1990
+ _define_property$1(this, "nextId", 0);
1991
+ /** Payload ids by type def (see {@link keyOf}). */ _define_property$1(this, "keys", /* @__PURE__ */ new WeakMap());
1992
+ /** The payload ids given so far. */ _define_property$1(this, "taken", /* @__PURE__ */ new Set());
1993
+ /** The `cut` payload of defs (see `indexPayload`). */ _define_property$1(this, "cutKeys", /* @__PURE__ */ new WeakMap());
1438
1994
  }
1439
1995
  };
1440
1996
  /**
@@ -1891,6 +2447,235 @@ function* deserializeTypeDef(t, resolved) {
1891
2447
  }
1892
2448
  }
1893
2449
 
2450
+ //#endregion
2451
+ //#region packages/typescript/src/runtime/translate-served.ts
2452
+ /**
2453
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
2454
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
2455
+ * collected for the client.
2456
+ */ function _define_property(obj, key, value) {
2457
+ if (key in obj) Object.defineProperty(obj, key, {
2458
+ value,
2459
+ enumerable: true,
2460
+ configurable: true,
2461
+ writable: true
2462
+ });
2463
+ else obj[key] = value;
2464
+ return obj;
2465
+ }
2466
+ /**
2467
+ * Translates the user-facing text of serialized annotated types (the output of
2468
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
2469
+ * found at any depth is read with {@link userTextOf}:
2470
+ *
2471
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
2472
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
2473
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
2474
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
2475
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
2476
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
2477
+ * translates the expressions' results by exact match.
2478
+ *
2479
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
2480
+ * result shares every part with no translated text, and is `json` itself when nothing was
2481
+ * translated.
2482
+ *
2483
+ * @example
2484
+ * ```ts
2485
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
2486
+ * i18n.exists(text) ? i18n.t(text) : undefined
2487
+ * )
2488
+ * ```
2489
+ */ function translateServed(json, t) {
2490
+ const texts = {};
2491
+ return {
2492
+ value: walk(json, void 0, {
2493
+ t,
2494
+ texts
2495
+ }),
2496
+ texts
2497
+ };
2498
+ }
2499
+ /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
2500
+ if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
2501
+ if (typeof value === "string") {
2502
+ if (mode === "expression") collectLiterals(value, ctx);
2503
+ else if (mode === true && require_user_text.formatCodeOf(value) === void 0) return translate(value, ctx) ?? value;
2504
+ return value;
2505
+ }
2506
+ if (typeof value !== "object" || value === null) return value;
2507
+ return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
2508
+ }
2509
+ /**
2510
+ * The mode of the value at `key` of an object of `mode`: a metadata key's user text, a field of a
2511
+ * value object's, else `metadata` objects only (a non-string text value — a `ref` target — has
2512
+ * metadata).
2513
+ */ function modeOf(key, mode) {
2514
+ if (typeof mode === "object") return mode.includes(`${key}()`) ? "expression" : mode.includes(key) || void 0;
2515
+ return mode === "metadata" && require_user_text.userTextOf(key) || (key === "metadata" ? "metadata" : void 0);
2516
+ }
2517
+ /** `t(text)` when it is a string (a plain-object dictionary also has `constructor`, …). */ function translate(text, ctx) {
2518
+ const out = ctx.t(text);
2519
+ return typeof out === "string" ? out : void 0;
2520
+ }
2521
+ /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
2522
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
2523
+ const translated = translate(literal, ctx);
2524
+ if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
2525
+ }
2526
+ }
2527
+ /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
2528
+ "n": "\n",
2529
+ "t": " ",
2530
+ "r": "\r",
2531
+ "b": "\b",
2532
+ "f": "\f",
2533
+ "v": "\v",
2534
+ "0": "\0",
2535
+ "\n": "",
2536
+ "\r": "",
2537
+ "\r\n": ""
2538
+ };
2539
+ /** 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;
2540
+ /** The string a literal's raw text (between its quotes) evaluates to. */ function decode(raw) {
2541
+ return raw.includes("\\") ? raw.replace(ESCAPE, (_, c) => {
2542
+ if (c.length < 3) return Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : c;
2543
+ const code = Number.parseInt(c.replace(/[ux{}]/g, ""), 16);
2544
+ return code > 1114111 ? "" : String.fromCodePoint(code);
2545
+ }) : raw;
2546
+ }
2547
+ /** A character of an identifier or a number. */ const IDENT = RegExp("[\\p{ID_Continue}$]", "u");
2548
+ /** A run of {@link IDENT} characters at `lastIndex`. */ const IDENT_RUN = RegExp("[\\p{ID_Continue}$]+", "uy");
2549
+ /** Keywords whose `(…)` a statement follows: a `/` after the `)` starts a regular expression. */ const CONTROL = new Set([
2550
+ "if",
2551
+ "while",
2552
+ "for",
2553
+ "with"
2554
+ ]);
2555
+ /** Keywords after which `/` starts a regular expression rather than a division. */ const REGEX_AFTER_WORD = new Set([
2556
+ "return",
2557
+ "typeof",
2558
+ "instanceof",
2559
+ "in",
2560
+ "of",
2561
+ "new",
2562
+ "delete",
2563
+ "void",
2564
+ "throw",
2565
+ "case",
2566
+ "do",
2567
+ "else",
2568
+ "yield",
2569
+ "await"
2570
+ ]);
2571
+ let LiteralScanner = class LiteralScanner {
2572
+ /** Scans code up to the end, or to the `}` closing a template's `${`. */ code() {
2573
+ const src = this.src;
2574
+ while (this.i < src.length) {
2575
+ const c = src[this.i];
2576
+ if (c === "/" && src[this.i + 1] === "/") {
2577
+ const end = src.indexOf("\n", this.i);
2578
+ this.i = end === -1 ? src.length : end;
2579
+ } else if (c === "/" && src[this.i + 1] === "*") {
2580
+ const end = src.indexOf("*/", this.i + 2);
2581
+ this.i = end === -1 ? src.length : end + 2;
2582
+ } else if (c === "'" || c === "\"" || c === "`") {
2583
+ const text = this.literal(c);
2584
+ if (text !== void 0 && text.trim() !== "") this.out.add(text);
2585
+ this.regexOk = false;
2586
+ } else if (c === "/" && this.regexOk) {
2587
+ this.regex();
2588
+ this.regexOk = false;
2589
+ } else if (IDENT.test(c)) this.word();
2590
+ else if ((c === "+" || c === "-") && src[this.i + 1] === c) {
2591
+ this.i += 2;
2592
+ this.regexOk = false;
2593
+ } else {
2594
+ this.i++;
2595
+ if (/\s/.test(c)) continue;
2596
+ if (c === "(" || c === "{") this.open.push(c === "(" ? "p" : c);
2597
+ else if (c === ")" || c === "}") {
2598
+ const top = this.open.pop();
2599
+ if (top === "$") return;
2600
+ this.regexOk = top === "c";
2601
+ continue;
2602
+ }
2603
+ this.regexOk = c !== "]";
2604
+ }
2605
+ }
2606
+ }
2607
+ /** An identifier, keyword or number at `i`; `i` past it (and past a control keyword's `(`). */ word() {
2608
+ const src = this.src;
2609
+ IDENT_RUN.lastIndex = this.i;
2610
+ IDENT_RUN.test(src);
2611
+ const word = src.slice(this.i, IDENT_RUN.lastIndex);
2612
+ this.i = IDENT_RUN.lastIndex;
2613
+ this.regexOk = REGEX_AFTER_WORD.has(word);
2614
+ if (CONTROL.has(word)) {
2615
+ while (/\s/.test(src[this.i] ?? "")) this.i++;
2616
+ if (src[this.i] === "(") {
2617
+ this.i++;
2618
+ this.open.push("c");
2619
+ this.regexOk = true;
2620
+ }
2621
+ }
2622
+ }
2623
+ /**
2624
+ * A `'…'` / `"…"` / `` `…` `` literal at `i`, decoded (`undefined`: a template with `${…}`, whose
2625
+ * code is scanned); `i` past it.
2626
+ */ literal(quote) {
2627
+ const src = this.src;
2628
+ const start = ++this.i;
2629
+ let plain = true;
2630
+ while (this.i < src.length && src[this.i] !== quote) if (src[this.i] === "\\") this.i += src.startsWith("\r\n", this.i + 1) ? 3 : 2;
2631
+ else if (quote === "`" && src.startsWith("${", this.i)) {
2632
+ plain = false;
2633
+ this.i += 2;
2634
+ this.open.push("$");
2635
+ this.code();
2636
+ } else this.i++;
2637
+ const end = this.i++;
2638
+ return plain ? decode(src.slice(start, end)) : void 0;
2639
+ }
2640
+ /** A regular expression literal starting at `i`; `i` past its flags. */ regex() {
2641
+ const src = this.src;
2642
+ let inClass = false;
2643
+ this.i++;
2644
+ while (this.i < src.length && src[this.i] !== "\n") {
2645
+ const c = src[this.i++];
2646
+ if (c === "\\") this.i++;
2647
+ else if (c === "[") inClass = true;
2648
+ else if (c === "]") inClass = false;
2649
+ else if (c === "/" && !inClass) break;
2650
+ }
2651
+ while (this.i < src.length && /[a-z]/i.test(src[this.i])) this.i++;
2652
+ }
2653
+ constructor(src, out) {
2654
+ _define_property(this, "src", void 0);
2655
+ _define_property(this, "out", void 0);
2656
+ _define_property(this, "i", void 0);
2657
+ /** A `/` here starts a regular expression (no operand just ended), not a division. */ _define_property(this, "regexOk", void 0);
2658
+ /**
2659
+ * The open brackets: `c` — the `(` of an `if` / `while` / `for` / `with` (a `/` after its `)` is
2660
+ * a regex); `p` — another `(`; `{`; `$` — a template's `${`.
2661
+ */ _define_property(this, "open", void 0);
2662
+ this.src = src;
2663
+ this.out = out;
2664
+ this.i = 0;
2665
+ this.regexOk = true;
2666
+ this.open = [];
2667
+ }
2668
+ };
2669
+ /**
2670
+ * The string literals of JavaScript `source`, as the strings they evaluate to: `'…'`, `"…"` and
2671
+ * `` `…` `` templates without `${…}` (the literals inside a `${…}` count). Comments and regular
2672
+ * expression literals are skipped; empty and blank literals are left out.
2673
+ */ function stringLiterals(source) {
2674
+ const out = /* @__PURE__ */ new Set();
2675
+ new LiteralScanner(source, out).code();
2676
+ return [...out];
2677
+ }
2678
+
1894
2679
  //#endregion
1895
2680
  exports.$ak = require_user_text.$ak;
1896
2681
  exports.$alias = require_user_text.$alias;
@@ -1934,11 +2719,14 @@ exports.localizeErrors = require_user_text.localizeErrors;
1934
2719
  exports.mergeJsonSchemas = mergeJsonSchemas;
1935
2720
  exports.messagesTranslator = require_user_text.messagesTranslator;
1936
2721
  exports.metaEmpty = require_user_text.metaEmpty;
2722
+ exports.normalizeForType = normalizeForType;
1937
2723
  exports.pendingStatements = require_user_text.pendingStatements;
1938
2724
  exports.registerCompiledCheck = require_user_text.registerCompiledCheck;
1939
2725
  exports.registerUserText = require_user_text.registerUserText;
1940
2726
  exports.serializeAnnotatedType = serializeAnnotatedType;
1941
2727
  exports.throwFeatureDisabled = throwFeatureDisabled;
2728
+ exports.translateServed = translateServed;
2729
+ exports.unionDiscriminator = require_user_text.unionDiscriminator;
1942
2730
  exports.userTextKeys = require_user_text.userTextKeys;
1943
2731
  exports.userTextOf = require_user_text.userTextOf;
1944
2732
  exports.watchLayer = require_user_text.watchLayer;