@atscript/typescript 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +25 -6
- package/dist/index.cjs +2 -2
- package/dist/index.d.ts +29 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-Ct9Ko5JG.mjs → plugin-Bx7j-vWf.mjs} +21 -6
- package/dist/{plugin-Cqao46Gt.cjs → plugin-JJ9MJ6AF.cjs} +21 -6
- package/dist/realm-runtime.js +787 -154
- package/dist/test-utils.cjs +2 -2
- package/dist/test-utils.d.ts +185 -157
- package/dist/test-utils.mjs +2 -2
- package/dist/{user-text-qL59indq.mjs → user-text-BOf56N4d.mjs} +25 -18
- package/dist/{user-text-BddKk8EU.cjs → user-text-Dl8FNKLL.cjs} +42 -17
- package/dist/utils.cjs +710 -84
- package/dist/utils.d.ts +138 -18
- package/dist/utils.mjs +708 -85
- package/package.json +4 -4
package/dist/utils.mjs
CHANGED
|
@@ -1,10 +1,91 @@
|
|
|
1
|
-
import { $ as
|
|
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/
|
|
3
|
+
//#region packages/typescript/src/runtime/copy-on-change.ts
|
|
4
|
+
/**
|
|
5
|
+
* Internal sentinel: the value cannot be taken by a type node (drives union branch selection in
|
|
6
|
+
* `coerce.ts` and `normalize.ts`). A {@link mapProps} step returns it to reject the whole object.
|
|
7
|
+
*/ const NO_MATCH = Symbol("atscript.no-match");
|
|
8
|
+
/**
|
|
9
|
+
* Maps the props of plain object `value` with `step` (props without a def — declared or pattern —
|
|
10
|
+
* are kept as they are). Copy-on-first-change: allocates the output only when some prop changed,
|
|
11
|
+
* else returns `value`; an own `__proto__` key stays an own key (never the output's prototype).
|
|
12
|
+
* NO_MATCH when a step returns it.
|
|
13
|
+
*/ function mapProps(type, value, step, ctx) {
|
|
14
|
+
const keys = Object.keys(value);
|
|
15
|
+
let out;
|
|
16
|
+
for (let i = 0; i < keys.length; i++) {
|
|
17
|
+
const key = keys[i];
|
|
18
|
+
const input = value[key];
|
|
19
|
+
let def = type.props.get(key);
|
|
20
|
+
if (!def) {
|
|
21
|
+
for (const { pattern, def: patternDef } of type.propsPatterns) if (pattern.test(key)) {
|
|
22
|
+
def = patternDef;
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const mapped = def ? step(def, input, ctx) : input;
|
|
27
|
+
if (mapped === NO_MATCH) return NO_MATCH;
|
|
28
|
+
if (out) setOwn(out, key, mapped);
|
|
29
|
+
else if (mapped !== input) {
|
|
30
|
+
out = {};
|
|
31
|
+
for (let j = 0; j < i; j++) setOwn(out, keys[j], value[keys[j]]);
|
|
32
|
+
setOwn(out, key, mapped);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return out ?? value;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Maps array / tuple items with `step`, against `of` (an array's item type) or `of[i]` (a tuple's
|
|
39
|
+
* items). Copy-on-first-change, as {@link mapProps}.
|
|
40
|
+
*/ function mapItems(value, of, step, ctx) {
|
|
41
|
+
return mapList(value, (input, i) => step(Array.isArray(of) ? of[i] : of, input, ctx));
|
|
42
|
+
}
|
|
43
|
+
/** Maps the items of `list` with `step`. Copy-on-first-change: `list` itself when none changed. */ function mapList(list, step) {
|
|
44
|
+
let out;
|
|
45
|
+
for (let i = 0; i < list.length; i++) {
|
|
46
|
+
const mapped = step(list[i], i);
|
|
47
|
+
if (out) out.push(mapped);
|
|
48
|
+
else if (mapped !== list[i]) {
|
|
49
|
+
out = list.slice(0, i);
|
|
50
|
+
out.push(mapped);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return out ?? list;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Maps the own values of JSON object `obj` with `step`. Copy-on-first-change: `obj` itself when
|
|
57
|
+
* none changed; an own `__proto__` key stays an own key.
|
|
58
|
+
*/ function mapEntries(obj, step) {
|
|
59
|
+
let out;
|
|
60
|
+
for (const key of Object.keys(obj)) {
|
|
61
|
+
const mapped = step(key, obj[key]);
|
|
62
|
+
if (mapped !== obj[key]) {
|
|
63
|
+
out ?? (out = { ...obj });
|
|
64
|
+
setOwn(out, key, mapped);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out ?? obj;
|
|
68
|
+
}
|
|
69
|
+
/** Whether `value` is a plain object (`{}` or prototype-less): class instances are not. */ function isPlainObject$1(value) {
|
|
70
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
71
|
+
const proto = Object.getPrototypeOf(value);
|
|
72
|
+
return proto === Object.prototype || proto === null;
|
|
73
|
+
}
|
|
4
74
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*/
|
|
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 { $ as boundOf, A as propAtChain, B as jsonSchemaPattern, C as createAnno
|
|
|
54
135
|
}
|
|
55
136
|
case "object":
|
|
56
137
|
if (!isPlainObject$1(value)) return NO_MATCH;
|
|
57
|
-
return
|
|
58
|
-
case "array": return Array.isArray(value) ?
|
|
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 ?
|
|
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
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*/
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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;
|
|
280
|
+
}
|
|
281
|
+
let of = parents.get(child);
|
|
282
|
+
if (!of) {
|
|
283
|
+
parents.set(child, of = []);
|
|
284
|
+
todo.push(child);
|
|
120
285
|
}
|
|
286
|
+
of.push(node);
|
|
121
287
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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));
|
|
132
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;
|
|
357
|
+
}
|
|
358
|
+
default: throw new Error(`Unknown type kind "${type.kind}"`);
|
|
133
359
|
}
|
|
134
|
-
|
|
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
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*/ function
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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,6 +518,7 @@ function isPlainObject$1(value) {
|
|
|
205
518
|
|
|
206
519
|
//#endregion
|
|
207
520
|
//#region packages/typescript/src/runtime/json-schema.ts
|
|
521
|
+
/** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
|
|
208
522
|
/**
|
|
209
523
|
* Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
|
|
210
524
|
*
|
|
@@ -220,8 +534,12 @@ function isPlainObject$1(value) {
|
|
|
220
534
|
* ```
|
|
221
535
|
*
|
|
222
536
|
* @param type - The annotated type to convert.
|
|
537
|
+
* @param opts - {@link TJsonSchemaOptions}.
|
|
223
538
|
* @returns A JSON Schema object.
|
|
224
|
-
*/ 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;
|
|
225
543
|
/**
|
|
226
544
|
* `$defs` entries by type def (identity): named objects (always extracted) and types found
|
|
227
545
|
* recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
|
|
@@ -249,8 +567,35 @@ function isPlainObject$1(value) {
|
|
|
249
567
|
...schema,
|
|
250
568
|
type: [schema.type, "null"]
|
|
251
569
|
};
|
|
252
|
-
|
|
253
|
-
|
|
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;
|
|
254
599
|
};
|
|
255
600
|
/**
|
|
256
601
|
* Non-primitive type defs being built: `true` once re-entered (recursive). A named object
|
|
@@ -287,7 +632,7 @@ function isPlainObject$1(value) {
|
|
|
287
632
|
* A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
|
|
288
633
|
* them instead, its recursion referring to the shared definition.
|
|
289
634
|
*/ function* refTo(typeDef, def, own) {
|
|
290
|
-
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);
|
|
291
636
|
inlining.add(def);
|
|
292
637
|
const schema = yield buildDef(def);
|
|
293
638
|
inlining.delete(def);
|
|
@@ -317,6 +662,7 @@ function isPlainObject$1(value) {
|
|
|
317
662
|
for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
|
|
318
663
|
schema.patternProperties = patternProperties(built, Object.keys(properties));
|
|
319
664
|
}
|
|
665
|
+
if (closed) schema.additionalProperties = false;
|
|
320
666
|
return schema;
|
|
321
667
|
}
|
|
322
668
|
/** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
|
|
@@ -326,14 +672,17 @@ function isPlainObject$1(value) {
|
|
|
326
672
|
const atRoot = def === type && !rootEntered;
|
|
327
673
|
rootEntered = true;
|
|
328
674
|
if (def.id && typeDef.kind === "object" && !atRoot) {
|
|
675
|
+
const own = annotations ? ownDef(def, type) ?? def : void 0;
|
|
329
676
|
if (!defs.has(typeDef)) {
|
|
330
677
|
reserve(typeDef, def.id, true);
|
|
331
678
|
const outer = building;
|
|
332
679
|
building = /* @__PURE__ */ new Map();
|
|
333
|
-
|
|
680
|
+
const entry = yield buildObject(def);
|
|
681
|
+
if (own) applyAnnotationKeywords(entry, own.metadata);
|
|
682
|
+
defs.get(typeDef).schema = entry;
|
|
334
683
|
building = outer;
|
|
335
684
|
}
|
|
336
|
-
return
|
|
685
|
+
return useOf(ref(typeDef), def, own, true);
|
|
337
686
|
}
|
|
338
687
|
if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
|
|
339
688
|
const repeated = atRoot ? void 0 : shared.get(typeDef);
|
|
@@ -362,7 +711,7 @@ function isPlainObject$1(value) {
|
|
|
362
711
|
const own = ownOf(def);
|
|
363
712
|
const same = def === own || sameConstraints(def, own);
|
|
364
713
|
defs.get(typeDef).schema = same ? schema : yield buildDef(own);
|
|
365
|
-
return def === type || !same ? schema : ref(typeDef);
|
|
714
|
+
return def === type || !same ? schema : useOf(ref(typeDef), def, own);
|
|
366
715
|
}
|
|
367
716
|
/** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
|
|
368
717
|
const ownOf = (def) => {
|
|
@@ -373,7 +722,12 @@ function isPlainObject$1(value) {
|
|
|
373
722
|
}
|
|
374
723
|
return own;
|
|
375
724
|
};
|
|
376
|
-
/** 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) {
|
|
377
731
|
const meta = def.metadata;
|
|
378
732
|
const all = function* (items) {
|
|
379
733
|
const out = [];
|
|
@@ -428,7 +782,7 @@ function isPlainObject$1(value) {
|
|
|
428
782
|
};
|
|
429
783
|
} else {
|
|
430
784
|
if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
|
|
431
|
-
schema = { anyOf: built };
|
|
785
|
+
schema = enums && enumOf(built, refSchemas) || { anyOf: built };
|
|
432
786
|
}
|
|
433
787
|
applyKeyCounts(schema, meta);
|
|
434
788
|
return schema;
|
|
@@ -681,13 +1035,41 @@ function withoutUniqueItems(meta) {
|
|
|
681
1035
|
const maxKeys = meta.get("expect.maxKeys");
|
|
682
1036
|
if (maxKeys !== void 0) schema.maxProperties = boundOf(maxKeys, "count");
|
|
683
1037
|
}
|
|
684
|
-
/** `
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
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;
|
|
691
1073
|
}
|
|
692
1074
|
/** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
|
|
693
1075
|
if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
|
|
@@ -741,7 +1123,7 @@ const UPPER_BOUNDS = new Set([
|
|
|
741
1123
|
applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
|
|
742
1124
|
continue;
|
|
743
1125
|
}
|
|
744
|
-
if (member.const !== void 0) continue;
|
|
1126
|
+
if (member.const !== void 0 || member.enum !== void 0) continue;
|
|
745
1127
|
const type = member.type;
|
|
746
1128
|
const extra = { type };
|
|
747
1129
|
if (type === "array") {
|
|
@@ -784,7 +1166,14 @@ const UPPER_BOUNDS = new Set([
|
|
|
784
1166
|
*/ function fromJsonSchema(schema) {
|
|
785
1167
|
const defsSource = schema.$defs || schema.definitions || {};
|
|
786
1168
|
const resolved = /* @__PURE__ */ new Map();
|
|
787
|
-
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) => {
|
|
788
1177
|
if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
|
|
789
1178
|
if (s.$ref) {
|
|
790
1179
|
const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
|
|
@@ -830,7 +1219,9 @@ const UPPER_BOUNDS = new Set([
|
|
|
830
1219
|
const handle = defineAnnotatedType("union");
|
|
831
1220
|
for (const t of s.type) handle.item(convert({
|
|
832
1221
|
...s,
|
|
833
|
-
type: t
|
|
1222
|
+
type: t,
|
|
1223
|
+
title: void 0,
|
|
1224
|
+
description: void 0
|
|
834
1225
|
}));
|
|
835
1226
|
return handle.$type;
|
|
836
1227
|
}
|
|
@@ -928,14 +1319,15 @@ const UPPER_BOUNDS = new Set([
|
|
|
928
1319
|
* to it are renamed.
|
|
929
1320
|
*
|
|
930
1321
|
* @param types - Array of annotated types, each with an `id`.
|
|
1322
|
+
* @param opts - {@link TJsonSchemaOptions}, for every schema.
|
|
931
1323
|
* @returns An object with `schemas` (keyed by id) and shared `$defs`.
|
|
932
|
-
*/ function mergeJsonSchemas(types) {
|
|
1324
|
+
*/ function mergeJsonSchemas(types, opts) {
|
|
933
1325
|
const mergedDefs = {};
|
|
934
1326
|
const schemas = {};
|
|
935
1327
|
for (const type of types) {
|
|
936
1328
|
const name = type.id;
|
|
937
1329
|
if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
|
|
938
|
-
const { $defs: defs, ...schema } = buildJsonSchema(type);
|
|
1330
|
+
const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
|
|
939
1331
|
if (!defs) {
|
|
940
1332
|
schemas[name] = schema;
|
|
941
1333
|
continue;
|
|
@@ -1184,12 +1576,13 @@ function isPlainObject(value) {
|
|
|
1184
1576
|
/**
|
|
1185
1577
|
* The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
|
|
1186
1578
|
* a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
|
|
1187
|
-
* (`static toJsonSchema()`)
|
|
1188
|
-
|
|
1579
|
+
* (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
|
|
1580
|
+
* of a type).
|
|
1581
|
+
*/ function lazyJsonSchema(type, opts) {
|
|
1189
1582
|
const known = lazy.get(type);
|
|
1190
1583
|
const writes = metadataWriteCount();
|
|
1191
1584
|
if (known?.writes === writes) return known.schema;
|
|
1192
|
-
const schema = buildJsonSchema(type);
|
|
1585
|
+
const schema = buildJsonSchema(type, opts);
|
|
1193
1586
|
lazy.set(type, {
|
|
1194
1587
|
writes,
|
|
1195
1588
|
schema
|
|
@@ -1201,14 +1594,15 @@ function isPlainObject(value) {
|
|
|
1201
1594
|
* The JSON schema of `type` (`jsonSchema: 'bundle'`): the
|
|
1202
1595
|
* bundled `literal` while the modules whose blocks applied are exactly those the build accounted
|
|
1203
1596
|
* (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
|
|
1204
|
-
* metadata writes are not seen (as in 0.1.110). Called by generated code
|
|
1205
|
-
|
|
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) {
|
|
1206
1600
|
const applied = appliedBlockModules();
|
|
1207
1601
|
const known = bundled.get(type);
|
|
1208
1602
|
if (known?.size === applied.size) return known.schema;
|
|
1209
1603
|
const accounted = new Set(modules);
|
|
1210
1604
|
const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
|
|
1211
|
-
const schema = same ? literal() : buildJsonSchema(type);
|
|
1605
|
+
const schema = same ? literal() : buildJsonSchema(type, opts);
|
|
1212
1606
|
bundled.set(type, {
|
|
1213
1607
|
size: applied.size,
|
|
1214
1608
|
schema,
|
|
@@ -1351,7 +1745,7 @@ function isPlainObject(value) {
|
|
|
1351
1745
|
|
|
1352
1746
|
//#endregion
|
|
1353
1747
|
//#region packages/typescript/src/runtime/serialize.ts
|
|
1354
|
-
function _define_property(obj, key, value) {
|
|
1748
|
+
function _define_property$1(obj, key, value) {
|
|
1355
1749
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
1356
1750
|
value,
|
|
1357
1751
|
enumerable: true,
|
|
@@ -1423,17 +1817,17 @@ function _define_property(obj, key, value) {
|
|
|
1423
1817
|
return id;
|
|
1424
1818
|
}
|
|
1425
1819
|
constructor() {
|
|
1426
|
-
_define_property(this, "own", /* @__PURE__ */ new Map());
|
|
1820
|
+
_define_property$1(this, "own", /* @__PURE__ */ new Map());
|
|
1427
1821
|
/**
|
|
1428
1822
|
* The nodes without an id met more than once (see `indexPayload`): serialized once, with a
|
|
1429
1823
|
* payload id, and referenced (`$ref`, `anon`) wherever else they are.
|
|
1430
|
-
*/ _define_property(this, "repeated", /* @__PURE__ */ new Set());
|
|
1431
|
-
_define_property(this, "firstKeys", /* @__PURE__ */ new Map());
|
|
1432
|
-
_define_property(this, "identities", /* @__PURE__ */ new WeakMap());
|
|
1433
|
-
_define_property(this, "nextId", 0);
|
|
1434
|
-
/** Payload ids by type def (see {@link keyOf}). */ _define_property(this, "keys", /* @__PURE__ */ new WeakMap());
|
|
1435
|
-
/** The payload ids given so far. */ _define_property(this, "taken", /* @__PURE__ */ new Set());
|
|
1436
|
-
/** The `cut` payload of defs (see `indexPayload`). */ _define_property(this, "cutKeys", /* @__PURE__ */ new WeakMap());
|
|
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());
|
|
1437
1831
|
}
|
|
1438
1832
|
};
|
|
1439
1833
|
/**
|
|
@@ -1891,4 +2285,233 @@ function* deserializeTypeDef(t, resolved) {
|
|
|
1891
2285
|
}
|
|
1892
2286
|
|
|
1893
2287
|
//#endregion
|
|
1894
|
-
|
|
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 };
|