@atscript/typescript 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.mjs CHANGED
@@ -1,10 +1,91 @@
1
- import { A as statelessRegExp, B as VALIDATOR_KEYS, C as isAnnotatedTypeOfPrimitive, D as ValidatorError, E as Validator, F as watchLayer, H as boundOf, I as invalidateCompiledValidators, L as metadataWriteCount, M as $nr, N as LayerMap, O as registerCompiledCheck, P as metaEmpty, R as touched, S as isAnnotatedType, T as propAtChain, V as arrayKeyProps, _ as annotate, a as $f, b as createObjectTypeDef, c as $ps, d as appliedBlockModules, f as pendingStatements, g as enterCut, h as cutKey, i as $end, j as $ak, k as jsonSchemaPattern, l as $q, m as cutAs, n as $alias, o as $fc, r as $blk, s as $ft, t as uniqueName, u as $sh, v as createAnnotatedTypeNode, w as isPhantomType, x as defineAnnotatedType, y as createMetadataMap, z as DECIMAL_RE } from "./unique-name-hg1CyPIs.mjs";
1
+ import { $ as DECIMAL_RE, 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 touched, R as localizeErrors, S as annotate, T as createObjectTypeDef, U as statelessRegExp, V as detectDiscriminator, W as $ak, X as invalidateCompiledValidators, Y as currentEpoch, Z as metadataWriteCount, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, et as VALIDATOR_KEYS, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, nt as boundOf, o as uniqueName, p as $ps, q as metaEmpty, r as registerUserText, s as $alias, t as $ut, tt as arrayKeyProps, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as messagesTranslator } from "./user-text-BOf56N4d.mjs";
2
2
 
3
- //#region packages/typescript/src/runtime/coerce.ts
3
+ //#region packages/typescript/src/runtime/copy-on-change.ts
4
4
  /**
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");
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/coerce.ts
8
89
  /**
9
90
  * Coerces string-transport input (route params, query strings) toward the
10
91
  * scalar shapes an annotated type expects.
@@ -54,11 +135,11 @@ import { A as statelessRegExp, B as VALIDATOR_KEYS, C as isAnnotatedTypeOfPrimit
54
135
  }
55
136
  case "object":
56
137
  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;
138
+ return mapProps(type, value, coerceChild, void 0);
139
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
59
140
  case "tuple": {
60
141
  const items = type.items;
61
- return Array.isArray(value) && value.length === items.length ? coerceItems(value, void 0, items) : NO_MATCH;
142
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
62
143
  }
63
144
  case "union":
64
145
  for (const item of type.items) {
@@ -103,57 +184,289 @@ function scalar(designType, value) {
103
184
  default: return NO_MATCH;
104
185
  }
105
186
  }
187
+ /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
188
+ const result = coerce(def, input);
189
+ return result === NO_MATCH ? input : result;
190
+ }
191
+
192
+ //#endregion
193
+ //#region packages/typescript/src/runtime/normalize.ts
194
+ const TRIM = 1;
195
+ const LOWERCASE = 2;
196
+ const UPPERCASE = 4;
106
197
  /**
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;
198
+ * Whether each node's subtree has normalizers: valid until the next metadata write or
199
+ * `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
200
+ */ let reach = /* @__PURE__ */ new WeakMap();
201
+ let stampWrites = -1;
202
+ let stampEpoch = -1;
203
+ /**
204
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
205
+ * `@normalize.lowercase` and `@normalize.uppercase`.
206
+ *
207
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
208
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
209
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
210
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
211
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
212
+ * uppercase. Other values (including class instances such as `Date`) and strings without
213
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
214
+ *
215
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
216
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
217
+ * value is left as it is. A union normalizes a value only when the result does not depend on
218
+ * which branch takes it:
219
+ * - an object union with a discriminator (a literal prop every object branch requires, see
220
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
221
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
222
+ * only when the normalized string equals its literal): when they all give the same result it
223
+ * is used; when they differ, the branches whose result their own validator accepts (default
224
+ * options) are kept, and the result is used when they agree; else the value is returned
225
+ * untouched (ambiguous).
226
+ *
227
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * // @normalize.trim @normalize.lowercase email: string.email
232
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
233
+ * ```
234
+ */ function normalizeForType(def, value) {
235
+ const writes = metadataWriteCount();
236
+ const epoch = currentEpoch();
237
+ if (writes !== stampWrites || epoch !== stampEpoch) {
238
+ stampWrites = writes;
239
+ stampEpoch = epoch;
240
+ reach = /* @__PURE__ */ new WeakMap();
241
+ }
242
+ if (!hasNormalizers(def)) return value;
243
+ const result = normalize(def, value, 0, /* @__PURE__ */ new Map());
244
+ return result === NO_MATCH ? value : result;
245
+ }
246
+ /** The nodes `def`'s value walk can enter (props, pattern props, items, elements). */ function childrenOf(def) {
247
+ const type = def.type;
248
+ switch (type.kind) {
249
+ case "object": {
250
+ const t = type;
251
+ const out = [...t.props.values()];
252
+ for (const p of t.propsPatterns) out.push(p.def);
253
+ return out;
254
+ }
255
+ case "array": return [type.of];
256
+ case "union":
257
+ case "intersection":
258
+ case "tuple": return type.items;
259
+ default: return [];
260
+ }
261
+ }
262
+ /**
263
+ * Whether `def` or a node its walk reaches has normalizers. Answers (and caches) every node
264
+ * reached, recursive types included: collects the reached nodes with their parents, then marks
265
+ * the nodes with normalizers and, back along the parents, every node that reaches one.
266
+ */ function hasNormalizers(def) {
267
+ const known = reach.get(def);
268
+ if (known !== void 0) return known;
269
+ const parents = new Map([[def, []]]);
270
+ const marked = [];
271
+ const todo = [def];
272
+ while (todo.length > 0) {
273
+ const node = todo.pop();
274
+ if (flagsOf(node, 0) !== 0) marked.push(node);
275
+ for (const child of childrenOf(node)) {
276
+ const cached = reach.get(child);
277
+ if (cached !== void 0) {
278
+ if (cached) marked.push(node);
279
+ continue;
120
280
  }
281
+ let of = parents.get(child);
282
+ if (!of) {
283
+ parents.set(child, of = []);
284
+ todo.push(child);
285
+ }
286
+ of.push(node);
121
287
  }
122
- let coerced = input;
123
- if (propDef) {
124
- const result = coerce(propDef, input);
125
- if (result !== NO_MATCH) coerced = result;
288
+ }
289
+ for (const node of parents.keys()) reach.set(node, false);
290
+ while (marked.length > 0) {
291
+ const node = marked.pop();
292
+ if (!reach.get(node)) {
293
+ reach.set(node, true);
294
+ marked.push(...parents.get(node));
126
295
  }
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;
296
+ }
297
+ return reach.get(def);
298
+ }
299
+ /** The normalizer flags of `def`, on top of `inherited` (a union's, for its branches). */ function flagsOf(def, inherited) {
300
+ const meta = def.metadata;
301
+ if (metaEmpty(meta)) return inherited;
302
+ let flags = inherited;
303
+ if (meta.get("normalize.trim")) flags |= TRIM;
304
+ if (meta.get("normalize.lowercase")) flags |= LOWERCASE;
305
+ if (meta.get("normalize.uppercase")) flags |= UPPERCASE;
306
+ return flags;
307
+ }
308
+ function applyFlags(value, flags) {
309
+ let out = value;
310
+ if (flags & TRIM) out = out.trim();
311
+ if (flags & LOWERCASE) out = out.toLowerCase();
312
+ if (flags & UPPERCASE) out = out.toUpperCase();
313
+ return out;
314
+ }
315
+ /**
316
+ * The normalized value, or NO_MATCH when `def` cannot take it (its kind does not fit the value).
317
+ * `inherited`: the normalizer flags of the unions / intersections `def` is a member of.
318
+ *
319
+ * Objects and unions are memoized per call by input object: a recursive union without a
320
+ * discriminator is tried for every branch at every level, which without it is exponential in
321
+ * the depth of the value.
322
+ */ function normalize(def, value, inherited, memo) {
323
+ if (value === void 0 || value === null) return value;
324
+ if (inherited === 0 && !hasNormalizers(def)) return takes(def, value) ? value : NO_MATCH;
325
+ const type = def.type;
326
+ switch (type.kind) {
327
+ case "": {
328
+ const out = typeof value === "string" && type.designType === "string" ? applyFlags(value, flagsOf(def, inherited)) : value;
329
+ return takes(def, out) ? out : NO_MATCH;
330
+ }
331
+ case "object": {
332
+ if (!isPlainObject$1(value)) return NO_MATCH;
333
+ const entries = entriesOf(memo, value);
334
+ return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, memo));
335
+ }
336
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, memo) : NO_MATCH;
337
+ case "tuple": {
338
+ const items = type.items;
339
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, memo) : NO_MATCH;
340
+ }
341
+ case "union": {
342
+ const flags = flagsOf(def, inherited);
343
+ const items = type.items;
344
+ if (typeof value !== "object") return normalizeUnion(items, value, flags, memo);
345
+ const entries = entriesOf(memo, value);
346
+ return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, memo));
347
+ }
348
+ case "intersection": {
349
+ const flags = flagsOf(def, inherited);
350
+ let current = value;
351
+ for (const item of type.items) {
352
+ const result = normalize(item, current, flags, memo);
353
+ if (result === NO_MATCH) return NO_MATCH;
354
+ current = result;
355
+ }
356
+ return current;
132
357
  }
358
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
133
359
  }
134
- return out ?? value;
360
+ }
361
+ /** The memoized results for input object `value` (see {@link normalize}). */ function entriesOf(memo, value) {
362
+ let entries = memo.get(value);
363
+ if (!entries) {
364
+ entries = [];
365
+ memo.set(value, entries);
366
+ }
367
+ return entries;
368
+ }
369
+ /** The memoized result for `type` and `flags`, `undefined` when none. */ function recall(entries, type, flags) {
370
+ for (const [t, f, result] of entries) if (t === type && f === flags) return result;
371
+ }
372
+ /** Memoizes `result` for `type` and `flags` and returns it. */ function remember(entries, type, flags, result) {
373
+ entries.push([
374
+ type,
375
+ flags,
376
+ result
377
+ ]);
378
+ return result;
379
+ }
380
+ /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, memo) {
381
+ if (!hasNormalizers(def)) return input;
382
+ const result = normalize(def, input, 0, memo);
383
+ return result === NO_MATCH ? input : result;
135
384
  }
136
385
  /**
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);
386
+ * A prop: as {@link normalizeItem}, but NO_MATCH (the object is not this type) when a literal prop
387
+ * (`kind: 'cat'`) holds another value.
388
+ */ function normalizeProp(def, input, memo) {
389
+ const out = normalizeItem(def, input, memo);
390
+ if (out === input && def.type.kind === "" && def.type.value !== void 0 && input !== def.type.value && input !== void 0 && input !== null) return NO_MATCH;
391
+ return out;
392
+ }
393
+ /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes(def, value) {
394
+ const type = def.type;
395
+ switch (type.kind) {
396
+ case "": {
397
+ const final = type;
398
+ switch (final.designType) {
399
+ case "string":
400
+ case "number":
401
+ case "boolean": return typeof value === final.designType && (final.value === void 0 || value === final.value);
402
+ case "decimal": return typeof value === "string";
403
+ case "object": return typeof value === "object";
404
+ case "any":
405
+ case "phantom": return true;
406
+ default: return false;
407
+ }
149
408
  }
409
+ case "object": return isPlainObject$1(value);
410
+ case "array": return Array.isArray(value);
411
+ case "tuple": return Array.isArray(value) && value.length === type.items.length;
412
+ case "union": return type.items.some((item) => takes(item, value));
413
+ case "intersection": return type.items.every((item) => takes(item, value));
414
+ default: return false;
150
415
  }
151
- return out ?? value;
152
416
  }
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;
417
+ /**
418
+ * A union: the branch a discriminator names, else the one result every branch that can take
419
+ * the value agrees on — or, when they differ, the one result of the branches whose validator
420
+ * accepts their result (NO_MATCH when none can take the value or it stays ambiguous).
421
+ */ function normalizeUnion(items, value, flags, memo) {
422
+ if (isPlainObject$1(value)) {
423
+ const disc = unionDiscriminator(items);
424
+ if (disc) {
425
+ const tag = value[disc.property];
426
+ for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, memo);
427
+ }
428
+ }
429
+ let first = NO_MATCH;
430
+ let firstItem;
431
+ let rest;
432
+ for (const item of items) {
433
+ const out = normalize(item, value, flags, memo);
434
+ if (out === NO_MATCH) continue;
435
+ if (first === NO_MATCH) {
436
+ first = out;
437
+ firstItem = item;
438
+ } else (rest ?? (rest = [])).push([item, out]);
439
+ }
440
+ if (!rest || rest.every(([, out]) => sameValue(out, first))) return first;
441
+ rest.unshift([firstItem, first]);
442
+ let accepted = NO_MATCH;
443
+ for (const [item, out] of rest) {
444
+ if (!branchValidator(item).validate(out, true)) continue;
445
+ if (accepted === NO_MATCH) accepted = out;
446
+ else if (!sameValue(accepted, out)) return NO_MATCH;
447
+ }
448
+ return accepted;
449
+ }
450
+ /**
451
+ * Each union branch's validator (default options; one error is enough to reject a result),
452
+ * judging its own normalized result.
453
+ */ const branchValidators = /* @__PURE__ */ new WeakMap();
454
+ function branchValidator(def) {
455
+ let validator = branchValidators.get(def);
456
+ if (!validator) {
457
+ validator = new Validator(def, { errorLimit: 1 });
458
+ branchValidators.set(def, validator);
459
+ }
460
+ return validator;
461
+ }
462
+ /** Whether two results of the same input are equal (shared, untouched parts are identical). */ function sameValue(a, b) {
463
+ if (a === b) return true;
464
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
465
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
466
+ const keys = Object.keys(a);
467
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
468
+ }
469
+ return false;
157
470
  }
158
471
 
159
472
  //#endregion
@@ -205,48 +518,7 @@ function isPlainObject$1(value) {
205
518
 
206
519
  //#endregion
207
520
  //#region packages/typescript/src/runtime/json-schema.ts
208
- /**
209
- * Detects a discriminator property across union items.
210
- *
211
- * Scans all items for object-typed members that share a common property
212
- * with distinct const/literal values. If exactly one such property exists,
213
- * it is returned as the discriminator. Returns `null` when no qualifying
214
- * property exists, or when more than one does (ambiguous).
215
- */ function detectDiscriminator(items) {
216
- if (items.length < 2) return null;
217
- for (const item of items) if (item.type.kind !== "object") return null;
218
- const firstObj = items[0].type;
219
- const candidates = [];
220
- for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
221
- let result = null;
222
- for (const candidate of candidates) {
223
- const values = /* @__PURE__ */ new Set();
224
- const indexMapping = {};
225
- let valid = true;
226
- for (let i = 0; i < items.length; i++) {
227
- const prop = items[i].type.props.get(candidate);
228
- if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
229
- valid = false;
230
- break;
231
- }
232
- const val = prop.type.value;
233
- if (values.has(val)) {
234
- valid = false;
235
- break;
236
- }
237
- values.add(val);
238
- indexMapping[String(val)] = i;
239
- }
240
- if (valid) {
241
- if (result) return null;
242
- result = {
243
- propertyName: candidate,
244
- indexMapping
245
- };
246
- }
247
- }
248
- return result;
249
- }
521
+ /** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
250
522
  /**
251
523
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
252
524
  *
@@ -262,8 +534,12 @@ function isPlainObject$1(value) {
262
534
  * ```
263
535
  *
264
536
  * @param type - The annotated type to convert.
537
+ * @param opts - {@link TJsonSchemaOptions}.
265
538
  * @returns A JSON Schema object.
266
- */ function buildJsonSchema(type) {
539
+ */ function buildJsonSchema(type, opts) {
540
+ const closed = opts?.closed === true;
541
+ const annotations = opts?.annotations !== false;
542
+ const enums = opts?.enums !== false;
267
543
  /**
268
544
  * `$defs` entries by type def (identity): named objects (always extracted) and types found
269
545
  * recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
@@ -291,8 +567,35 @@ function isPlainObject$1(value) {
291
567
  ...schema,
292
568
  type: [schema.type, "null"]
293
569
  };
294
- if (Object.keys(schema).length === 1 && Array.isArray(schema.anyOf)) return { anyOf: [...schema.anyOf, { type: "null" }] };
295
- return { anyOf: [schema, { type: "null" }] };
570
+ const notes = {};
571
+ let body = schema;
572
+ for (const [, keyword] of ANNOTATION_KEYWORDS) if (body[keyword] !== void 0) {
573
+ if (body === schema) body = { ...schema };
574
+ notes[keyword] = body[keyword];
575
+ delete body[keyword];
576
+ }
577
+ if (body !== schema && Object.keys(body).length === 1 && body.allOf?.length === 1) body = body.allOf[0];
578
+ if (Object.keys(body).length === 1 && Array.isArray(body.anyOf)) return {
579
+ anyOf: [...body.anyOf, { type: "null" }],
580
+ ...notes
581
+ };
582
+ return {
583
+ anyOf: [body, { type: "null" }],
584
+ ...notes
585
+ };
586
+ };
587
+ /**
588
+ * A use of a `$defs` entry: `schema` (its `$ref`) with what the use adds to the entry (built
589
+ * from `own`, see `ownDef`): its key counts, and its title / description when they differ
590
+ * from the entry's — beside the reference, in an `allOf`.
591
+ */ const useOf = (schema, def, own, keyCounts = false) => {
592
+ const extra = {};
593
+ if (annotations) applyAnnotationKeywords(extra, def.metadata, own?.metadata);
594
+ if (keyCounts) applyKeyCounts(extra, def.metadata);
595
+ return Object.keys(extra).length > 0 ? {
596
+ allOf: [schema],
597
+ ...extra
598
+ } : schema;
296
599
  };
297
600
  /**
298
601
  * Non-primitive type defs being built: `true` once re-entered (recursive). A named object
@@ -329,7 +632,7 @@ function isPlainObject$1(value) {
329
632
  * A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
330
633
  * them instead, its recursion referring to the shared definition.
331
634
  */ function* refTo(typeDef, def, own) {
332
- if (def === own || inlining.has(def) || sameConstraints(def, own)) return ref(typeDef);
635
+ if (def === own || inlining.has(def) || sameConstraints(def, own)) return useOf(ref(typeDef), def, own);
333
636
  inlining.add(def);
334
637
  const schema = yield buildDef(def);
335
638
  inlining.delete(def);
@@ -359,6 +662,7 @@ function isPlainObject$1(value) {
359
662
  for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
360
663
  schema.patternProperties = patternProperties(built, Object.keys(properties));
361
664
  }
665
+ if (closed) schema.additionalProperties = false;
362
666
  return schema;
363
667
  }
364
668
  /** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
@@ -368,14 +672,17 @@ function isPlainObject$1(value) {
368
672
  const atRoot = def === type && !rootEntered;
369
673
  rootEntered = true;
370
674
  if (def.id && typeDef.kind === "object" && !atRoot) {
675
+ const own = annotations ? ownDef(def, type) ?? def : void 0;
371
676
  if (!defs.has(typeDef)) {
372
677
  reserve(typeDef, def.id, true);
373
678
  const outer = building;
374
679
  building = /* @__PURE__ */ new Map();
375
- defs.get(typeDef).schema = yield buildObject(def);
680
+ const entry = yield buildObject(def);
681
+ if (own) applyAnnotationKeywords(entry, own.metadata);
682
+ defs.get(typeDef).schema = entry;
376
683
  building = outer;
377
684
  }
378
- return ref(typeDef);
685
+ return useOf(ref(typeDef), def, own, true);
379
686
  }
380
687
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
381
688
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -404,7 +711,7 @@ function isPlainObject$1(value) {
404
711
  const own = ownOf(def);
405
712
  const same = def === own || sameConstraints(def, own);
406
713
  defs.get(typeDef).schema = same ? schema : yield buildDef(own);
407
- return def === type || !same ? schema : ref(typeDef);
714
+ return def === type || !same ? schema : useOf(ref(typeDef), def, own);
408
715
  }
409
716
  /** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
410
717
  const ownOf = (def) => {
@@ -415,7 +722,12 @@ function isPlainObject$1(value) {
415
722
  }
416
723
  return own;
417
724
  };
418
- /** The schema of `def`'s own type (see {@link build}). */ function* buildDef(def) {
725
+ /** The schema of `def`'s own type (see {@link build}), with its title / description. */ function* buildDef(def) {
726
+ const schema = yield buildBody(def);
727
+ if (annotations) applyAnnotationKeywords(schema, def.metadata);
728
+ return schema;
729
+ }
730
+ /** The schema of `def`'s own type, without its title / description (see {@link buildDef}). */ function* buildBody(def) {
419
731
  const meta = def.metadata;
420
732
  const all = function* (items) {
421
733
  const out = [];
@@ -423,7 +735,11 @@ function isPlainObject$1(value) {
423
735
  return out;
424
736
  };
425
737
  const kind = def.type.kind;
426
- if (kind === "object") return yield buildObject(def);
738
+ if (kind === "object") {
739
+ const schema = yield buildObject(def);
740
+ applyKeyCounts(schema, meta);
741
+ return schema;
742
+ }
427
743
  if (kind === "array") {
428
744
  const d = def;
429
745
  const schema = {
@@ -445,6 +761,7 @@ function isPlainObject$1(value) {
445
761
  maxItems: items.length
446
762
  };
447
763
  const disc = detectDiscriminator(items);
764
+ let schema;
448
765
  if (disc) {
449
766
  const mapping = {};
450
767
  for (const [val, idx] of Object.entries(disc.indexMapping)) {
@@ -456,16 +773,19 @@ function isPlainObject$1(value) {
456
773
  ]);
457
774
  else mapping[val] = `#/oneOf/${idx}`;
458
775
  }
459
- return {
776
+ schema = {
460
777
  oneOf: built,
461
778
  discriminator: {
462
779
  propertyName: disc.propertyName,
463
780
  mapping
464
781
  }
465
782
  };
783
+ } else {
784
+ if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
785
+ schema = enums && enumOf(built, refSchemas) || { anyOf: built };
466
786
  }
467
- if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
468
- return { anyOf: built };
787
+ applyKeyCounts(schema, meta);
788
+ return schema;
469
789
  }
470
790
  return forAnnotatedType(def, {
471
791
  phantom() {
@@ -706,6 +1026,51 @@ function withoutUniqueItems(meta) {
706
1026
  const maxLength = meta.get("expect.maxLength");
707
1027
  if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
708
1028
  }
1029
+ /**
1030
+ * `@expect.minKeys` / `maxKeys` → `minProperties` / `maxProperties` (they constrain objects
1031
+ * only, so they also sit on a union's schema as they are).
1032
+ */ function applyKeyCounts(schema, meta) {
1033
+ const minKeys = meta.get("expect.minKeys");
1034
+ if (minKeys !== void 0) schema.minProperties = boundOf(minKeys, "count");
1035
+ const maxKeys = meta.get("expect.maxKeys");
1036
+ if (maxKeys !== void 0) schema.maxProperties = boundOf(maxKeys, "count");
1037
+ }
1038
+ /** `@meta.label` → `title`, `@meta.description` → `description` (see `annotations`). */ function applyAnnotationKeywords(schema, meta, except) {
1039
+ if (metaEmpty(meta)) return;
1040
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) {
1041
+ const value = meta.get(key);
1042
+ if (value !== void 0 && value !== except?.get(key)) schema[keyword] = value;
1043
+ }
1044
+ }
1045
+ /**
1046
+ * The `{ type, enum }` schema of a union whose members are all literals (`const`, a nested
1047
+ * union of literals' `enum`, or `null`), at least one of them not `null`; `undefined` for any
1048
+ * other union (a member with other keywords — a title, a constraint — keeps the `anyOf`).
1049
+ */ function enumOf(members, refs) {
1050
+ const values = [];
1051
+ const types = [];
1052
+ let literal = false;
1053
+ for (const member of members) {
1054
+ if (refs.has(member)) return;
1055
+ const keys = Object.keys(member);
1056
+ let memberValues;
1057
+ if ("const" in member && keys.every((k) => k === "const" || k === "type")) {
1058
+ memberValues = [member.const];
1059
+ literal = true;
1060
+ } else if (Array.isArray(member.enum) && keys.every((k) => k === "enum" || k === "type")) {
1061
+ memberValues = member.enum;
1062
+ literal = true;
1063
+ } else if (member.type === "null" && keys.length === 1) memberValues = [null];
1064
+ else return;
1065
+ for (const value of memberValues) if (!values.includes(value)) values.push(value);
1066
+ for (const t of [member.type ?? []].flat()) if (!types.includes(t)) types.push(t);
1067
+ }
1068
+ if (!literal) return;
1069
+ const schema = {};
1070
+ if (types.length > 0) schema.type = types.length === 1 ? types[0] : types;
1071
+ schema.enum = values;
1072
+ return schema;
1073
+ }
709
1074
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
710
1075
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
711
1076
  if (schema.type === "string") {
@@ -758,7 +1123,7 @@ const UPPER_BOUNDS = new Set([
758
1123
  applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
759
1124
  continue;
760
1125
  }
761
- if (member.const !== void 0) continue;
1126
+ if (member.const !== void 0 || member.enum !== void 0) continue;
762
1127
  const type = member.type;
763
1128
  const extra = { type };
764
1129
  if (type === "array") {
@@ -801,7 +1166,14 @@ const UPPER_BOUNDS = new Set([
801
1166
  */ function fromJsonSchema(schema) {
802
1167
  const defsSource = schema.$defs || schema.definitions || {};
803
1168
  const resolved = /* @__PURE__ */ new Map();
804
- const convert = (s) => {
1169
+ /** `title` → `@meta.label`, `description` → `@meta.description` (not on a shared `$ref`). */ const convert = (s) => {
1170
+ const type = convertNode(s);
1171
+ if (s && !s.$ref) {
1172
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) if (typeof s[keyword] === "string") annotate(type.metadata, key, s[keyword]);
1173
+ }
1174
+ return type;
1175
+ };
1176
+ const convertNode = (s) => {
805
1177
  if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
806
1178
  if (s.$ref) {
807
1179
  const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
@@ -847,7 +1219,9 @@ const UPPER_BOUNDS = new Set([
847
1219
  const handle = defineAnnotatedType("union");
848
1220
  for (const t of s.type) handle.item(convert({
849
1221
  ...s,
850
- type: t
1222
+ type: t,
1223
+ title: void 0,
1224
+ description: void 0
851
1225
  }));
852
1226
  return handle.$type;
853
1227
  }
@@ -861,6 +1235,8 @@ const UPPER_BOUNDS = new Set([
861
1235
  handle.prop(key, propType);
862
1236
  }
863
1237
  for (const [pattern, propSchema] of Object.entries(s.patternProperties ?? {})) handle.propPattern(compilePattern(pattern), convert(propSchema));
1238
+ if (typeof s.minProperties === "number") handle.annotate("expect.minKeys", { count: s.minProperties });
1239
+ if (typeof s.maxProperties === "number") handle.annotate("expect.maxKeys", { count: s.maxProperties });
864
1240
  return handle.$type;
865
1241
  }
866
1242
  if (s.type === "array") {
@@ -943,14 +1319,15 @@ const UPPER_BOUNDS = new Set([
943
1319
  * to it are renamed.
944
1320
  *
945
1321
  * @param types - Array of annotated types, each with an `id`.
1322
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
946
1323
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
947
- */ function mergeJsonSchemas(types) {
1324
+ */ function mergeJsonSchemas(types, opts) {
948
1325
  const mergedDefs = {};
949
1326
  const schemas = {};
950
1327
  for (const type of types) {
951
1328
  const name = type.id;
952
1329
  if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
953
- const { $defs: defs, ...schema } = buildJsonSchema(type);
1330
+ const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
954
1331
  if (!defs) {
955
1332
  schemas[name] = schema;
956
1333
  continue;
@@ -1025,27 +1402,31 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1025
1402
  }
1026
1403
  if (mode === "db") {
1027
1404
  const dbValue = prop.metadata.get("db.default");
1028
- if (dbValue !== void 0) {
1029
- const parsed = parseRawValue(dbValue, prop);
1030
- if (parsed !== void 0 && prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
1031
- return;
1032
- }
1405
+ if (dbValue !== void 0) return validRawValue(dbValue, prop);
1033
1406
  if (prop.metadata.has("db.default.increment")) return { value: "increment" };
1034
1407
  if (prop.metadata.has("db.default.uuid")) return { value: "uuid" };
1035
1408
  if (prop.metadata.has("db.default.now")) return { value: "now" };
1036
1409
  return;
1037
1410
  }
1038
1411
  const metaKey = mode === "default" ? "meta.default" : "meta.example";
1039
- const rawStr = prop.metadata.get(metaKey);
1040
- if (rawStr === void 0) return;
1041
- const parsed = parseRawValue(rawStr, prop);
1042
- if (parsed === void 0) return;
1043
- if (prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
1412
+ const metaValue = prop.metadata.get(metaKey);
1413
+ if (metaValue === void 0) return;
1414
+ return validRawValue(metaValue, prop);
1415
+ }
1416
+ /**
1417
+ * An annotation's raw value as a valid value of `prop` (see {@link parseRawValue}); a string the
1418
+ * JSON reading does not fit is tried as the string itself (a `decimal` field, `decimal | null`).
1419
+ */ function validRawValue(raw, prop) {
1420
+ const validator = prop.validator({ unknownProps: "ignore" });
1421
+ const parsed = parseRawValue(raw, prop);
1422
+ if (parsed !== void 0 && validator.validate(parsed, true)) return { value: parsed };
1423
+ if (typeof raw === "string" && parsed !== raw && validator.validate(raw, true)) return { value: raw };
1044
1424
  }
1045
1425
  /**
1046
- * Parses a raw annotation string into a JS value.
1047
- * Strings are returned as-is for string types; everything else goes through JSON.parse.
1426
+ * Parses a raw annotation value into a JS value: a number / boolean literal (a `value`
1427
+ * argument) as it is; a string as-is for string types, else through JSON.parse.
1048
1428
  */ function parseRawValue(raw, prop) {
1429
+ if (typeof raw !== "string") return raw;
1049
1430
  if (prop.type.kind === "" && prop.type.designType === "string") return raw;
1050
1431
  try {
1051
1432
  return JSON.parse(raw);
@@ -1060,7 +1441,8 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1060
1441
  case "number": return 0;
1061
1442
  case "boolean": return false;
1062
1443
  case "undefined": return;
1063
- case "null": return null;
1444
+ case "null":
1445
+ case "any": return null;
1064
1446
  default: return;
1065
1447
  }
1066
1448
  }
@@ -1158,7 +1540,12 @@ function* buildStructure(def, path, mode, walk) {
1158
1540
  const items = [];
1159
1541
  for (const item of type.items) items.push(yield build(item, path, mode, walk));
1160
1542
  if (items.some(stops)) return STOPPED;
1161
- const values = items.filter((item) => item !== STOPPED);
1543
+ const isAny = (i) => {
1544
+ const t = type.items[i].type;
1545
+ return t.kind === "" && t.designType === "any";
1546
+ };
1547
+ const kept = items.filter((item, i) => item !== STOPPED && !isAny(i));
1548
+ const values = kept.length > 0 ? kept : items.filter((item) => item !== STOPPED);
1162
1549
  return values.length > 0 && values.every(isPlainObject) ? Object.assign({}, ...values) : values[0];
1163
1550
  }
1164
1551
  default: throw new Error(`Unknown type kind "${type.kind}"`);
@@ -1189,12 +1576,13 @@ function isPlainObject(value) {
1189
1576
  /**
1190
1577
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
1191
1578
  * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
1192
- * (`static toJsonSchema()`).
1193
- */ function lazyJsonSchema(type) {
1579
+ * (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
1580
+ * of a type).
1581
+ */ function lazyJsonSchema(type, opts) {
1194
1582
  const known = lazy.get(type);
1195
1583
  const writes = metadataWriteCount();
1196
1584
  if (known?.writes === writes) return known.schema;
1197
- const schema = buildJsonSchema(type);
1585
+ const schema = buildJsonSchema(type, opts);
1198
1586
  lazy.set(type, {
1199
1587
  writes,
1200
1588
  schema
@@ -1206,14 +1594,15 @@ function isPlainObject(value) {
1206
1594
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
1207
1595
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
1208
1596
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
1209
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
1210
- */ function bundledSchemaOf(type, literal, modules = []) {
1597
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
1598
+ * `jsonSchemaOptions` of the build (the literal was built with them).
1599
+ */ function bundledSchemaOf(type, literal, modules = [], opts) {
1211
1600
  const applied = appliedBlockModules();
1212
1601
  const known = bundled.get(type);
1213
1602
  if (known?.size === applied.size) return known.schema;
1214
1603
  const accounted = new Set(modules);
1215
1604
  const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
1216
- const schema = same ? literal() : buildJsonSchema(type);
1605
+ const schema = same ? literal() : buildJsonSchema(type, opts);
1217
1606
  bundled.set(type, {
1218
1607
  size: applied.size,
1219
1608
  schema,
@@ -1356,7 +1745,7 @@ function isPlainObject(value) {
1356
1745
 
1357
1746
  //#endregion
1358
1747
  //#region packages/typescript/src/runtime/serialize.ts
1359
- function _define_property(obj, key, value) {
1748
+ function _define_property$1(obj, key, value) {
1360
1749
  if (key in obj) Object.defineProperty(obj, key, {
1361
1750
  value,
1362
1751
  enumerable: true,
@@ -1428,17 +1817,17 @@ function _define_property(obj, key, value) {
1428
1817
  return id;
1429
1818
  }
1430
1819
  constructor() {
1431
- _define_property(this, "own", /* @__PURE__ */ new Map());
1820
+ _define_property$1(this, "own", /* @__PURE__ */ new Map());
1432
1821
  /**
1433
1822
  * The nodes without an id met more than once (see `indexPayload`): serialized once, with a
1434
1823
  * payload id, and referenced (`$ref`, `anon`) wherever else they are.
1435
- */ _define_property(this, "repeated", /* @__PURE__ */ new Set());
1436
- _define_property(this, "firstKeys", /* @__PURE__ */ new Map());
1437
- _define_property(this, "identities", /* @__PURE__ */ new WeakMap());
1438
- _define_property(this, "nextId", 0);
1439
- /** Payload ids by type def (see {@link keyOf}). */ _define_property(this, "keys", /* @__PURE__ */ new WeakMap());
1440
- /** The payload ids given so far. */ _define_property(this, "taken", /* @__PURE__ */ new Set());
1441
- /** The `cut` payload of defs (see `indexPayload`). */ _define_property(this, "cutKeys", /* @__PURE__ */ new WeakMap());
1824
+ */ _define_property$1(this, "repeated", /* @__PURE__ */ new Set());
1825
+ _define_property$1(this, "firstKeys", /* @__PURE__ */ new Map());
1826
+ _define_property$1(this, "identities", /* @__PURE__ */ new WeakMap());
1827
+ _define_property$1(this, "nextId", 0);
1828
+ /** Payload ids by type def (see {@link keyOf}). */ _define_property$1(this, "keys", /* @__PURE__ */ new WeakMap());
1829
+ /** The payload ids given so far. */ _define_property$1(this, "taken", /* @__PURE__ */ new Set());
1830
+ /** The `cut` payload of defs (see `indexPayload`). */ _define_property$1(this, "cutKeys", /* @__PURE__ */ new WeakMap());
1442
1831
  }
1443
1832
  };
1444
1833
  /**
@@ -1896,4 +2285,233 @@ function* deserializeTypeDef(t, resolved) {
1896
2285
  }
1897
2286
 
1898
2287
  //#endregion
1899
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, LayerMap, SERIALIZE_VERSION, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, mergeJsonSchemas, metaEmpty, pendingStatements, registerCompiledCheck, serializeAnnotatedType, throwFeatureDisabled, watchLayer };
2288
+ //#region packages/typescript/src/runtime/translate-served.ts
2289
+ /**
2290
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
2291
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
2292
+ * collected for the client.
2293
+ */ function _define_property(obj, key, value) {
2294
+ if (key in obj) Object.defineProperty(obj, key, {
2295
+ value,
2296
+ enumerable: true,
2297
+ configurable: true,
2298
+ writable: true
2299
+ });
2300
+ else obj[key] = value;
2301
+ return obj;
2302
+ }
2303
+ /**
2304
+ * Translates the user-facing text of serialized annotated types (the output of
2305
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
2306
+ * found at any depth is read with {@link userTextOf}:
2307
+ *
2308
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
2309
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
2310
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
2311
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
2312
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
2313
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
2314
+ * translates the expressions' results by exact match.
2315
+ *
2316
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
2317
+ * result shares every part with no translated text, and is `json` itself when nothing was
2318
+ * translated.
2319
+ *
2320
+ * @example
2321
+ * ```ts
2322
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
2323
+ * i18n.exists(text) ? i18n.t(text) : undefined
2324
+ * )
2325
+ * ```
2326
+ */ function translateServed(json, t) {
2327
+ const texts = {};
2328
+ return {
2329
+ value: walk(json, void 0, {
2330
+ t,
2331
+ texts
2332
+ }),
2333
+ texts
2334
+ };
2335
+ }
2336
+ /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
2337
+ if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
2338
+ if (typeof value === "string") {
2339
+ if (mode === "expression") collectLiterals(value, ctx);
2340
+ else if (mode === true && formatCodeOf(value) === void 0) return translate(value, ctx) ?? value;
2341
+ return value;
2342
+ }
2343
+ if (typeof value !== "object" || value === null) return value;
2344
+ return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
2345
+ }
2346
+ /**
2347
+ * The mode of the value at `key` of an object of `mode`: a metadata key's user text, a field of a
2348
+ * value object's, else `metadata` objects only (a non-string text value — a `ref` target — has
2349
+ * metadata).
2350
+ */ function modeOf(key, mode) {
2351
+ if (typeof mode === "object") return mode.includes(`${key}()`) ? "expression" : mode.includes(key) || void 0;
2352
+ return mode === "metadata" && userTextOf(key) || (key === "metadata" ? "metadata" : void 0);
2353
+ }
2354
+ /** `t(text)` when it is a string (a plain-object dictionary also has `constructor`, …). */ function translate(text, ctx) {
2355
+ const out = ctx.t(text);
2356
+ return typeof out === "string" ? out : void 0;
2357
+ }
2358
+ /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
2359
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
2360
+ const translated = translate(literal, ctx);
2361
+ if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
2362
+ }
2363
+ }
2364
+ /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
2365
+ "n": "\n",
2366
+ "t": " ",
2367
+ "r": "\r",
2368
+ "b": "\b",
2369
+ "f": "\f",
2370
+ "v": "\v",
2371
+ "0": "\0",
2372
+ "\n": "",
2373
+ "\r": "",
2374
+ "\r\n": ""
2375
+ };
2376
+ /** 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;
2377
+ /** The string a literal's raw text (between its quotes) evaluates to. */ function decode(raw) {
2378
+ return raw.includes("\\") ? raw.replace(ESCAPE, (_, c) => {
2379
+ if (c.length < 3) return Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : c;
2380
+ const code = Number.parseInt(c.replace(/[ux{}]/g, ""), 16);
2381
+ return code > 1114111 ? "" : String.fromCodePoint(code);
2382
+ }) : raw;
2383
+ }
2384
+ /** A character of an identifier or a number. */ const IDENT = RegExp("[\\p{ID_Continue}$]", "u");
2385
+ /** A run of {@link IDENT} characters at `lastIndex`. */ const IDENT_RUN = RegExp("[\\p{ID_Continue}$]+", "uy");
2386
+ /** Keywords whose `(…)` a statement follows: a `/` after the `)` starts a regular expression. */ const CONTROL = new Set([
2387
+ "if",
2388
+ "while",
2389
+ "for",
2390
+ "with"
2391
+ ]);
2392
+ /** Keywords after which `/` starts a regular expression rather than a division. */ const REGEX_AFTER_WORD = new Set([
2393
+ "return",
2394
+ "typeof",
2395
+ "instanceof",
2396
+ "in",
2397
+ "of",
2398
+ "new",
2399
+ "delete",
2400
+ "void",
2401
+ "throw",
2402
+ "case",
2403
+ "do",
2404
+ "else",
2405
+ "yield",
2406
+ "await"
2407
+ ]);
2408
+ let LiteralScanner = class LiteralScanner {
2409
+ /** Scans code up to the end, or to the `}` closing a template's `${`. */ code() {
2410
+ const src = this.src;
2411
+ while (this.i < src.length) {
2412
+ const c = src[this.i];
2413
+ if (c === "/" && src[this.i + 1] === "/") {
2414
+ const end = src.indexOf("\n", this.i);
2415
+ this.i = end === -1 ? src.length : end;
2416
+ } else if (c === "/" && src[this.i + 1] === "*") {
2417
+ const end = src.indexOf("*/", this.i + 2);
2418
+ this.i = end === -1 ? src.length : end + 2;
2419
+ } else if (c === "'" || c === "\"" || c === "`") {
2420
+ const text = this.literal(c);
2421
+ if (text !== void 0 && text.trim() !== "") this.out.add(text);
2422
+ this.regexOk = false;
2423
+ } else if (c === "/" && this.regexOk) {
2424
+ this.regex();
2425
+ this.regexOk = false;
2426
+ } else if (IDENT.test(c)) this.word();
2427
+ else if ((c === "+" || c === "-") && src[this.i + 1] === c) {
2428
+ this.i += 2;
2429
+ this.regexOk = false;
2430
+ } else {
2431
+ this.i++;
2432
+ if (/\s/.test(c)) continue;
2433
+ if (c === "(" || c === "{") this.open.push(c === "(" ? "p" : c);
2434
+ else if (c === ")" || c === "}") {
2435
+ const top = this.open.pop();
2436
+ if (top === "$") return;
2437
+ this.regexOk = top === "c";
2438
+ continue;
2439
+ }
2440
+ this.regexOk = c !== "]";
2441
+ }
2442
+ }
2443
+ }
2444
+ /** An identifier, keyword or number at `i`; `i` past it (and past a control keyword's `(`). */ word() {
2445
+ const src = this.src;
2446
+ IDENT_RUN.lastIndex = this.i;
2447
+ IDENT_RUN.test(src);
2448
+ const word = src.slice(this.i, IDENT_RUN.lastIndex);
2449
+ this.i = IDENT_RUN.lastIndex;
2450
+ this.regexOk = REGEX_AFTER_WORD.has(word);
2451
+ if (CONTROL.has(word)) {
2452
+ while (/\s/.test(src[this.i] ?? "")) this.i++;
2453
+ if (src[this.i] === "(") {
2454
+ this.i++;
2455
+ this.open.push("c");
2456
+ this.regexOk = true;
2457
+ }
2458
+ }
2459
+ }
2460
+ /**
2461
+ * A `'…'` / `"…"` / `` `…` `` literal at `i`, decoded (`undefined`: a template with `${…}`, whose
2462
+ * code is scanned); `i` past it.
2463
+ */ literal(quote) {
2464
+ const src = this.src;
2465
+ const start = ++this.i;
2466
+ let plain = true;
2467
+ while (this.i < src.length && src[this.i] !== quote) if (src[this.i] === "\\") this.i += src.startsWith("\r\n", this.i + 1) ? 3 : 2;
2468
+ else if (quote === "`" && src.startsWith("${", this.i)) {
2469
+ plain = false;
2470
+ this.i += 2;
2471
+ this.open.push("$");
2472
+ this.code();
2473
+ } else this.i++;
2474
+ const end = this.i++;
2475
+ return plain ? decode(src.slice(start, end)) : void 0;
2476
+ }
2477
+ /** A regular expression literal starting at `i`; `i` past its flags. */ regex() {
2478
+ const src = this.src;
2479
+ let inClass = false;
2480
+ this.i++;
2481
+ while (this.i < src.length && src[this.i] !== "\n") {
2482
+ const c = src[this.i++];
2483
+ if (c === "\\") this.i++;
2484
+ else if (c === "[") inClass = true;
2485
+ else if (c === "]") inClass = false;
2486
+ else if (c === "/" && !inClass) break;
2487
+ }
2488
+ while (this.i < src.length && /[a-z]/i.test(src[this.i])) this.i++;
2489
+ }
2490
+ constructor(src, out) {
2491
+ _define_property(this, "src", void 0);
2492
+ _define_property(this, "out", void 0);
2493
+ _define_property(this, "i", void 0);
2494
+ /** A `/` here starts a regular expression (no operand just ended), not a division. */ _define_property(this, "regexOk", void 0);
2495
+ /**
2496
+ * The open brackets: `c` — the `(` of an `if` / `while` / `for` / `with` (a `/` after its `)` is
2497
+ * a regex); `p` — another `(`; `{`; `$` — a template's `${`.
2498
+ */ _define_property(this, "open", void 0);
2499
+ this.src = src;
2500
+ this.out = out;
2501
+ this.i = 0;
2502
+ this.regexOk = true;
2503
+ this.open = [];
2504
+ }
2505
+ };
2506
+ /**
2507
+ * The string literals of JavaScript `source`, as the strings they evaluate to: `'…'`, `"…"` and
2508
+ * `` `…` `` templates without `${…}` (the literals inside a `${…}` count). Comments and regular
2509
+ * expression literals are skipped; empty and blank literals are left out.
2510
+ */ function stringLiterals(source) {
2511
+ const out = /* @__PURE__ */ new Set();
2512
+ new LiteralScanner(source, out).code();
2513
+ return [...out];
2514
+ }
2515
+
2516
+ //#endregion
2517
+ 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 };