@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.cjs
CHANGED
|
@@ -1,11 +1,92 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_user_text = require('./user-text-
|
|
2
|
+
const require_user_text = require('./user-text-Dl8FNKLL.cjs');
|
|
3
3
|
|
|
4
|
-
//#region packages/typescript/src/runtime/
|
|
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
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*/
|
|
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_user_text = require('./user-text-BddKk8EU.cjs');
|
|
|
55
136
|
}
|
|
56
137
|
case "object":
|
|
57
138
|
if (!isPlainObject$1(value)) return NO_MATCH;
|
|
58
|
-
return
|
|
59
|
-
case "array": return Array.isArray(value) ?
|
|
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 ?
|
|
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
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*/
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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;
|
|
281
|
+
}
|
|
282
|
+
let of = parents.get(child);
|
|
283
|
+
if (!of) {
|
|
284
|
+
parents.set(child, of = []);
|
|
285
|
+
todo.push(child);
|
|
121
286
|
}
|
|
287
|
+
of.push(node);
|
|
122
288
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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));
|
|
133
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;
|
|
358
|
+
}
|
|
359
|
+
default: throw new Error(`Unknown type kind "${type.kind}"`);
|
|
134
360
|
}
|
|
135
|
-
|
|
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
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*/ function
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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,6 +519,7 @@ function isPlainObject$1(value) {
|
|
|
206
519
|
|
|
207
520
|
//#endregion
|
|
208
521
|
//#region packages/typescript/src/runtime/json-schema.ts
|
|
522
|
+
/** Annotations written as JSON Schema annotation keywords (`annotations` option). */ const ANNOTATION_KEYWORDS = [["meta.label", "title"], ["meta.description", "description"]];
|
|
209
523
|
/**
|
|
210
524
|
* Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
|
|
211
525
|
*
|
|
@@ -221,8 +535,12 @@ function isPlainObject$1(value) {
|
|
|
221
535
|
* ```
|
|
222
536
|
*
|
|
223
537
|
* @param type - The annotated type to convert.
|
|
538
|
+
* @param opts - {@link TJsonSchemaOptions}.
|
|
224
539
|
* @returns A JSON Schema object.
|
|
225
|
-
*/ 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;
|
|
226
544
|
/**
|
|
227
545
|
* `$defs` entries by type def (identity): named objects (always extracted) and types found
|
|
228
546
|
* recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
|
|
@@ -250,8 +568,35 @@ function isPlainObject$1(value) {
|
|
|
250
568
|
...schema,
|
|
251
569
|
type: [schema.type, "null"]
|
|
252
570
|
};
|
|
253
|
-
|
|
254
|
-
|
|
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;
|
|
255
600
|
};
|
|
256
601
|
/**
|
|
257
602
|
* Non-primitive type defs being built: `true` once re-entered (recursive). A named object
|
|
@@ -288,7 +633,7 @@ function isPlainObject$1(value) {
|
|
|
288
633
|
* A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
|
|
289
634
|
* them instead, its recursion referring to the shared definition.
|
|
290
635
|
*/ function* refTo(typeDef, def, own) {
|
|
291
|
-
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);
|
|
292
637
|
inlining.add(def);
|
|
293
638
|
const schema = yield buildDef(def);
|
|
294
639
|
inlining.delete(def);
|
|
@@ -318,6 +663,7 @@ function isPlainObject$1(value) {
|
|
|
318
663
|
for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
|
|
319
664
|
schema.patternProperties = patternProperties(built, Object.keys(properties));
|
|
320
665
|
}
|
|
666
|
+
if (closed) schema.additionalProperties = false;
|
|
321
667
|
return schema;
|
|
322
668
|
}
|
|
323
669
|
/** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
|
|
@@ -327,14 +673,17 @@ function isPlainObject$1(value) {
|
|
|
327
673
|
const atRoot = def === type && !rootEntered;
|
|
328
674
|
rootEntered = true;
|
|
329
675
|
if (def.id && typeDef.kind === "object" && !atRoot) {
|
|
676
|
+
const own = annotations ? ownDef(def, type) ?? def : void 0;
|
|
330
677
|
if (!defs.has(typeDef)) {
|
|
331
678
|
reserve(typeDef, def.id, true);
|
|
332
679
|
const outer = building;
|
|
333
680
|
building = /* @__PURE__ */ new Map();
|
|
334
|
-
|
|
681
|
+
const entry = yield buildObject(def);
|
|
682
|
+
if (own) applyAnnotationKeywords(entry, own.metadata);
|
|
683
|
+
defs.get(typeDef).schema = entry;
|
|
335
684
|
building = outer;
|
|
336
685
|
}
|
|
337
|
-
return
|
|
686
|
+
return useOf(ref(typeDef), def, own, true);
|
|
338
687
|
}
|
|
339
688
|
if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
|
|
340
689
|
const repeated = atRoot ? void 0 : shared.get(typeDef);
|
|
@@ -363,7 +712,7 @@ function isPlainObject$1(value) {
|
|
|
363
712
|
const own = ownOf(def);
|
|
364
713
|
const same = def === own || sameConstraints(def, own);
|
|
365
714
|
defs.get(typeDef).schema = same ? schema : yield buildDef(own);
|
|
366
|
-
return def === type || !same ? schema : ref(typeDef);
|
|
715
|
+
return def === type || !same ? schema : useOf(ref(typeDef), def, own);
|
|
367
716
|
}
|
|
368
717
|
/** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
|
|
369
718
|
const ownOf = (def) => {
|
|
@@ -374,7 +723,12 @@ function isPlainObject$1(value) {
|
|
|
374
723
|
}
|
|
375
724
|
return own;
|
|
376
725
|
};
|
|
377
|
-
/** 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) {
|
|
378
732
|
const meta = def.metadata;
|
|
379
733
|
const all = function* (items) {
|
|
380
734
|
const out = [];
|
|
@@ -429,7 +783,7 @@ function isPlainObject$1(value) {
|
|
|
429
783
|
};
|
|
430
784
|
} else {
|
|
431
785
|
if (!require_user_text.metaEmpty(meta)) applyUnionConstraints(built, meta, items);
|
|
432
|
-
schema = { anyOf: built };
|
|
786
|
+
schema = enums && enumOf(built, refSchemas) || { anyOf: built };
|
|
433
787
|
}
|
|
434
788
|
applyKeyCounts(schema, meta);
|
|
435
789
|
return schema;
|
|
@@ -682,13 +1036,41 @@ function withoutUniqueItems(meta) {
|
|
|
682
1036
|
const maxKeys = meta.get("expect.maxKeys");
|
|
683
1037
|
if (maxKeys !== void 0) schema.maxProperties = require_user_text.boundOf(maxKeys, "count");
|
|
684
1038
|
}
|
|
685
|
-
/** `
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
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;
|
|
692
1074
|
}
|
|
693
1075
|
/** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
|
|
694
1076
|
if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
|
|
@@ -742,7 +1124,7 @@ const UPPER_BOUNDS = new Set([
|
|
|
742
1124
|
applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
|
|
743
1125
|
continue;
|
|
744
1126
|
}
|
|
745
|
-
if (member.const !== void 0) continue;
|
|
1127
|
+
if (member.const !== void 0 || member.enum !== void 0) continue;
|
|
746
1128
|
const type = member.type;
|
|
747
1129
|
const extra = { type };
|
|
748
1130
|
if (type === "array") {
|
|
@@ -785,7 +1167,14 @@ const UPPER_BOUNDS = new Set([
|
|
|
785
1167
|
*/ function fromJsonSchema(schema) {
|
|
786
1168
|
const defsSource = schema.$defs || schema.definitions || {};
|
|
787
1169
|
const resolved = /* @__PURE__ */ new Map();
|
|
788
|
-
const convert = (s) => {
|
|
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) => {
|
|
789
1178
|
if (!s || Object.keys(s).length === 0) return require_user_text.defineAnnotatedType().designType("any").$type;
|
|
790
1179
|
if (s.$ref) {
|
|
791
1180
|
const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
|
|
@@ -831,7 +1220,9 @@ const UPPER_BOUNDS = new Set([
|
|
|
831
1220
|
const handle = require_user_text.defineAnnotatedType("union");
|
|
832
1221
|
for (const t of s.type) handle.item(convert({
|
|
833
1222
|
...s,
|
|
834
|
-
type: t
|
|
1223
|
+
type: t,
|
|
1224
|
+
title: void 0,
|
|
1225
|
+
description: void 0
|
|
835
1226
|
}));
|
|
836
1227
|
return handle.$type;
|
|
837
1228
|
}
|
|
@@ -929,14 +1320,15 @@ const UPPER_BOUNDS = new Set([
|
|
|
929
1320
|
* to it are renamed.
|
|
930
1321
|
*
|
|
931
1322
|
* @param types - Array of annotated types, each with an `id`.
|
|
1323
|
+
* @param opts - {@link TJsonSchemaOptions}, for every schema.
|
|
932
1324
|
* @returns An object with `schemas` (keyed by id) and shared `$defs`.
|
|
933
|
-
*/ function mergeJsonSchemas(types) {
|
|
1325
|
+
*/ function mergeJsonSchemas(types, opts) {
|
|
934
1326
|
const mergedDefs = {};
|
|
935
1327
|
const schemas = {};
|
|
936
1328
|
for (const type of types) {
|
|
937
1329
|
const name = type.id;
|
|
938
1330
|
if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
|
|
939
|
-
const { $defs: defs, ...schema } = buildJsonSchema(type);
|
|
1331
|
+
const { $defs: defs, ...schema } = buildJsonSchema(type, opts);
|
|
940
1332
|
if (!defs) {
|
|
941
1333
|
schemas[name] = schema;
|
|
942
1334
|
continue;
|
|
@@ -1185,12 +1577,13 @@ function isPlainObject(value) {
|
|
|
1185
1577
|
/**
|
|
1186
1578
|
* The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
|
|
1187
1579
|
* a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
|
|
1188
|
-
* (`static toJsonSchema()`)
|
|
1189
|
-
|
|
1580
|
+
* (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
|
|
1581
|
+
* of a type).
|
|
1582
|
+
*/ function lazyJsonSchema(type, opts) {
|
|
1190
1583
|
const known = lazy.get(type);
|
|
1191
1584
|
const writes = require_user_text.metadataWriteCount();
|
|
1192
1585
|
if (known?.writes === writes) return known.schema;
|
|
1193
|
-
const schema = buildJsonSchema(type);
|
|
1586
|
+
const schema = buildJsonSchema(type, opts);
|
|
1194
1587
|
lazy.set(type, {
|
|
1195
1588
|
writes,
|
|
1196
1589
|
schema
|
|
@@ -1202,14 +1595,15 @@ function isPlainObject(value) {
|
|
|
1202
1595
|
* The JSON schema of `type` (`jsonSchema: 'bundle'`): the
|
|
1203
1596
|
* bundled `literal` while the modules whose blocks applied are exactly those the build accounted
|
|
1204
1597
|
* (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
|
|
1205
|
-
* metadata writes are not seen (as in 0.1.110). Called by generated code
|
|
1206
|
-
|
|
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) {
|
|
1207
1601
|
const applied = require_user_text.appliedBlockModules();
|
|
1208
1602
|
const known = bundled.get(type);
|
|
1209
1603
|
if (known?.size === applied.size) return known.schema;
|
|
1210
1604
|
const accounted = new Set(modules);
|
|
1211
1605
|
const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
|
|
1212
|
-
const schema = same ? literal() : buildJsonSchema(type);
|
|
1606
|
+
const schema = same ? literal() : buildJsonSchema(type, opts);
|
|
1213
1607
|
bundled.set(type, {
|
|
1214
1608
|
size: applied.size,
|
|
1215
1609
|
schema,
|
|
@@ -1352,7 +1746,7 @@ function isPlainObject(value) {
|
|
|
1352
1746
|
|
|
1353
1747
|
//#endregion
|
|
1354
1748
|
//#region packages/typescript/src/runtime/serialize.ts
|
|
1355
|
-
function _define_property(obj, key, value) {
|
|
1749
|
+
function _define_property$1(obj, key, value) {
|
|
1356
1750
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
1357
1751
|
value,
|
|
1358
1752
|
enumerable: true,
|
|
@@ -1424,17 +1818,17 @@ function _define_property(obj, key, value) {
|
|
|
1424
1818
|
return id;
|
|
1425
1819
|
}
|
|
1426
1820
|
constructor() {
|
|
1427
|
-
_define_property(this, "own", /* @__PURE__ */ new Map());
|
|
1821
|
+
_define_property$1(this, "own", /* @__PURE__ */ new Map());
|
|
1428
1822
|
/**
|
|
1429
1823
|
* The nodes without an id met more than once (see `indexPayload`): serialized once, with a
|
|
1430
1824
|
* payload id, and referenced (`$ref`, `anon`) wherever else they are.
|
|
1431
|
-
*/ _define_property(this, "repeated", /* @__PURE__ */ new Set());
|
|
1432
|
-
_define_property(this, "firstKeys", /* @__PURE__ */ new Map());
|
|
1433
|
-
_define_property(this, "identities", /* @__PURE__ */ new WeakMap());
|
|
1434
|
-
_define_property(this, "nextId", 0);
|
|
1435
|
-
/** Payload ids by type def (see {@link keyOf}). */ _define_property(this, "keys", /* @__PURE__ */ new WeakMap());
|
|
1436
|
-
/** The payload ids given so far. */ _define_property(this, "taken", /* @__PURE__ */ new Set());
|
|
1437
|
-
/** The `cut` payload of defs (see `indexPayload`). */ _define_property(this, "cutKeys", /* @__PURE__ */ new WeakMap());
|
|
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());
|
|
1438
1832
|
}
|
|
1439
1833
|
};
|
|
1440
1834
|
/**
|
|
@@ -1891,6 +2285,235 @@ function* deserializeTypeDef(t, resolved) {
|
|
|
1891
2285
|
}
|
|
1892
2286
|
}
|
|
1893
2287
|
|
|
2288
|
+
//#endregion
|
|
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
|
+
|
|
1894
2517
|
//#endregion
|
|
1895
2518
|
exports.$ak = require_user_text.$ak;
|
|
1896
2519
|
exports.$alias = require_user_text.$alias;
|
|
@@ -1934,11 +2557,14 @@ exports.localizeErrors = require_user_text.localizeErrors;
|
|
|
1934
2557
|
exports.mergeJsonSchemas = mergeJsonSchemas;
|
|
1935
2558
|
exports.messagesTranslator = require_user_text.messagesTranslator;
|
|
1936
2559
|
exports.metaEmpty = require_user_text.metaEmpty;
|
|
2560
|
+
exports.normalizeForType = normalizeForType;
|
|
1937
2561
|
exports.pendingStatements = require_user_text.pendingStatements;
|
|
1938
2562
|
exports.registerCompiledCheck = require_user_text.registerCompiledCheck;
|
|
1939
2563
|
exports.registerUserText = require_user_text.registerUserText;
|
|
1940
2564
|
exports.serializeAnnotatedType = serializeAnnotatedType;
|
|
1941
2565
|
exports.throwFeatureDisabled = throwFeatureDisabled;
|
|
2566
|
+
exports.translateServed = translateServed;
|
|
2567
|
+
exports.unionDiscriminator = require_user_text.unionDiscriminator;
|
|
1942
2568
|
exports.userTextKeys = require_user_text.userTextKeys;
|
|
1943
2569
|
exports.userTextOf = require_user_text.userTextOf;
|
|
1944
2570
|
exports.watchLayer = require_user_text.watchLayer;
|