@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.cjs CHANGED
@@ -1,11 +1,92 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_unique_name = require('./unique-name-xWd9uO-k.cjs');
2
+ const require_user_text = require('./user-text-Dl8FNKLL.cjs');
3
3
 
4
- //#region packages/typescript/src/runtime/coerce.ts
4
+ //#region packages/typescript/src/runtime/copy-on-change.ts
5
+ /**
6
+ * Internal sentinel: the value cannot be taken by a type node (drives union branch selection in
7
+ * `coerce.ts` and `normalize.ts`). A {@link mapProps} step returns it to reject the whole object.
8
+ */ const NO_MATCH = Symbol("atscript.no-match");
9
+ /**
10
+ * Maps the props of plain object `value` with `step` (props without a def — declared or pattern —
11
+ * are kept as they are). Copy-on-first-change: allocates the output only when some prop changed,
12
+ * else returns `value`; an own `__proto__` key stays an own key (never the output's prototype).
13
+ * NO_MATCH when a step returns it.
14
+ */ function mapProps(type, value, step, ctx) {
15
+ const keys = Object.keys(value);
16
+ let out;
17
+ for (let i = 0; i < keys.length; i++) {
18
+ const key = keys[i];
19
+ const input = value[key];
20
+ let def = type.props.get(key);
21
+ if (!def) {
22
+ for (const { pattern, def: patternDef } of type.propsPatterns) if (pattern.test(key)) {
23
+ def = patternDef;
24
+ break;
25
+ }
26
+ }
27
+ const mapped = def ? step(def, input, ctx) : input;
28
+ if (mapped === NO_MATCH) return NO_MATCH;
29
+ if (out) setOwn(out, key, mapped);
30
+ else if (mapped !== input) {
31
+ out = {};
32
+ for (let j = 0; j < i; j++) setOwn(out, keys[j], value[keys[j]]);
33
+ setOwn(out, key, mapped);
34
+ }
35
+ }
36
+ return out ?? value;
37
+ }
38
+ /**
39
+ * Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
40
+ * items). Copy-on-first-change, as {@link mapProps}.
41
+ */ function mapItems(value, of, step, ctx) {
42
+ return mapList(value, (input, i) => step(Array.isArray(of) ? of[i] : of, input, ctx));
43
+ }
44
+ /** Maps the items of `list` with `step`. Copy-on-first-change: `list` itself when none changed. */ function mapList(list, step) {
45
+ let out;
46
+ for (let i = 0; i < list.length; i++) {
47
+ const mapped = step(list[i], i);
48
+ if (out) out.push(mapped);
49
+ else if (mapped !== list[i]) {
50
+ out = list.slice(0, i);
51
+ out.push(mapped);
52
+ }
53
+ }
54
+ return out ?? list;
55
+ }
56
+ /**
57
+ * Maps the own values of JSON object `obj` with `step`. Copy-on-first-change: `obj` itself when
58
+ * none changed; an own `__proto__` key stays an own key.
59
+ */ function mapEntries(obj, step) {
60
+ let out;
61
+ for (const key of Object.keys(obj)) {
62
+ const mapped = step(key, obj[key]);
63
+ if (mapped !== obj[key]) {
64
+ out ?? (out = { ...obj });
65
+ setOwn(out, key, mapped);
66
+ }
67
+ }
68
+ return out ?? obj;
69
+ }
70
+ /** Whether `value` is a plain object (`{}` or prototype-less): class instances are not. */ function isPlainObject$1(value) {
71
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
72
+ const proto = Object.getPrototypeOf(value);
73
+ return proto === Object.prototype || proto === null;
74
+ }
5
75
  /**
6
- * Internal sentinel returned when a value cannot be coerced to a type node.
7
- * Drives union branch selection without allocating per-node result objects.
8
- */ const NO_MATCH = Symbol("atscript.coerce.no-match");
76
+ * Sets own property `key` of `out`: `__proto__` as an own data property (an assignment would set
77
+ * the object's prototype instead — input parsed from JSON may carry such a key).
78
+ */ function setOwn(out, key, value) {
79
+ if (key === "__proto__") Object.defineProperty(out, key, {
80
+ value,
81
+ writable: true,
82
+ enumerable: true,
83
+ configurable: true
84
+ });
85
+ else out[key] = value;
86
+ }
87
+
88
+ //#endregion
89
+ //#region packages/typescript/src/runtime/coerce.ts
9
90
  /**
10
91
  * Coerces string-transport input (route params, query strings) toward the
11
92
  * scalar shapes an annotated type expects.
@@ -55,11 +136,11 @@ const require_unique_name = require('./unique-name-xWd9uO-k.cjs');
55
136
  }
56
137
  case "object":
57
138
  if (!isPlainObject$1(value)) return NO_MATCH;
58
- return coerceProps(def, value);
59
- case "array": return Array.isArray(value) ? coerceItems(value, type.of) : NO_MATCH;
139
+ return mapProps(type, value, coerceChild, void 0);
140
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
60
141
  case "tuple": {
61
142
  const items = type.items;
62
- return Array.isArray(value) && value.length === items.length ? coerceItems(value, void 0, items) : NO_MATCH;
143
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
63
144
  }
64
145
  case "union":
65
146
  for (const item of type.items) {
@@ -104,57 +185,289 @@ function scalar(designType, value) {
104
185
  default: return NO_MATCH;
105
186
  }
106
187
  }
188
+ /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
189
+ const result = coerce(def, input);
190
+ return result === NO_MATCH ? input : result;
191
+ }
192
+
193
+ //#endregion
194
+ //#region packages/typescript/src/runtime/normalize.ts
195
+ const TRIM = 1;
196
+ const LOWERCASE = 2;
197
+ const UPPERCASE = 4;
107
198
  /**
108
- * Coerces the props of a plain object. Copy-on-first-change: allocates the
109
- * output object only when some prop actually coerced, else returns the input.
110
- */ function coerceProps(def, value) {
111
- const keys = Object.keys(value);
112
- let out;
113
- for (let i = 0; i < keys.length; i++) {
114
- const key = keys[i];
115
- const input = value[key];
116
- let propDef = def.type.props.get(key);
117
- if (!propDef) {
118
- for (const { pattern, def: patternDef } of def.type.propsPatterns) if (pattern.test(key)) {
119
- propDef = patternDef;
120
- break;
199
+ * Whether each node's subtree has normalizers: valid until the next metadata write or
200
+ * `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
201
+ */ let reach = /* @__PURE__ */ new WeakMap();
202
+ let stampWrites = -1;
203
+ let stampEpoch = -1;
204
+ /**
205
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
206
+ * `@normalize.lowercase` and `@normalize.uppercase`.
207
+ *
208
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
209
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
210
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
211
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
212
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
213
+ * uppercase. Other values (including class instances such as `Date`) and strings without
214
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
215
+ *
216
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
217
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
218
+ * value is left as it is. A union normalizes a value only when the result does not depend on
219
+ * which branch takes it:
220
+ * - an object union with a discriminator (a literal prop every object branch requires, see
221
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
222
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
223
+ * only when the normalized string equals its literal): when they all give the same result it
224
+ * is used; when they differ, the branches whose result their own validator accepts (default
225
+ * options) are kept, and the result is used when they agree; else the value is returned
226
+ * untouched (ambiguous).
227
+ *
228
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * // @normalize.trim @normalize.lowercase email: string.email
233
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
234
+ * ```
235
+ */ function normalizeForType(def, value) {
236
+ const writes = require_user_text.metadataWriteCount();
237
+ const epoch = require_user_text.currentEpoch();
238
+ if (writes !== stampWrites || epoch !== stampEpoch) {
239
+ stampWrites = writes;
240
+ stampEpoch = epoch;
241
+ reach = /* @__PURE__ */ new WeakMap();
242
+ }
243
+ if (!hasNormalizers(def)) return value;
244
+ const result = normalize(def, value, 0, /* @__PURE__ */ new Map());
245
+ return result === NO_MATCH ? value : result;
246
+ }
247
+ /** The nodes `def`'s value walk can enter (props, pattern props, items, elements). */ function childrenOf(def) {
248
+ const type = def.type;
249
+ switch (type.kind) {
250
+ case "object": {
251
+ const t = type;
252
+ const out = [...t.props.values()];
253
+ for (const p of t.propsPatterns) out.push(p.def);
254
+ return out;
255
+ }
256
+ case "array": return [type.of];
257
+ case "union":
258
+ case "intersection":
259
+ case "tuple": return type.items;
260
+ default: return [];
261
+ }
262
+ }
263
+ /**
264
+ * Whether `def` or a node its walk reaches has normalizers. Answers (and caches) every node
265
+ * reached, recursive types included: collects the reached nodes with their parents, then marks
266
+ * the nodes with normalizers and, back along the parents, every node that reaches one.
267
+ */ function hasNormalizers(def) {
268
+ const known = reach.get(def);
269
+ if (known !== void 0) return known;
270
+ const parents = new Map([[def, []]]);
271
+ const marked = [];
272
+ const todo = [def];
273
+ while (todo.length > 0) {
274
+ const node = todo.pop();
275
+ if (flagsOf(node, 0) !== 0) marked.push(node);
276
+ for (const child of childrenOf(node)) {
277
+ const cached = reach.get(child);
278
+ if (cached !== void 0) {
279
+ if (cached) marked.push(node);
280
+ continue;
121
281
  }
282
+ let of = parents.get(child);
283
+ if (!of) {
284
+ parents.set(child, of = []);
285
+ todo.push(child);
286
+ }
287
+ of.push(node);
122
288
  }
123
- let coerced = input;
124
- if (propDef) {
125
- const result = coerce(propDef, input);
126
- if (result !== NO_MATCH) coerced = result;
289
+ }
290
+ for (const node of parents.keys()) reach.set(node, false);
291
+ while (marked.length > 0) {
292
+ const node = marked.pop();
293
+ if (!reach.get(node)) {
294
+ reach.set(node, true);
295
+ marked.push(...parents.get(node));
127
296
  }
128
- if (out) out[key] = coerced;
129
- else if (coerced !== input) {
130
- out = {};
131
- for (let j = 0; j < i; j++) out[keys[j]] = value[keys[j]];
132
- out[key] = coerced;
297
+ }
298
+ return reach.get(def);
299
+ }
300
+ /** The normalizer flags of `def`, on top of `inherited` (a union's, for its branches). */ function flagsOf(def, inherited) {
301
+ const meta = def.metadata;
302
+ if (require_user_text.metaEmpty(meta)) return inherited;
303
+ let flags = inherited;
304
+ if (meta.get("normalize.trim")) flags |= TRIM;
305
+ if (meta.get("normalize.lowercase")) flags |= LOWERCASE;
306
+ if (meta.get("normalize.uppercase")) flags |= UPPERCASE;
307
+ return flags;
308
+ }
309
+ function applyFlags(value, flags) {
310
+ let out = value;
311
+ if (flags & TRIM) out = out.trim();
312
+ if (flags & LOWERCASE) out = out.toLowerCase();
313
+ if (flags & UPPERCASE) out = out.toUpperCase();
314
+ return out;
315
+ }
316
+ /**
317
+ * The normalized value, or NO_MATCH when `def` cannot take it (its kind does not fit the value).
318
+ * `inherited`: the normalizer flags of the unions / intersections `def` is a member of.
319
+ *
320
+ * Objects and unions are memoized per call by input object: a recursive union without a
321
+ * discriminator is tried for every branch at every level, which without it is exponential in
322
+ * the depth of the value.
323
+ */ function normalize(def, value, inherited, memo) {
324
+ if (value === void 0 || value === null) return value;
325
+ if (inherited === 0 && !hasNormalizers(def)) return takes(def, value) ? value : NO_MATCH;
326
+ const type = def.type;
327
+ switch (type.kind) {
328
+ case "": {
329
+ const out = typeof value === "string" && type.designType === "string" ? applyFlags(value, flagsOf(def, inherited)) : value;
330
+ return takes(def, out) ? out : NO_MATCH;
331
+ }
332
+ case "object": {
333
+ if (!isPlainObject$1(value)) return NO_MATCH;
334
+ const entries = entriesOf(memo, value);
335
+ return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, memo));
336
+ }
337
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, memo) : NO_MATCH;
338
+ case "tuple": {
339
+ const items = type.items;
340
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, memo) : NO_MATCH;
341
+ }
342
+ case "union": {
343
+ const flags = flagsOf(def, inherited);
344
+ const items = type.items;
345
+ if (typeof value !== "object") return normalizeUnion(items, value, flags, memo);
346
+ const entries = entriesOf(memo, value);
347
+ return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, memo));
348
+ }
349
+ case "intersection": {
350
+ const flags = flagsOf(def, inherited);
351
+ let current = value;
352
+ for (const item of type.items) {
353
+ const result = normalize(item, current, flags, memo);
354
+ if (result === NO_MATCH) return NO_MATCH;
355
+ current = result;
356
+ }
357
+ return current;
133
358
  }
359
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
134
360
  }
135
- return out ?? value;
361
+ }
362
+ /** The memoized results for input object `value` (see {@link normalize}). */ function entriesOf(memo, value) {
363
+ let entries = memo.get(value);
364
+ if (!entries) {
365
+ entries = [];
366
+ memo.set(value, entries);
367
+ }
368
+ return entries;
369
+ }
370
+ /** The memoized result for `type` and `flags`, `undefined` when none. */ function recall(entries, type, flags) {
371
+ for (const [t, f, result] of entries) if (t === type && f === flags) return result;
372
+ }
373
+ /** Memoizes `result` for `type` and `flags` and returns it. */ function remember(entries, type, flags, result) {
374
+ entries.push([
375
+ type,
376
+ flags,
377
+ result
378
+ ]);
379
+ return result;
380
+ }
381
+ /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, memo) {
382
+ if (!hasNormalizers(def)) return input;
383
+ const result = normalize(def, input, 0, memo);
384
+ return result === NO_MATCH ? input : result;
136
385
  }
137
386
  /**
138
- * Coerces array/tuple items against `of` (arrays) or `items[i]` (tuples).
139
- * Copy-on-first-change, same as {@link coerceProps}.
140
- */ function coerceItems(value, of, items) {
141
- let out;
142
- for (let i = 0; i < value.length; i++) {
143
- const input = value[i];
144
- const result = coerce(of ?? items[i], input);
145
- const coerced = result === NO_MATCH ? input : result;
146
- if (out) out.push(coerced);
147
- else if (coerced !== input) {
148
- out = value.slice(0, i);
149
- out.push(coerced);
387
+ * A prop: as {@link normalizeItem}, but NO_MATCH (the object is not this type) when a literal prop
388
+ * (`kind: 'cat'`) holds another value.
389
+ */ function normalizeProp(def, input, memo) {
390
+ const out = normalizeItem(def, input, memo);
391
+ if (out === input && def.type.kind === "" && def.type.value !== void 0 && input !== def.type.value && input !== void 0 && input !== null) return NO_MATCH;
392
+ return out;
393
+ }
394
+ /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes(def, value) {
395
+ const type = def.type;
396
+ switch (type.kind) {
397
+ case "": {
398
+ const final = type;
399
+ switch (final.designType) {
400
+ case "string":
401
+ case "number":
402
+ case "boolean": return typeof value === final.designType && (final.value === void 0 || value === final.value);
403
+ case "decimal": return typeof value === "string";
404
+ case "object": return typeof value === "object";
405
+ case "any":
406
+ case "phantom": return true;
407
+ default: return false;
408
+ }
150
409
  }
410
+ case "object": return isPlainObject$1(value);
411
+ case "array": return Array.isArray(value);
412
+ case "tuple": return Array.isArray(value) && value.length === type.items.length;
413
+ case "union": return type.items.some((item) => takes(item, value));
414
+ case "intersection": return type.items.every((item) => takes(item, value));
415
+ default: return false;
151
416
  }
152
- return out ?? value;
153
417
  }
154
- function isPlainObject$1(value) {
155
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
156
- const proto = Object.getPrototypeOf(value);
157
- return proto === Object.prototype || proto === null;
418
+ /**
419
+ * A union: the branch a discriminator names, else the one result every branch that can take
420
+ * the value agrees on — or, when they differ, the one result of the branches whose validator
421
+ * accepts their result (NO_MATCH when none can take the value or it stays ambiguous).
422
+ */ function normalizeUnion(items, value, flags, memo) {
423
+ if (isPlainObject$1(value)) {
424
+ const disc = require_user_text.unionDiscriminator(items);
425
+ if (disc) {
426
+ const tag = value[disc.property];
427
+ for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, memo);
428
+ }
429
+ }
430
+ let first = NO_MATCH;
431
+ let firstItem;
432
+ let rest;
433
+ for (const item of items) {
434
+ const out = normalize(item, value, flags, memo);
435
+ if (out === NO_MATCH) continue;
436
+ if (first === NO_MATCH) {
437
+ first = out;
438
+ firstItem = item;
439
+ } else (rest ?? (rest = [])).push([item, out]);
440
+ }
441
+ if (!rest || rest.every(([, out]) => sameValue(out, first))) return first;
442
+ rest.unshift([firstItem, first]);
443
+ let accepted = NO_MATCH;
444
+ for (const [item, out] of rest) {
445
+ if (!branchValidator(item).validate(out, true)) continue;
446
+ if (accepted === NO_MATCH) accepted = out;
447
+ else if (!sameValue(accepted, out)) return NO_MATCH;
448
+ }
449
+ return accepted;
450
+ }
451
+ /**
452
+ * Each union branch's validator (default options; one error is enough to reject a result),
453
+ * judging its own normalized result.
454
+ */ const branchValidators = /* @__PURE__ */ new WeakMap();
455
+ function branchValidator(def) {
456
+ let validator = branchValidators.get(def);
457
+ if (!validator) {
458
+ validator = new require_user_text.Validator(def, { errorLimit: 1 });
459
+ branchValidators.set(def, validator);
460
+ }
461
+ return validator;
462
+ }
463
+ /** Whether two results of the same input are equal (shared, untouched parts are identical). */ function sameValue(a, b) {
464
+ if (a === b) return true;
465
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
466
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
467
+ const keys = Object.keys(a);
468
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
469
+ }
470
+ return false;
158
471
  }
159
472
 
160
473
  //#endregion
@@ -206,48 +519,7 @@ function isPlainObject$1(value) {
206
519
 
207
520
  //#endregion
208
521
  //#region packages/typescript/src/runtime/json-schema.ts
209
- /**
210
- * Detects a discriminator property across union items.
211
- *
212
- * Scans all items for object-typed members that share a common property
213
- * with distinct const/literal values. If exactly one such property exists,
214
- * it is returned as the discriminator. Returns `null` when no qualifying
215
- * property exists, or when more than one does (ambiguous).
216
- */ function detectDiscriminator(items) {
217
- if (items.length < 2) return null;
218
- for (const item of items) if (item.type.kind !== "object") return null;
219
- const firstObj = items[0].type;
220
- const candidates = [];
221
- for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
222
- let result = null;
223
- for (const candidate of candidates) {
224
- const values = /* @__PURE__ */ new Set();
225
- const indexMapping = {};
226
- let valid = true;
227
- for (let i = 0; i < items.length; i++) {
228
- const prop = items[i].type.props.get(candidate);
229
- if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
230
- valid = false;
231
- break;
232
- }
233
- const val = prop.type.value;
234
- if (values.has(val)) {
235
- valid = false;
236
- break;
237
- }
238
- values.add(val);
239
- indexMapping[String(val)] = i;
240
- }
241
- if (valid) {
242
- if (result) return null;
243
- result = {
244
- propertyName: candidate,
245
- indexMapping
246
- };
247
- }
248
- }
249
- return result;
250
- }
522
+ /** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
251
523
  /**
252
524
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
253
525
  *
@@ -263,8 +535,12 @@ function isPlainObject$1(value) {
263
535
  * ```
264
536
  *
265
537
  * @param type - The annotated type to convert.
538
+ * @param opts - {@link TJsonSchemaOptions}.
266
539
  * @returns A JSON Schema object.
267
- */ function buildJsonSchema(type) {
540
+ */ function buildJsonSchema(type, opts) {
541
+ const closed = opts?.closed === true;
542
+ const annotations = opts?.annotations !== false;
543
+ const enums = opts?.enums !== false;
268
544
  /**
269
545
  * `$defs` entries by type def (identity): named objects (always extracted) and types found
270
546
  * recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
@@ -292,8 +568,35 @@ function isPlainObject$1(value) {
292
568
  ...schema,
293
569
  type: [schema.type, "null"]
294
570
  };
295
- if (Object.keys(schema).length === 1 && Array.isArray(schema.anyOf)) return { anyOf: [...schema.anyOf, { type: "null" }] };
296
- return { anyOf: [schema, { type: "null" }] };
571
+ const notes = {};
572
+ let body = schema;
573
+ for (const [, keyword] of ANNOTATION_KEYWORDS) if (body[keyword] !== void 0) {
574
+ if (body === schema) body = { ...schema };
575
+ notes[keyword] = body[keyword];
576
+ delete body[keyword];
577
+ }
578
+ if (body !== schema && Object.keys(body).length === 1 && body.allOf?.length === 1) body = body.allOf[0];
579
+ if (Object.keys(body).length === 1 && Array.isArray(body.anyOf)) return {
580
+ anyOf: [...body.anyOf, { type: "null" }],
581
+ ...notes
582
+ };
583
+ return {
584
+ anyOf: [body, { type: "null" }],
585
+ ...notes
586
+ };
587
+ };
588
+ /**
589
+ * A use of a `$defs` entry: `schema` (its `$ref`) with what the use adds to the entry (built
590
+ * from `own`, see `ownDef`): its key counts, and its title / description when they differ
591
+ * from the entry's — beside the reference, in an `allOf`.
592
+ */ const useOf = (schema, def, own, keyCounts = false) => {
593
+ const extra = {};
594
+ if (annotations) applyAnnotationKeywords(extra, def.metadata, own?.metadata);
595
+ if (keyCounts) applyKeyCounts(extra, def.metadata);
596
+ return Object.keys(extra).length > 0 ? {
597
+ allOf: [schema],
598
+ ...extra
599
+ } : schema;
297
600
  };
298
601
  /**
299
602
  * Non-primitive type defs being built: `true` once re-entered (recursive). A named object
@@ -330,7 +633,7 @@ function isPlainObject$1(value) {
330
633
  * A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
331
634
  * them instead, its recursion referring to the shared definition.
332
635
  */ function* refTo(typeDef, def, own) {
333
- if (def === own || inlining.has(def) || sameConstraints(def, own)) return ref(typeDef);
636
+ if (def === own || inlining.has(def) || sameConstraints(def, own)) return useOf(ref(typeDef), def, own);
334
637
  inlining.add(def);
335
638
  const schema = yield buildDef(def);
336
639
  inlining.delete(def);
@@ -340,7 +643,7 @@ function isPlainObject$1(value) {
340
643
  const properties = {};
341
644
  const required = [];
342
645
  for (const [key, val] of d.type.props.entries()) {
343
- if (require_unique_name.isPhantomType(val)) continue;
646
+ if (require_user_text.isPhantomType(val)) continue;
344
647
  if (val.optional) {
345
648
  const schema = yield build(val);
346
649
  properties[key] = val.metadata.get("meta.required") ? schema : nullable(schema);
@@ -360,6 +663,7 @@ function isPlainObject$1(value) {
360
663
  for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
361
664
  schema.patternProperties = patternProperties(built, Object.keys(properties));
362
665
  }
666
+ if (closed) schema.additionalProperties = false;
363
667
  return schema;
364
668
  }
365
669
  /** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
@@ -369,14 +673,17 @@ function isPlainObject$1(value) {
369
673
  const atRoot = def === type && !rootEntered;
370
674
  rootEntered = true;
371
675
  if (def.id && typeDef.kind === "object" && !atRoot) {
676
+ const own = annotations ? ownDef(def, type) ?? def : void 0;
372
677
  if (!defs.has(typeDef)) {
373
678
  reserve(typeDef, def.id, true);
374
679
  const outer = building;
375
680
  building = /* @__PURE__ */ new Map();
376
- defs.get(typeDef).schema = yield buildObject(def);
681
+ const entry = yield buildObject(def);
682
+ if (own) applyAnnotationKeywords(entry, own.metadata);
683
+ defs.get(typeDef).schema = entry;
377
684
  building = outer;
378
685
  }
379
- return ref(typeDef);
686
+ return useOf(ref(typeDef), def, own, true);
380
687
  }
381
688
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
382
689
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -405,7 +712,7 @@ function isPlainObject$1(value) {
405
712
  const own = ownOf(def);
406
713
  const same = def === own || sameConstraints(def, own);
407
714
  defs.get(typeDef).schema = same ? schema : yield buildDef(own);
408
- return def === type || !same ? schema : ref(typeDef);
715
+ return def === type || !same ? schema : useOf(ref(typeDef), def, own);
409
716
  }
410
717
  /** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
411
718
  const ownOf = (def) => {
@@ -416,7 +723,12 @@ function isPlainObject$1(value) {
416
723
  }
417
724
  return own;
418
725
  };
419
- /** The schema of `def`'s own type (see {@link build}). */ function* buildDef(def) {
726
+ /** The schema of `def`'s own type (see {@link build}), with its title / description. */ function* buildDef(def) {
727
+ const schema = yield buildBody(def);
728
+ if (annotations) applyAnnotationKeywords(schema, def.metadata);
729
+ return schema;
730
+ }
731
+ /** The schema of `def`'s own type, without its title / description (see {@link buildDef}). */ function* buildBody(def) {
420
732
  const meta = def.metadata;
421
733
  const all = function* (items) {
422
734
  const out = [];
@@ -424,7 +736,11 @@ function isPlainObject$1(value) {
424
736
  return out;
425
737
  };
426
738
  const kind = def.type.kind;
427
- if (kind === "object") return yield buildObject(def);
739
+ if (kind === "object") {
740
+ const schema = yield buildObject(def);
741
+ applyKeyCounts(schema, meta);
742
+ return schema;
743
+ }
428
744
  if (kind === "array") {
429
745
  const d = def;
430
746
  const schema = {
@@ -445,7 +761,8 @@ function isPlainObject$1(value) {
445
761
  minItems: items.length,
446
762
  maxItems: items.length
447
763
  };
448
- const disc = detectDiscriminator(items);
764
+ const disc = require_user_text.detectDiscriminator(items);
765
+ let schema;
449
766
  if (disc) {
450
767
  const mapping = {};
451
768
  for (const [val, idx] of Object.entries(disc.indexMapping)) {
@@ -457,16 +774,19 @@ function isPlainObject$1(value) {
457
774
  ]);
458
775
  else mapping[val] = `#/oneOf/${idx}`;
459
776
  }
460
- return {
777
+ schema = {
461
778
  oneOf: built,
462
779
  discriminator: {
463
780
  propertyName: disc.propertyName,
464
781
  mapping
465
782
  }
466
783
  };
784
+ } else {
785
+ if (!require_user_text.metaEmpty(meta)) applyUnionConstraints(built, meta, items);
786
+ schema = enums && enumOf(built, refSchemas) || { anyOf: built };
467
787
  }
468
- if (!require_unique_name.metaEmpty(meta)) applyUnionConstraints(built, meta, items);
469
- return { anyOf: built };
788
+ applyKeyCounts(schema, meta);
789
+ return schema;
470
790
  }
471
791
  return forAnnotatedType(def, {
472
792
  phantom() {
@@ -480,7 +800,7 @@ function isPlainObject$1(value) {
480
800
  const dt = d.type.designType;
481
801
  schema.type = dt === "undefined" ? "null" : dt === "decimal" ? "string" : dt;
482
802
  }
483
- if (d.type.designType === "decimal" && d.type.value === void 0) schema.pattern = require_unique_name.DECIMAL_RE.source;
803
+ if (d.type.designType === "decimal" && d.type.value === void 0) schema.pattern = require_user_text.DECIMAL_RE.source;
484
804
  applyScalarConstraints(schema, meta);
485
805
  return schema;
486
806
  },
@@ -573,7 +893,7 @@ function isPlainObject$1(value) {
573
893
  const taken = /* @__PURE__ */ new Set();
574
894
  const names = /* @__PURE__ */ new Map();
575
895
  for (const [typeDef, { base }] of defs) {
576
- const name = require_unique_name.uniqueName(base, (n) => taken.has(n) || n !== base && asked.has(n), "_");
896
+ const name = require_user_text.uniqueName(base, (n) => taken.has(n) || n !== base && asked.has(n), "_");
577
897
  taken.add(name);
578
898
  names.set(typeDef, name);
579
899
  }
@@ -590,8 +910,8 @@ function isPlainObject$1(value) {
590
910
  for (const seen = /* @__PURE__ */ new Set(); own !== root && own.ref && !seen.has(own);) {
591
911
  seen.add(own);
592
912
  const ref = own.ref.type();
593
- const target = require_unique_name.isAnnotatedType(ref) ? require_unique_name.propAtChain(ref, own.ref.field ? own.ref.field.split(".") : []) : void 0;
594
- if (!require_unique_name.isAnnotatedType(target) || target.type !== def.type) break;
913
+ const target = require_user_text.isAnnotatedType(ref) ? require_user_text.propAtChain(ref, own.ref.field ? own.ref.field.split(".") : []) : void 0;
914
+ if (!require_user_text.isAnnotatedType(target) || target.type !== def.type) break;
595
915
  own = target;
596
916
  }
597
917
  return own === def && !def.ref ? void 0 : own;
@@ -674,7 +994,7 @@ function withoutUniqueItems(meta) {
674
994
  const exclude = declared.length > 0 ? `^(?!(?:${declared.map((n) => n.replaceAll(/[\\^$.*+?()[\]{}|/]/g, "\\$&")).join("|")})$)[\\s\\S]*?` : "";
675
995
  const out = {};
676
996
  for (const [regex, schema] of patterns) {
677
- const pattern = require_unique_name.jsonSchemaPattern(regex.source, regex.flags);
997
+ const pattern = require_user_text.jsonSchemaPattern(regex.source, regex.flags);
678
998
  const key = exclude ? `${exclude}(?:${pattern})` : pattern;
679
999
  const taken = out[key];
680
1000
  out[key] = taken ? { anyOf: [...Object.keys(taken).length === 1 && taken.anyOf ? taken.anyOf : [taken], schema] } : schema;
@@ -690,7 +1010,7 @@ function withoutUniqueItems(meta) {
690
1010
  return Array.isArray(schema.anyOf) && schema.anyOf.some((s) => acceptsNull(s, refs));
691
1011
  }
692
1012
  /** `a` and `b` carry the same schema constraints. */ function sameConstraints(a, b) {
693
- return a.metadata === b.metadata || require_unique_name.VALIDATOR_KEYS.every((key) => {
1013
+ return a.metadata === b.metadata || require_user_text.VALIDATOR_KEYS.every((key) => {
694
1014
  const x = a.metadata.get(key);
695
1015
  const y = b.metadata.get(key);
696
1016
  return x === y || JSON.stringify(x) === JSON.stringify(y);
@@ -701,21 +1021,66 @@ function withoutUniqueItems(meta) {
701
1021
  * `@expect.array.uniqueItems` → `uniqueItems` unless the items are objects with
702
1022
  * `@expect.array.key` props (unique by those props: JSON Schema compares whole items).
703
1023
  */ function applyArrayConstraints(schema, meta, of) {
704
- if (meta.get("expect.array.uniqueItems") && require_unique_name.arrayKeyProps(of).length === 0) schema.uniqueItems = true;
1024
+ if (meta.get("expect.array.uniqueItems") && require_user_text.arrayKeyProps(of).length === 0) schema.uniqueItems = true;
705
1025
  const minLength = meta.get("expect.minLength");
706
- if (minLength !== void 0) schema.minItems = require_unique_name.boundOf(minLength, "length");
1026
+ if (minLength !== void 0) schema.minItems = require_user_text.boundOf(minLength, "length");
707
1027
  const maxLength = meta.get("expect.maxLength");
708
- if (maxLength !== void 0) schema.maxItems = require_unique_name.boundOf(maxLength, "length");
1028
+ if (maxLength !== void 0) schema.maxItems = require_user_text.boundOf(maxLength, "length");
1029
+ }
1030
+ /**
1031
+ * `@expect.minKeys` / `maxKeys` → `minProperties` / `maxProperties` (they constrain objects
1032
+ * only, so they also sit on a union's schema as they are).
1033
+ */ function applyKeyCounts(schema, meta) {
1034
+ const minKeys = meta.get("expect.minKeys");
1035
+ if (minKeys !== void 0) schema.minProperties = require_user_text.boundOf(minKeys, "count");
1036
+ const maxKeys = meta.get("expect.maxKeys");
1037
+ if (maxKeys !== void 0) schema.maxProperties = require_user_text.boundOf(maxKeys, "count");
1038
+ }
1039
+ /** `@meta.label` → `title`, `@meta.description` → `description` (see `annotations`). */ function applyAnnotationKeywords(schema, meta, except) {
1040
+ if (require_user_text.metaEmpty(meta)) return;
1041
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) {
1042
+ const value = meta.get(key);
1043
+ if (value !== void 0 && value !== except?.get(key)) schema[keyword] = value;
1044
+ }
1045
+ }
1046
+ /**
1047
+ * The `{ type, enum }` schema of a union whose members are all literals (`const`, a nested
1048
+ * union of literals' `enum`, or `null`), at least one of them not `null`; `undefined` for any
1049
+ * other union (a member with other keywords — a title, a constraint — keeps the `anyOf`).
1050
+ */ function enumOf(members, refs) {
1051
+ const values = [];
1052
+ const types = [];
1053
+ let literal = false;
1054
+ for (const member of members) {
1055
+ if (refs.has(member)) return;
1056
+ const keys = Object.keys(member);
1057
+ let memberValues;
1058
+ if ("const" in member && keys.every((k) => k === "const" || k === "type")) {
1059
+ memberValues = [member.const];
1060
+ literal = true;
1061
+ } else if (Array.isArray(member.enum) && keys.every((k) => k === "enum" || k === "type")) {
1062
+ memberValues = member.enum;
1063
+ literal = true;
1064
+ } else if (member.type === "null" && keys.length === 1) memberValues = [null];
1065
+ else return;
1066
+ for (const value of memberValues) if (!values.includes(value)) values.push(value);
1067
+ for (const t of [member.type ?? []].flat()) if (!types.includes(t)) types.push(t);
1068
+ }
1069
+ if (!literal) return;
1070
+ const schema = {};
1071
+ if (types.length > 0) schema.type = types.length === 1 ? types[0] : types;
1072
+ schema.enum = values;
1073
+ return schema;
709
1074
  }
710
1075
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
711
1076
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
712
1077
  if (schema.type === "string") {
713
1078
  if (meta.get("meta.required")) schema.minLength = 1;
714
1079
  const minLength = meta.get("expect.minLength");
715
- if (minLength !== void 0) schema.minLength = require_unique_name.boundOf(minLength, "length");
1080
+ if (minLength !== void 0) schema.minLength = require_user_text.boundOf(minLength, "length");
716
1081
  const maxLength = meta.get("expect.maxLength");
717
- if (maxLength !== void 0) schema.maxLength = require_unique_name.boundOf(maxLength, "length");
718
- const patterns = (meta.get("expect.pattern") ?? []).map((p) => require_unique_name.jsonSchemaPattern(p.pattern, p.flags));
1082
+ if (maxLength !== void 0) schema.maxLength = require_user_text.boundOf(maxLength, "length");
1083
+ const patterns = (meta.get("expect.pattern") ?? []).map((p) => require_user_text.jsonSchemaPattern(p.pattern, p.flags));
719
1084
  if (meta.get("meta.required")) patterns.push("\\S");
720
1085
  if (schema.pattern !== void 0) {
721
1086
  patterns.unshift(schema.pattern);
@@ -727,13 +1092,13 @@ function withoutUniqueItems(meta) {
727
1092
  if (schema.type === "boolean" && meta.get("meta.required")) schema.const = true;
728
1093
  if (schema.type === "number" || schema.type === "integer") {
729
1094
  const min = meta.get("expect.min");
730
- if (min !== void 0) schema.minimum = require_unique_name.boundOf(min, "minValue");
1095
+ if (min !== void 0) schema.minimum = require_user_text.boundOf(min, "minValue");
731
1096
  const max = meta.get("expect.max");
732
- if (max !== void 0) schema.maximum = require_unique_name.boundOf(max, "maxValue");
1097
+ if (max !== void 0) schema.maximum = require_user_text.boundOf(max, "maxValue");
733
1098
  const exMin = meta.get("expect.exclusiveMin");
734
- if (exMin !== void 0) schema.exclusiveMinimum = require_unique_name.boundOf(exMin, "exclusiveMinValue");
1099
+ if (exMin !== void 0) schema.exclusiveMinimum = require_user_text.boundOf(exMin, "exclusiveMinValue");
735
1100
  const exMax = meta.get("expect.exclusiveMax");
736
- if (exMax !== void 0) schema.exclusiveMaximum = require_unique_name.boundOf(exMax, "exclusiveMaxValue");
1101
+ if (exMax !== void 0) schema.exclusiveMaximum = require_user_text.boundOf(exMax, "exclusiveMaxValue");
737
1102
  }
738
1103
  }
739
1104
  const LOWER_BOUNDS = new Set([
@@ -759,7 +1124,7 @@ const UPPER_BOUNDS = new Set([
759
1124
  applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
760
1125
  continue;
761
1126
  }
762
- if (member.const !== void 0) continue;
1127
+ if (member.const !== void 0 || member.enum !== void 0) continue;
763
1128
  const type = member.type;
764
1129
  const extra = { type };
765
1130
  if (type === "array") {
@@ -802,13 +1167,20 @@ const UPPER_BOUNDS = new Set([
802
1167
  */ function fromJsonSchema(schema) {
803
1168
  const defsSource = schema.$defs || schema.definitions || {};
804
1169
  const resolved = /* @__PURE__ */ new Map();
805
- const convert = (s) => {
806
- if (!s || Object.keys(s).length === 0) return require_unique_name.defineAnnotatedType().designType("any").$type;
1170
+ /** `title` → `@meta.label`, `description` → `@meta.description` (not on a shared `$ref`). */ const convert = (s) => {
1171
+ const type = convertNode(s);
1172
+ if (s && !s.$ref) {
1173
+ for (const [key, keyword] of ANNOTATION_KEYWORDS) if (typeof s[keyword] === "string") require_user_text.annotate(type.metadata, key, s[keyword]);
1174
+ }
1175
+ return type;
1176
+ };
1177
+ const convertNode = (s) => {
1178
+ if (!s || Object.keys(s).length === 0) return require_user_text.defineAnnotatedType().designType("any").$type;
807
1179
  if (s.$ref) {
808
1180
  const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
809
1181
  if (resolved.has(refName)) return resolved.get(refName);
810
1182
  if (defsSource[refName]) {
811
- const placeholder = require_unique_name.defineAnnotatedType().designType("any").$type;
1183
+ const placeholder = require_user_text.defineAnnotatedType().designType("any").$type;
812
1184
  resolved.set(refName, placeholder);
813
1185
  const type = convert(defsSource[refName]);
814
1186
  resolved.set(refName, type);
@@ -819,41 +1191,43 @@ const UPPER_BOUNDS = new Set([
819
1191
  if ("const" in s) {
820
1192
  const val = s.const;
821
1193
  const dt = val === null ? "null" : typeof val;
822
- return require_unique_name.defineAnnotatedType().designType(dt).value(val).$type;
1194
+ return require_user_text.defineAnnotatedType().designType(dt).value(val).$type;
823
1195
  }
824
1196
  if (s.enum) {
825
- const handle = require_unique_name.defineAnnotatedType("union");
1197
+ const handle = require_user_text.defineAnnotatedType("union");
826
1198
  for (const val of s.enum) {
827
1199
  const dt = val === null ? "null" : typeof val;
828
- handle.item(require_unique_name.defineAnnotatedType().designType(dt).value(val).$type);
1200
+ handle.item(require_user_text.defineAnnotatedType().designType(dt).value(val).$type);
829
1201
  }
830
1202
  return handle.$type;
831
1203
  }
832
1204
  if (s.anyOf) {
833
- const handle = require_unique_name.defineAnnotatedType("union");
1205
+ const handle = require_user_text.defineAnnotatedType("union");
834
1206
  for (const item of s.anyOf) handle.item(convert(item));
835
1207
  return handle.$type;
836
1208
  }
837
1209
  if (s.oneOf) {
838
- const handle = require_unique_name.defineAnnotatedType("union");
1210
+ const handle = require_user_text.defineAnnotatedType("union");
839
1211
  for (const item of s.oneOf) handle.item(convert(item));
840
1212
  return handle.$type;
841
1213
  }
842
1214
  if (s.allOf && !s.type) {
843
- const handle = require_unique_name.defineAnnotatedType("intersection");
1215
+ const handle = require_user_text.defineAnnotatedType("intersection");
844
1216
  for (const item of s.allOf) handle.item(convert(item));
845
1217
  return handle.$type;
846
1218
  }
847
1219
  if (Array.isArray(s.type)) {
848
- const handle = require_unique_name.defineAnnotatedType("union");
1220
+ const handle = require_user_text.defineAnnotatedType("union");
849
1221
  for (const t of s.type) handle.item(convert({
850
1222
  ...s,
851
- type: t
1223
+ type: t,
1224
+ title: void 0,
1225
+ description: void 0
852
1226
  }));
853
1227
  return handle.$type;
854
1228
  }
855
1229
  if (s.type === "object") {
856
- const handle = require_unique_name.defineAnnotatedType("object");
1230
+ const handle = require_user_text.defineAnnotatedType("object");
857
1231
  const required = new Set(s.required || []);
858
1232
  if (s.properties) for (const [key, propSchema] of Object.entries(s.properties)) {
859
1233
  const optional = !required.has(key);
@@ -862,22 +1236,24 @@ const UPPER_BOUNDS = new Set([
862
1236
  handle.prop(key, propType);
863
1237
  }
864
1238
  for (const [pattern, propSchema] of Object.entries(s.patternProperties ?? {})) handle.propPattern(compilePattern(pattern), convert(propSchema));
1239
+ if (typeof s.minProperties === "number") handle.annotate("expect.minKeys", { count: s.minProperties });
1240
+ if (typeof s.maxProperties === "number") handle.annotate("expect.maxKeys", { count: s.maxProperties });
865
1241
  return handle.$type;
866
1242
  }
867
1243
  if (s.type === "array") {
868
1244
  if (Array.isArray(s.items)) {
869
- const handle = require_unique_name.defineAnnotatedType("tuple");
1245
+ const handle = require_user_text.defineAnnotatedType("tuple");
870
1246
  for (const item of s.items) handle.item(convert(item));
871
1247
  return handle.$type;
872
1248
  }
873
- const itemType = s.items ? convert(s.items) : require_unique_name.defineAnnotatedType().designType("any").$type;
874
- const handle = require_unique_name.defineAnnotatedType("array").of(itemType);
1249
+ const itemType = s.items ? convert(s.items) : require_user_text.defineAnnotatedType().designType("any").$type;
1250
+ const handle = require_user_text.defineAnnotatedType("array").of(itemType);
875
1251
  if (typeof s.minItems === "number") handle.annotate("expect.minLength", { length: s.minItems });
876
1252
  if (typeof s.maxItems === "number") handle.annotate("expect.maxLength", { length: s.maxItems });
877
1253
  return handle.$type;
878
1254
  }
879
1255
  if (s.type === "string") {
880
- const handle = require_unique_name.defineAnnotatedType().designType("string").tags("string");
1256
+ const handle = require_user_text.defineAnnotatedType().designType("string").tags("string");
881
1257
  if (typeof s.minLength === "number") handle.annotate("expect.minLength", { length: s.minLength });
882
1258
  if (typeof s.maxLength === "number") handle.annotate("expect.maxLength", { length: s.maxLength });
883
1259
  if (s.pattern) handle.annotate("expect.pattern", { pattern: s.pattern }, true);
@@ -887,19 +1263,19 @@ const UPPER_BOUNDS = new Set([
887
1263
  return handle.$type;
888
1264
  }
889
1265
  if (s.type === "integer") {
890
- const handle = require_unique_name.defineAnnotatedType().designType("number").tags("number");
1266
+ const handle = require_user_text.defineAnnotatedType().designType("number").tags("number");
891
1267
  handle.annotate("expect.int", true);
892
1268
  annotateNumberBounds(handle, s);
893
1269
  return handle.$type;
894
1270
  }
895
1271
  if (s.type === "number") {
896
- const handle = require_unique_name.defineAnnotatedType().designType("number").tags("number");
1272
+ const handle = require_user_text.defineAnnotatedType().designType("number").tags("number");
897
1273
  annotateNumberBounds(handle, s);
898
1274
  return handle.$type;
899
1275
  }
900
- if (s.type === "boolean") return require_unique_name.defineAnnotatedType().designType("boolean").tags("boolean").$type;
901
- if (s.type === "null") return require_unique_name.defineAnnotatedType().designType("null").tags("null").$type;
902
- return require_unique_name.defineAnnotatedType().designType("any").$type;
1276
+ if (s.type === "boolean") return require_user_text.defineAnnotatedType().designType("boolean").tags("boolean").$type;
1277
+ if (s.type === "null") return require_user_text.defineAnnotatedType().designType("null").tags("null").$type;
1278
+ return require_user_text.defineAnnotatedType().designType("any").$type;
903
1279
  };
904
1280
  return convert(schema);
905
1281
  }
@@ -944,14 +1320,15 @@ const UPPER_BOUNDS = new Set([
944
1320
  * to it are renamed.
945
1321
  *
946
1322
  * @param types - Array of annotated types, each with an `id`.
1323
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
947
1324
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
948
- */ function mergeJsonSchemas(types) {
1325
+ */ function mergeJsonSchemas(types, opts) {
949
1326
  const mergedDefs = {};
950
1327
  const schemas = {};
951
1328
  for (const type of types) {
952
1329
  const name = type.id;
953
1330
  if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
954
- const { $defs: defs, ...schema } = buildJsonSchema(type);
1331
+ const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
955
1332
  if (!defs) {
956
1333
  schemas[name] = schema;
957
1334
  continue;
@@ -961,7 +1338,7 @@ const UPPER_BOUNDS = new Set([
961
1338
  for (const defName of Object.keys(local)) {
962
1339
  const family = defName.replace(/_\d+$/, "");
963
1340
  const same = Object.keys(mergedDefs).find((merged) => merged.replace(/_\d+$/, "") === family && sameSchema(local[defName], local, mergedDefs[merged], mergedDefs, /* @__PURE__ */ new Set()));
964
- renamed.set(defName, same ?? (defName in mergedDefs || [...renamed.values()].includes(defName) ? require_unique_name.uniqueName(family, (n) => n in mergedDefs || [...renamed.values()].includes(n), "_") : defName));
1341
+ renamed.set(defName, same ?? (defName in mergedDefs || [...renamed.values()].includes(defName) ? require_user_text.uniqueName(family, (n) => n in mergedDefs || [...renamed.values()].includes(n), "_") : defName));
965
1342
  }
966
1343
  for (const [defName, merged] of renamed) if (!(merged in mergedDefs)) mergedDefs[merged] = renameRefs(local[defName], renamed);
967
1344
  schemas[name] = renameRefs(schema, renamed);
@@ -1026,27 +1403,31 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1026
1403
  }
1027
1404
  if (mode === "db") {
1028
1405
  const dbValue = prop.metadata.get("db.default");
1029
- if (dbValue !== void 0) {
1030
- const parsed = parseRawValue(dbValue, prop);
1031
- if (parsed !== void 0 && prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
1032
- return;
1033
- }
1406
+ if (dbValue !== void 0) return validRawValue(dbValue, prop);
1034
1407
  if (prop.metadata.has("db.default.increment")) return { value: "increment" };
1035
1408
  if (prop.metadata.has("db.default.uuid")) return { value: "uuid" };
1036
1409
  if (prop.metadata.has("db.default.now")) return { value: "now" };
1037
1410
  return;
1038
1411
  }
1039
1412
  const metaKey = mode === "default" ? "meta.default" : "meta.example";
1040
- const rawStr = prop.metadata.get(metaKey);
1041
- if (rawStr === void 0) return;
1042
- const parsed = parseRawValue(rawStr, prop);
1043
- if (parsed === void 0) return;
1044
- if (prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
1413
+ const metaValue = prop.metadata.get(metaKey);
1414
+ if (metaValue === void 0) return;
1415
+ return validRawValue(metaValue, prop);
1416
+ }
1417
+ /**
1418
+ * An annotation's raw value as a valid value of `prop` (see {@link parseRawValue}); a string the
1419
+ * JSON reading does not fit is tried as the string itself (a `decimal` field, `decimal | null`).
1420
+ */ function validRawValue(raw, prop) {
1421
+ const validator = prop.validator({ unknownProps: "ignore" });
1422
+ const parsed = parseRawValue(raw, prop);
1423
+ if (parsed !== void 0 && validator.validate(parsed, true)) return { value: parsed };
1424
+ if (typeof raw === "string" && parsed !== raw && validator.validate(raw, true)) return { value: raw };
1045
1425
  }
1046
1426
  /**
1047
- * Parses a raw annotation string into a JS value.
1048
- * Strings are returned as-is for string types; everything else goes through JSON.parse.
1427
+ * Parses a raw annotation value into a JS value: a number / boolean literal (a `value`
1428
+ * argument) as it is; a string as-is for string types, else through JSON.parse.
1049
1429
  */ function parseRawValue(raw, prop) {
1430
+ if (typeof raw !== "string") return raw;
1050
1431
  if (prop.type.kind === "" && prop.type.designType === "string") return raw;
1051
1432
  try {
1052
1433
  return JSON.parse(raw);
@@ -1061,7 +1442,8 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1061
1442
  case "number": return 0;
1062
1443
  case "boolean": return false;
1063
1444
  case "undefined": return;
1064
- case "null": return null;
1445
+ case "null":
1446
+ case "any": return null;
1065
1447
  default: return;
1066
1448
  }
1067
1449
  }
@@ -1104,7 +1486,7 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1104
1486
  */ function* build(def, path, mode, walk) {
1105
1487
  const resolved = resolveValue(def, path, mode);
1106
1488
  if (resolved !== void 0) return resolved.value;
1107
- const below = require_unique_name.enterCut(walk.path, def);
1489
+ const below = require_user_text.enterCut(walk.path, def);
1108
1490
  if (below === false) return STOPPED;
1109
1491
  return yield buildStructure(def, path, mode, {
1110
1492
  ...walk,
@@ -1112,7 +1494,7 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1112
1494
  });
1113
1495
  }
1114
1496
  function* buildStructure(def, path, mode, walk) {
1115
- const recursive = (node) => require_unique_name.enterCut(walk.path, node) === false;
1497
+ const recursive = (node) => require_user_text.enterCut(walk.path, node) === false;
1116
1498
  const stops = (value) => value === STOPPED && !walk.lenient;
1117
1499
  const type = def.type;
1118
1500
  switch (type.kind) {
@@ -1120,7 +1502,7 @@ function* buildStructure(def, path, mode, walk) {
1120
1502
  case "object": {
1121
1503
  const data = {};
1122
1504
  for (const [key, prop] of type.props.entries()) {
1123
- if (require_unique_name.isPhantomType(prop)) continue;
1505
+ if (require_user_text.isPhantomType(prop)) continue;
1124
1506
  const childPath = path ? `${path}.${key}` : key;
1125
1507
  if (prop.optional) {
1126
1508
  if (mode === "example") {
@@ -1159,7 +1541,12 @@ function* buildStructure(def, path, mode, walk) {
1159
1541
  const items = [];
1160
1542
  for (const item of type.items) items.push(yield build(item, path, mode, walk));
1161
1543
  if (items.some(stops)) return STOPPED;
1162
- const values = items.filter((item) => item !== STOPPED);
1544
+ const isAny = (i) => {
1545
+ const t = type.items[i].type;
1546
+ return t.kind === "" && t.designType === "any";
1547
+ };
1548
+ const kept = items.filter((item, i) => item !== STOPPED && !isAny(i));
1549
+ const values = kept.length > 0 ? kept : items.filter((item) => item !== STOPPED);
1163
1550
  return values.length > 0 && values.every(isPlainObject) ? Object.assign({}, ...values) : values[0];
1164
1551
  }
1165
1552
  default: throw new Error(`Unknown type kind "${type.kind}"`);
@@ -1190,12 +1577,13 @@ function isPlainObject(value) {
1190
1577
  /**
1191
1578
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
1192
1579
  * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
1193
- * (`static toJsonSchema()`).
1194
- */ function lazyJsonSchema(type) {
1580
+ * (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
1581
+ * of a type).
1582
+ */ function lazyJsonSchema(type, opts) {
1195
1583
  const known = lazy.get(type);
1196
- const writes = require_unique_name.metadataWriteCount();
1584
+ const writes = require_user_text.metadataWriteCount();
1197
1585
  if (known?.writes === writes) return known.schema;
1198
- const schema = buildJsonSchema(type);
1586
+ const schema = buildJsonSchema(type, opts);
1199
1587
  lazy.set(type, {
1200
1588
  writes,
1201
1589
  schema
@@ -1207,14 +1595,15 @@ function isPlainObject(value) {
1207
1595
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
1208
1596
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
1209
1597
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
1210
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
1211
- */ function bundledSchemaOf(type, literal, modules = []) {
1212
- const applied = require_unique_name.appliedBlockModules();
1598
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
1599
+ * `jsonSchemaOptions` of the build (the literal was built with them).
1600
+ */ function bundledSchemaOf(type, literal, modules = [], opts) {
1601
+ const applied = require_user_text.appliedBlockModules();
1213
1602
  const known = bundled.get(type);
1214
1603
  if (known?.size === applied.size) return known.schema;
1215
1604
  const accounted = new Set(modules);
1216
1605
  const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
1217
- const schema = same ? literal() : buildJsonSchema(type);
1606
+ const schema = same ? literal() : buildJsonSchema(type, opts);
1218
1607
  bundled.set(type, {
1219
1608
  size: applied.size,
1220
1609
  schema,
@@ -1253,10 +1642,10 @@ function isPlainObject(value) {
1253
1642
  const union = existing;
1254
1643
  for (const [key, value] of def.metadata) union.metadata.set(key, value);
1255
1644
  union.type.items.push(def);
1256
- require_unique_name.touched(union.type);
1645
+ require_user_text.touched(union.type);
1257
1646
  delete union.optional;
1258
1647
  } else if (existing) {
1259
- const flatUnion = require_unique_name.defineAnnotatedType("union").copyMetadata(existing.metadata).copyMetadata(def.metadata);
1648
+ const flatUnion = require_user_text.defineAnnotatedType("union").copyMetadata(existing.metadata).copyMetadata(def.metadata);
1260
1649
  flatUnion.item(existing).item(def);
1261
1650
  const unionType = flatUnion.$type;
1262
1651
  unionType.__flat_union = true;
@@ -1270,11 +1659,11 @@ function isPlainObject(value) {
1270
1659
  const entries = [...def.type.props];
1271
1660
  for (let i = entries.length - 1; i >= 0; i--) {
1272
1661
  const [key, value] = entries[i];
1273
- if (!(skipPhantom && require_unique_name.isPhantomType(value))) tasks.push(() => flattenType(value, prefix ? `${prefix}.${key}` : key, inComplex, path));
1662
+ if (!(skipPhantom && require_user_text.isPhantomType(value))) tasks.push(() => flattenType(value, prefix ? `${prefix}.${key}` : key, inComplex, path));
1274
1663
  }
1275
1664
  }
1276
1665
  /** The sub-paths of array element / union item `def` at `name` (no entry of its own). */ function flattenArray(def, name, path) {
1277
- const below = require_unique_name.enterCut(path, def);
1666
+ const below = require_user_text.enterCut(path, def);
1278
1667
  if (below === false) return;
1279
1668
  switch (def.type.kind) {
1280
1669
  case "object":
@@ -1299,7 +1688,7 @@ function isPlainObject(value) {
1299
1688
  }
1300
1689
  }
1301
1690
  /** Flattens `def` at `prefix`, below `path`. */ function flattenType(def, prefix, inComplexTypeOrArray, path) {
1302
- const below = require_unique_name.enterCut(path, def);
1691
+ const below = require_user_text.enterCut(path, def);
1303
1692
  if (below === false) {
1304
1693
  addFieldToFlatMap(prefix, def);
1305
1694
  fieldDone(prefix, def);
@@ -1314,13 +1703,13 @@ function isPlainObject(value) {
1314
1703
  case "array": {
1315
1704
  let typeArray = def;
1316
1705
  if (!inComplexTypeOrArray) {
1317
- typeArray = require_unique_name.defineAnnotatedType().type(def).copyMetadata(def.metadata).$type;
1706
+ typeArray = require_user_text.defineAnnotatedType().type(def).copyMetadata(def.metadata).$type;
1318
1707
  if (def.optional) typeArray.optional = def.optional;
1319
1708
  if (options?.topLevelArrayTag) typeArray.metadata.set(options.topLevelArrayTag, true);
1320
1709
  }
1321
1710
  addFieldToFlatMap(prefix, typeArray);
1322
1711
  tasks.push(() => fieldDone(prefix, def));
1323
- if (!require_unique_name.isAnnotatedTypeOfPrimitive(typeArray.type.of)) {
1712
+ if (!require_user_text.isAnnotatedTypeOfPrimitive(typeArray.type.of)) {
1324
1713
  const of = typeArray.type.of;
1325
1714
  tasks.push(() => flattenArray(of, prefix, below));
1326
1715
  }
@@ -1357,7 +1746,7 @@ function isPlainObject(value) {
1357
1746
 
1358
1747
  //#endregion
1359
1748
  //#region packages/typescript/src/runtime/serialize.ts
1360
- function _define_property(obj, key, value) {
1749
+ function _define_property$1(obj, key, value) {
1361
1750
  if (key in obj) Object.defineProperty(obj, key, {
1362
1751
  value,
1363
1752
  enumerable: true,
@@ -1405,7 +1794,7 @@ function _define_property(obj, key, value) {
1405
1794
  */ keyOf(def) {
1406
1795
  let key = this.keys.get(def.type);
1407
1796
  if (key === void 0) {
1408
- key = require_unique_name.uniqueName(def.id ?? ANON_ID, (k) => this.taken.has(k), "@");
1797
+ key = require_user_text.uniqueName(def.id ?? ANON_ID, (k) => this.taken.has(k), "@");
1409
1798
  this.taken.add(key);
1410
1799
  this.keys.set(def.type, key);
1411
1800
  }
@@ -1429,17 +1818,17 @@ function _define_property(obj, key, value) {
1429
1818
  return id;
1430
1819
  }
1431
1820
  constructor() {
1432
- _define_property(this, "own", /* @__PURE__ */ new Map());
1821
+ _define_property$1(this, "own", /* @__PURE__ */ new Map());
1433
1822
  /**
1434
1823
  * The nodes without an id met more than once (see `indexPayload`): serialized once, with a
1435
1824
  * payload id, and referenced (`$ref`, `anon`) wherever else they are.
1436
- */ _define_property(this, "repeated", /* @__PURE__ */ new Set());
1437
- _define_property(this, "firstKeys", /* @__PURE__ */ new Map());
1438
- _define_property(this, "identities", /* @__PURE__ */ new WeakMap());
1439
- _define_property(this, "nextId", 0);
1440
- /** Payload ids by type def (see {@link keyOf}). */ _define_property(this, "keys", /* @__PURE__ */ new WeakMap());
1441
- /** The payload ids given so far. */ _define_property(this, "taken", /* @__PURE__ */ new Set());
1442
- /** The `cut` payload of defs (see `indexPayload`). */ _define_property(this, "cutKeys", /* @__PURE__ */ new WeakMap());
1825
+ */ _define_property$1(this, "repeated", /* @__PURE__ */ new Set());
1826
+ _define_property$1(this, "firstKeys", /* @__PURE__ */ new Map());
1827
+ _define_property$1(this, "identities", /* @__PURE__ */ new WeakMap());
1828
+ _define_property$1(this, "nextId", 0);
1829
+ /** Payload ids by type def (see {@link keyOf}). */ _define_property$1(this, "keys", /* @__PURE__ */ new WeakMap());
1830
+ /** The payload ids given so far. */ _define_property$1(this, "taken", /* @__PURE__ */ new Set());
1831
+ /** The `cut` payload of defs (see `indexPayload`). */ _define_property$1(this, "cutKeys", /* @__PURE__ */ new WeakMap());
1443
1832
  }
1444
1833
  };
1445
1834
  /**
@@ -1599,7 +1988,7 @@ function* serializeNode(def, path, options, visited) {
1599
1988
  if (counted.has(type) && !node.id) visited.repeated.add(type);
1600
1989
  counted.add(type);
1601
1990
  if (!first || node.id) return;
1602
- const key = require_unique_name.cutKey(node);
1991
+ const key = require_user_text.cutKey(node);
1603
1992
  const group = groups.get(key);
1604
1993
  if (!group) groups.set(key, [type]);
1605
1994
  else if (!group.includes(type)) group.push(type);
@@ -1670,12 +2059,12 @@ function* serializeTypeDef(def, path, options, visited) {
1670
2059
  * invoked. Classes, `function` expressions, async/generator functions and any other function
1671
2060
  * are never called, so serializing never runs user code.
1672
2061
  */ function resolveAnnotationTarget(value) {
1673
- if (require_unique_name.isAnnotatedType(value)) return value;
2062
+ if (require_user_text.isAnnotatedType(value)) return value;
1674
2063
  if (typeof value === "function" && value.length === 0 && !Object.prototype.hasOwnProperty.call(value, "prototype") && value.constructor === Function) {
1675
2064
  const fn = value;
1676
2065
  try {
1677
2066
  const target = fn();
1678
- return require_unique_name.isAnnotatedType(target) ? target : void 0;
2067
+ return require_user_text.isAnnotatedType(target) ? target : void 0;
1679
2068
  } catch {
1680
2069
  return;
1681
2070
  }
@@ -1781,10 +2170,10 @@ function serializeMetadata(owner, site, options, state) {
1781
2170
  return token;
1782
2171
  }
1783
2172
  function emptyObjectTypeDef() {
1784
- return require_unique_name.createObjectTypeDef();
2173
+ return require_user_text.createObjectTypeDef();
1785
2174
  }
1786
2175
  function toMetadataMap(record) {
1787
- return require_unique_name.createMetadataMap(Object.entries(record));
2176
+ return require_user_text.createMetadataMap(Object.entries(record));
1788
2177
  }
1789
2178
  function* deserializeRef(data, resolved) {
1790
2179
  if (!data.ref) return;
@@ -1796,7 +2185,7 @@ function* deserializeRef(data, resolved) {
1796
2185
  field: data.ref.field
1797
2186
  };
1798
2187
  }
1799
- const sentinel = require_unique_name.createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
2188
+ const sentinel = require_user_text.createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
1800
2189
  return {
1801
2190
  type: () => sentinel,
1802
2191
  field: data.ref.field
@@ -1807,8 +2196,8 @@ function* deserializeNode(data, resolved) {
1807
2196
  const { id: refId, own } = data.type;
1808
2197
  const target = resolved.get(refId);
1809
2198
  const id = data.anon ? void 0 : data.origId ?? target?.id ?? refId;
1810
- if (!own) return target || require_unique_name.createAnnotatedTypeNode(emptyObjectTypeDef(), require_unique_name.createMetadataMap(), { id });
1811
- const node = require_unique_name.createAnnotatedTypeNode(target?.type ?? emptyObjectTypeDef(), toMetadataMap(data.metadata), {
2199
+ if (!own) return target || require_user_text.createAnnotatedTypeNode(emptyObjectTypeDef(), require_user_text.createMetadataMap(), { id });
2200
+ const node = require_user_text.createAnnotatedTypeNode(target?.type ?? emptyObjectTypeDef(), toMetadataMap(data.metadata), {
1812
2201
  id,
1813
2202
  optional: data.optional || void 0,
1814
2203
  ref: yield deserializeRef(data, resolved)
@@ -1828,7 +2217,7 @@ function* deserializeNode(data, resolved) {
1828
2217
  if (data.id) {
1829
2218
  const existing = resolved.get(data.id);
1830
2219
  if (existing) return existing;
1831
- result = require_unique_name.createAnnotatedTypeNode(emptyObjectTypeDef(), metadata, {
2220
+ result = require_user_text.createAnnotatedTypeNode(emptyObjectTypeDef(), metadata, {
1832
2221
  optional: data.optional || void 0,
1833
2222
  id: data.anon ? void 0 : data.origId ?? data.id
1834
2223
  });
@@ -1836,13 +2225,13 @@ function* deserializeNode(data, resolved) {
1836
2225
  }
1837
2226
  const type = yield deserializeTypeDef(data.type, resolved);
1838
2227
  const ref = yield deserializeRef(data, resolved);
1839
- if (data.cut !== void 0) require_unique_name.cutAs(type, cutToken(resolved, data.cut));
2228
+ if (data.cut !== void 0) require_user_text.cutAs(type, cutToken(resolved, data.cut));
1840
2229
  if (result) {
1841
2230
  result.type = type;
1842
2231
  if (ref) result.ref = ref;
1843
2232
  return result;
1844
2233
  }
1845
- return require_unique_name.createAnnotatedTypeNode(type, metadata, {
2234
+ return require_user_text.createAnnotatedTypeNode(type, metadata, {
1846
2235
  optional: data.optional || void 0,
1847
2236
  id: data.id || void 0,
1848
2237
  ref
@@ -1861,11 +2250,11 @@ function* deserializeTypeDef(t, resolved) {
1861
2250
  return result;
1862
2251
  }
1863
2252
  case "object": {
1864
- const def = require_unique_name.createObjectTypeDef(tags);
2253
+ const def = require_user_text.createObjectTypeDef(tags);
1865
2254
  for (const [key, val] of Object.entries(t.props)) def.props.set(key, yield deserializeNode(val, resolved));
1866
2255
  const patterns = [];
1867
2256
  for (const pp of t.propsPatterns) patterns.push({
1868
- pattern: require_unique_name.statelessRegExp(new RegExp(pp.pattern.source, pp.pattern.flags)),
2257
+ pattern: require_user_text.statelessRegExp(new RegExp(pp.pattern.source, pp.pattern.flags)),
1869
2258
  def: yield deserializeNode(pp.def, resolved)
1870
2259
  });
1871
2260
  def.propsPatterns = patterns;
@@ -1890,51 +2279,292 @@ function* deserializeTypeDef(t, resolved) {
1890
2279
  case "$ref": {
1891
2280
  const existing = resolved.get(t.id);
1892
2281
  if (existing) return existing.type;
1893
- return require_unique_name.createObjectTypeDef(tags);
2282
+ return require_user_text.createObjectTypeDef(tags);
1894
2283
  }
1895
2284
  default: throw new Error(`Unknown serialized type kind "${t.kind}"`);
1896
2285
  }
1897
2286
  }
1898
2287
 
1899
2288
  //#endregion
1900
- exports.$ak = require_unique_name.$ak;
1901
- exports.$alias = require_unique_name.$alias;
1902
- exports.$blk = require_unique_name.$blk;
1903
- exports.$end = require_unique_name.$end;
1904
- exports.$f = require_unique_name.$f;
1905
- exports.$fc = require_unique_name.$fc;
1906
- exports.$ft = require_unique_name.$ft;
1907
- exports.$nr = require_unique_name.$nr;
1908
- exports.$ps = require_unique_name.$ps;
1909
- exports.$q = require_unique_name.$q;
1910
- exports.$sh = require_unique_name.$sh;
1911
- exports.LayerMap = require_unique_name.LayerMap;
2289
+ //#region packages/typescript/src/runtime/translate-served.ts
2290
+ /**
2291
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
2292
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
2293
+ * collected for the client.
2294
+ */ function _define_property(obj, key, value) {
2295
+ if (key in obj) Object.defineProperty(obj, key, {
2296
+ value,
2297
+ enumerable: true,
2298
+ configurable: true,
2299
+ writable: true
2300
+ });
2301
+ else obj[key] = value;
2302
+ return obj;
2303
+ }
2304
+ /**
2305
+ * Translates the user-facing text of serialized annotated types (the output of
2306
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
2307
+ * found at any depth is read with {@link userTextOf}:
2308
+ *
2309
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
2310
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
2311
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
2312
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
2313
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
2314
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
2315
+ * translates the expressions' results by exact match.
2316
+ *
2317
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
2318
+ * result shares every part with no translated text, and is `json` itself when nothing was
2319
+ * translated.
2320
+ *
2321
+ * @example
2322
+ * ```ts
2323
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
2324
+ * i18n.exists(text) ? i18n.t(text) : undefined
2325
+ * )
2326
+ * ```
2327
+ */ function translateServed(json, t) {
2328
+ const texts = {};
2329
+ return {
2330
+ value: walk(json, void 0, {
2331
+ t,
2332
+ texts
2333
+ }),
2334
+ texts
2335
+ };
2336
+ }
2337
+ /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
2338
+ if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
2339
+ if (typeof value === "string") {
2340
+ if (mode === "expression") collectLiterals(value, ctx);
2341
+ else if (mode === true && require_user_text.formatCodeOf(value) === void 0) return translate(value, ctx) ?? value;
2342
+ return value;
2343
+ }
2344
+ if (typeof value !== "object" || value === null) return value;
2345
+ return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
2346
+ }
2347
+ /**
2348
+ * The mode of the value at `key` of an object of `mode`: a metadata key's user text, a field of a
2349
+ * value object's, else `metadata` objects only (a non-string text value — a `ref` target — has
2350
+ * metadata).
2351
+ */ function modeOf(key, mode) {
2352
+ if (typeof mode === "object") return mode.includes(`${key}()`) ? "expression" : mode.includes(key) || void 0;
2353
+ return mode === "metadata" && require_user_text.userTextOf(key) || (key === "metadata" ? "metadata" : void 0);
2354
+ }
2355
+ /** `t(text)` when it is a string (a plain-object dictionary also has `constructor`, …). */ function translate(text, ctx) {
2356
+ const out = ctx.t(text);
2357
+ return typeof out === "string" ? out : void 0;
2358
+ }
2359
+ /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
2360
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
2361
+ const translated = translate(literal, ctx);
2362
+ if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
2363
+ }
2364
+ }
2365
+ /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
2366
+ "n": "\n",
2367
+ "t": " ",
2368
+ "r": "\r",
2369
+ "b": "\b",
2370
+ "f": "\f",
2371
+ "v": "\v",
2372
+ "0": "\0",
2373
+ "\n": "",
2374
+ "\r": "",
2375
+ "\r\n": ""
2376
+ };
2377
+ /** 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;
2378
+ /** The string a literal's raw text (between its quotes) evaluates to. */ function decode(raw) {
2379
+ return raw.includes("\\") ? raw.replace(ESCAPE, (_, c) => {
2380
+ if (c.length < 3) return Object.hasOwn(ESCAPES, c) ? ESCAPES[c] : c;
2381
+ const code = Number.parseInt(c.replace(/[ux{}]/g, ""), 16);
2382
+ return code > 1114111 ? "" : String.fromCodePoint(code);
2383
+ }) : raw;
2384
+ }
2385
+ /** A character of an identifier or a number. */ const IDENT = RegExp("[\\p{ID_Continue}$]", "u");
2386
+ /** A run of {@link IDENT} characters at `lastIndex`. */ const IDENT_RUN = RegExp("[\\p{ID_Continue}$]+", "uy");
2387
+ /** Keywords whose `(…)` a statement follows: a `/` after the `)` starts a regular expression. */ const CONTROL = new Set([
2388
+ "if",
2389
+ "while",
2390
+ "for",
2391
+ "with"
2392
+ ]);
2393
+ /** Keywords after which `/` starts a regular expression rather than a division. */ const REGEX_AFTER_WORD = new Set([
2394
+ "return",
2395
+ "typeof",
2396
+ "instanceof",
2397
+ "in",
2398
+ "of",
2399
+ "new",
2400
+ "delete",
2401
+ "void",
2402
+ "throw",
2403
+ "case",
2404
+ "do",
2405
+ "else",
2406
+ "yield",
2407
+ "await"
2408
+ ]);
2409
+ let LiteralScanner = class LiteralScanner {
2410
+ /** Scans code up to the end, or to the `}` closing a template's `${`. */ code() {
2411
+ const src = this.src;
2412
+ while (this.i < src.length) {
2413
+ const c = src[this.i];
2414
+ if (c === "/" && src[this.i + 1] === "/") {
2415
+ const end = src.indexOf("\n", this.i);
2416
+ this.i = end === -1 ? src.length : end;
2417
+ } else if (c === "/" && src[this.i + 1] === "*") {
2418
+ const end = src.indexOf("*/", this.i + 2);
2419
+ this.i = end === -1 ? src.length : end + 2;
2420
+ } else if (c === "'" || c === "\"" || c === "`") {
2421
+ const text = this.literal(c);
2422
+ if (text !== void 0 && text.trim() !== "") this.out.add(text);
2423
+ this.regexOk = false;
2424
+ } else if (c === "/" && this.regexOk) {
2425
+ this.regex();
2426
+ this.regexOk = false;
2427
+ } else if (IDENT.test(c)) this.word();
2428
+ else if ((c === "+" || c === "-") && src[this.i + 1] === c) {
2429
+ this.i += 2;
2430
+ this.regexOk = false;
2431
+ } else {
2432
+ this.i++;
2433
+ if (/\s/.test(c)) continue;
2434
+ if (c === "(" || c === "{") this.open.push(c === "(" ? "p" : c);
2435
+ else if (c === ")" || c === "}") {
2436
+ const top = this.open.pop();
2437
+ if (top === "$") return;
2438
+ this.regexOk = top === "c";
2439
+ continue;
2440
+ }
2441
+ this.regexOk = c !== "]";
2442
+ }
2443
+ }
2444
+ }
2445
+ /** An identifier, keyword or number at `i`; `i` past it (and past a control keyword's `(`). */ word() {
2446
+ const src = this.src;
2447
+ IDENT_RUN.lastIndex = this.i;
2448
+ IDENT_RUN.test(src);
2449
+ const word = src.slice(this.i, IDENT_RUN.lastIndex);
2450
+ this.i = IDENT_RUN.lastIndex;
2451
+ this.regexOk = REGEX_AFTER_WORD.has(word);
2452
+ if (CONTROL.has(word)) {
2453
+ while (/\s/.test(src[this.i] ?? "")) this.i++;
2454
+ if (src[this.i] === "(") {
2455
+ this.i++;
2456
+ this.open.push("c");
2457
+ this.regexOk = true;
2458
+ }
2459
+ }
2460
+ }
2461
+ /**
2462
+ * A `'…'` / `"…"` / `` `…` `` literal at `i`, decoded (`undefined`: a template with `${…}`, whose
2463
+ * code is scanned); `i` past it.
2464
+ */ literal(quote) {
2465
+ const src = this.src;
2466
+ const start = ++this.i;
2467
+ let plain = true;
2468
+ while (this.i < src.length && src[this.i] !== quote) if (src[this.i] === "\\") this.i += src.startsWith("\r\n", this.i + 1) ? 3 : 2;
2469
+ else if (quote === "`" && src.startsWith("${", this.i)) {
2470
+ plain = false;
2471
+ this.i += 2;
2472
+ this.open.push("$");
2473
+ this.code();
2474
+ } else this.i++;
2475
+ const end = this.i++;
2476
+ return plain ? decode(src.slice(start, end)) : void 0;
2477
+ }
2478
+ /** A regular expression literal starting at `i`; `i` past its flags. */ regex() {
2479
+ const src = this.src;
2480
+ let inClass = false;
2481
+ this.i++;
2482
+ while (this.i < src.length && src[this.i] !== "\n") {
2483
+ const c = src[this.i++];
2484
+ if (c === "\\") this.i++;
2485
+ else if (c === "[") inClass = true;
2486
+ else if (c === "]") inClass = false;
2487
+ else if (c === "/" && !inClass) break;
2488
+ }
2489
+ while (this.i < src.length && /[a-z]/i.test(src[this.i])) this.i++;
2490
+ }
2491
+ constructor(src, out) {
2492
+ _define_property(this, "src", void 0);
2493
+ _define_property(this, "out", void 0);
2494
+ _define_property(this, "i", void 0);
2495
+ /** A `/` here starts a regular expression (no operand just ended), not a division. */ _define_property(this, "regexOk", void 0);
2496
+ /**
2497
+ * The open brackets: `c` — the `(` of an `if` / `while` / `for` / `with` (a `/` after its `)` is
2498
+ * a regex); `p` — another `(`; `{`; `$` — a template's `${`.
2499
+ */ _define_property(this, "open", void 0);
2500
+ this.src = src;
2501
+ this.out = out;
2502
+ this.i = 0;
2503
+ this.regexOk = true;
2504
+ this.open = [];
2505
+ }
2506
+ };
2507
+ /**
2508
+ * The string literals of JavaScript `source`, as the strings they evaluate to: `'…'`, `"…"` and
2509
+ * `` `…` `` templates without `${…}` (the literals inside a `${…}` count). Comments and regular
2510
+ * expression literals are skipped; empty and blank literals are left out.
2511
+ */ function stringLiterals(source) {
2512
+ const out = /* @__PURE__ */ new Set();
2513
+ new LiteralScanner(source, out).code();
2514
+ return [...out];
2515
+ }
2516
+
2517
+ //#endregion
2518
+ exports.$ak = require_user_text.$ak;
2519
+ exports.$alias = require_user_text.$alias;
2520
+ exports.$blk = require_user_text.$blk;
2521
+ exports.$end = require_user_text.$end;
2522
+ exports.$f = require_user_text.$f;
2523
+ exports.$fc = require_user_text.$fc;
2524
+ exports.$ft = require_user_text.$ft;
2525
+ exports.$nr = require_user_text.$nr;
2526
+ exports.$ps = require_user_text.$ps;
2527
+ exports.$q = require_user_text.$q;
2528
+ exports.$sh = require_user_text.$sh;
2529
+ exports.$ut = require_user_text.$ut;
2530
+ exports.LayerMap = require_user_text.LayerMap;
1912
2531
  exports.SERIALIZE_VERSION = SERIALIZE_VERSION;
1913
- exports.Validator = require_unique_name.Validator;
1914
- exports.ValidatorError = require_unique_name.ValidatorError;
1915
- exports.annotate = require_unique_name.annotate;
1916
- exports.appliedBlockModules = require_unique_name.appliedBlockModules;
2532
+ exports.VALIDATOR_ERROR_CODES = require_user_text.VALIDATOR_ERROR_CODES;
2533
+ exports.VALIDATOR_MESSAGES = require_user_text.VALIDATOR_MESSAGES;
2534
+ exports.Validator = require_user_text.Validator;
2535
+ exports.ValidatorError = require_user_text.ValidatorError;
2536
+ exports.annotate = require_user_text.annotate;
2537
+ exports.appliedBlockModules = require_user_text.appliedBlockModules;
1917
2538
  exports.buildJsonSchema = buildJsonSchema;
1918
2539
  exports.bundledSchemaOf = bundledSchemaOf;
1919
2540
  exports.coerceForType = coerceForType;
1920
2541
  exports.coerceScalar = coerceScalar;
1921
- exports.createAnnotatedTypeNode = require_unique_name.createAnnotatedTypeNode;
2542
+ exports.createAnnotatedTypeNode = require_user_text.createAnnotatedTypeNode;
1922
2543
  exports.createDataFromAnnotatedType = createDataFromAnnotatedType;
1923
- exports.defineAnnotatedType = require_unique_name.defineAnnotatedType;
2544
+ exports.defineAnnotatedType = require_user_text.defineAnnotatedType;
1924
2545
  exports.deserializeAnnotatedType = deserializeAnnotatedType;
1925
- exports.detectDiscriminator = detectDiscriminator;
2546
+ exports.detectDiscriminator = require_user_text.detectDiscriminator;
1926
2547
  exports.flattenAnnotatedType = flattenAnnotatedType;
1927
2548
  exports.forAnnotatedType = forAnnotatedType;
2549
+ exports.formatValidatorMessage = require_user_text.formatValidatorMessage;
1928
2550
  exports.fromJsonSchema = fromJsonSchema;
1929
- exports.invalidateCompiledValidators = require_unique_name.invalidateCompiledValidators;
1930
- exports.isAnnotatedType = require_unique_name.isAnnotatedType;
1931
- exports.isAnnotatedTypeOfPrimitive = require_unique_name.isAnnotatedTypeOfPrimitive;
1932
- exports.isPhantomType = require_unique_name.isPhantomType;
2551
+ exports.invalidateCompiledValidators = require_user_text.invalidateCompiledValidators;
2552
+ exports.isAnnotatedType = require_user_text.isAnnotatedType;
2553
+ exports.isAnnotatedTypeOfPrimitive = require_user_text.isAnnotatedTypeOfPrimitive;
2554
+ exports.isPhantomType = require_user_text.isPhantomType;
1933
2555
  exports.lazyJsonSchema = lazyJsonSchema;
2556
+ exports.localizeErrors = require_user_text.localizeErrors;
1934
2557
  exports.mergeJsonSchemas = mergeJsonSchemas;
1935
- exports.metaEmpty = require_unique_name.metaEmpty;
1936
- exports.pendingStatements = require_unique_name.pendingStatements;
1937
- exports.registerCompiledCheck = require_unique_name.registerCompiledCheck;
2558
+ exports.messagesTranslator = require_user_text.messagesTranslator;
2559
+ exports.metaEmpty = require_user_text.metaEmpty;
2560
+ exports.normalizeForType = normalizeForType;
2561
+ exports.pendingStatements = require_user_text.pendingStatements;
2562
+ exports.registerCompiledCheck = require_user_text.registerCompiledCheck;
2563
+ exports.registerUserText = require_user_text.registerUserText;
1938
2564
  exports.serializeAnnotatedType = serializeAnnotatedType;
1939
2565
  exports.throwFeatureDisabled = throwFeatureDisabled;
1940
- exports.watchLayer = require_unique_name.watchLayer;
2566
+ exports.translateServed = translateServed;
2567
+ exports.unionDiscriminator = require_user_text.unionDiscriminator;
2568
+ exports.userTextKeys = require_user_text.userTextKeys;
2569
+ exports.userTextOf = require_user_text.userTextOf;
2570
+ exports.watchLayer = require_user_text.watchLayer;