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