@alexify/metaschema 1.0.0 → 3.0.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +551 -1
  2. package/README.md +235 -34
  3. package/SECURITY.md +32 -11
  4. package/index.d.ts +798 -23
  5. package/package.json +30 -6
  6. package/src/codec.js +490 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +512 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +141 -0
  12. package/src/errors.js +10 -1
  13. package/src/generators/index.d.ts +29 -0
  14. package/src/generators/index.js +90 -0
  15. package/src/generators/jsonschema.js +535 -0
  16. package/src/generators/typescript.js +237 -0
  17. package/src/index.js +1 -3
  18. package/src/issues.js +291 -0
  19. package/src/kinds.js +9 -12
  20. package/src/lint.js +98 -0
  21. package/src/locales/en.d.ts +5 -0
  22. package/src/locales/en.js +66 -0
  23. package/src/locales/uk.d.ts +5 -0
  24. package/src/locales/uk.js +62 -0
  25. package/src/metadata.js +65 -119
  26. package/src/metautil.js +8 -1
  27. package/src/model.js +31 -20
  28. package/src/preprocessor.js +45 -27
  29. package/src/prototypes/abstract.js +101 -51
  30. package/src/prototypes/collections.js +106 -41
  31. package/src/prototypes/json.js +9 -5
  32. package/src/prototypes/reference.js +91 -20
  33. package/src/prototypes/scalars.js +124 -16
  34. package/src/prototypes/schema.js +31 -6
  35. package/src/prototypes/tuple.js +57 -29
  36. package/src/prototypes/union.js +139 -0
  37. package/src/result.js +115 -0
  38. package/src/rules.js +185 -0
  39. package/src/runtime/browser.js +2 -2
  40. package/src/runtime/node.js +4 -2
  41. package/src/schema.js +181 -68
  42. package/src/struct.js +101 -33
  43. package/src/types.js +14 -14
  44. package/src/util.js +41 -50
@@ -0,0 +1,512 @@
1
+ // The emitters: one per built-in prototype, each rendering as straight-line
2
+ // code the check its `compile()` closes over, so a compiled schema records
3
+ // exactly the issues of the closure backend, in the same order, with the
4
+ // same paths and params. What is not inlined (a reference, a custom type, a
5
+ // validate function, the unknown-keys scan) is the closure backend's own
6
+ // function, called through the scope.
7
+ //
8
+ // Generated code names three things: `v` the value, `c` the context and `k`
9
+ // the key the root was called with. Every other identifier is fresh.
10
+ const { ENUM_SET_SIZE } = require('../util.js');
11
+ const { issues, runValidate } = require('../issues.js');
12
+ const { codePoints, lengthOf, ruleNames } = require('../rules.js');
13
+ const { STRUCT, isStruct } = require('../struct.js');
14
+ const scalars = require('../prototypes/scalars.js');
15
+ const collections = require('../prototypes/collections.js');
16
+ const { schema } = require('../prototypes/schema.js');
17
+ const { tuple } = require('../prototypes/tuple.js');
18
+ const { union, nameOf, tableOf } = require('../prototypes/union.js');
19
+ const { json } = require('../prototypes/json.js');
20
+ const { prop, quote, literal } = require('./code.js');
21
+
22
+ // The key of the field under check, as source: a quoted name, an index, a
23
+ // loop variable, or nothing at the root (`undefined` here, `void 0` there).
24
+ const keyOf = (key) => (key === undefined ? 'void 0' : key);
25
+
26
+ // The path of an issue is the stack of container keys plus the key of the
27
+ // field. The closure backend pushes a container's key before its children;
28
+ // here the keys since the last real push are known at generation time
29
+ // (`prefix`) and pushed only around a statement that records or calls out,
30
+ // so a valid value never touches the path.
31
+ const located = (keys, statement) => {
32
+ const { length } = keys;
33
+ if (length === 0) return statement;
34
+ const pop = length === 1 ? 'c.path.pop();' : `c.path.length -= ${length};`;
35
+ return `c.path.push(${keys.join(', ')}); ${statement} ${pop}`;
36
+ };
37
+
38
+ // A statement that may record, with its path, then the error limit: past it
39
+ // everything stops, up to the nearest union branch or the root.
40
+ const record = (state, statement, extra = []) => {
41
+ const keys = extra.length === 0 ? state.prefix : state.prefix.concat(extra);
42
+ state.code.push(`${located(keys, statement)} if (c.count >= c.limit) break ${state.label};`);
43
+ };
44
+
45
+ // The state under a container: its key joins the prefix of its children.
46
+ const inside = (state, key) =>
47
+ key === undefined ? state : { ...state, prefix: [...state.prefix, key] };
48
+
49
+ const issue = (state, name, args) => `${state.code.ref(issues)}.${name}(c, ${args});`;
50
+
51
+ const typeIssue = (state, expected, x, key) =>
52
+ issue(state, 'type', `${quote(expected)}, ${x}, ${keyOf(key)}`);
53
+
54
+ const notObject = (x) => `${x} === null || typeof ${x} !== "object" || Array.isArray(${x})`;
55
+
56
+ // The conditions of the bounds a field has.
57
+ const outside = (state, x, min, max) => {
58
+ const parts = [];
59
+ if (min !== undefined) parts.push(`${x} < ${state.code.value(min)}`);
60
+ if (max !== undefined) parts.push(`${x} > ${state.code.value(max)}`);
61
+ return parts.join(' || ');
62
+ };
63
+
64
+ const emitLength = (type, x, key, state) => {
65
+ const { code } = state;
66
+ const { min, max } = type.length;
67
+ if (min === undefined && max === undefined) return;
68
+ const n = code.name('n');
69
+ let measure = `${code.ref(lengthOf)}(${x})`;
70
+ if (type.scalar === 'string') {
71
+ measure = type.unicode === true ? `${code.ref(codePoints)}(${x})` : `${x}.length`;
72
+ }
73
+ code.push(`const ${n} = ${measure};`);
74
+ code.push(`if (${outside(state, n, min, max)}) {`);
75
+ const bounds = `${code.value(min)}, ${code.value(max)}, ${n}, ${keyOf(key)}`;
76
+ record(state, issue(state, 'length', bounds));
77
+ code.push('}');
78
+ };
79
+
80
+ const emitPattern = (type, x, key, state) => {
81
+ const { code } = state;
82
+ const { pattern } = type;
83
+ code.push(`if (!${code.ref(pattern)}.test(${x})) {`);
84
+ record(state, issue(state, 'pattern', `${quote(pattern.source)}, ${keyOf(key)}`));
85
+ code.push('}');
86
+ };
87
+
88
+ const emitRange = (type, x, key, state) => {
89
+ const { code } = state;
90
+ const { min, max } = type;
91
+ code.push(`if (${outside(state, x, min, max)}) {`);
92
+ const bounds = `${code.value(min)}, ${code.value(max)}, ${x}, ${keyOf(key)}`;
93
+ record(state, issue(state, 'range', bounds));
94
+ code.push('}');
95
+ };
96
+
97
+ const RULES = Object.assign(Object.create(null), {
98
+ length: emitLength,
99
+ pattern: emitPattern,
100
+ range: emitRange,
101
+ });
102
+
103
+ // The rules of a field in the order the closure backend runs them.
104
+ const rulesOf = (type) => {
105
+ const names = ruleNames(type);
106
+ const list = [];
107
+ for (let index = 0; index < names.length; index += 1) list.push(RULES[names[index]]);
108
+ return list;
109
+ };
110
+
111
+ // The rules, then the validate function on a value that passed them.
112
+ const emitTail = (type, x, key, state, rules) => {
113
+ const { code } = state;
114
+ const { validate } = type;
115
+ const guarded = validate && rules.length > 0;
116
+ const before = guarded ? code.name('b') : '';
117
+ if (guarded) code.push(`const ${before} = c.count;`);
118
+ for (const rule of rules) rule(type, x, key, state);
119
+ if (!validate) return;
120
+ if (guarded) code.push(`if (c.count === ${before}) {`);
121
+ const call = `${code.ref(runValidate)}(${code.ref(type)}, ${code.ref(validate)}, ${x}, c);`;
122
+ record(state, call, key === undefined ? [] : [key]);
123
+ if (guarded) code.push('}');
124
+ };
125
+
126
+ // A type check as `if (fails) { issue } else { body; rules; validate }`: the
127
+ // rules and the validate function run only on a value of the type, and
128
+ // after a body (the elements, the fields) only when it recorded nothing.
129
+ const typed = (type, x, key, state, fails, failure, body) => {
130
+ const { code } = state;
131
+ code.push(`if (${fails}) {`);
132
+ record(state, failure);
133
+ const rules = type === null ? [] : rulesOf(type);
134
+ const tail = type !== null && (rules.length > 0 || type.validate);
135
+ if (body === undefined && !tail) {
136
+ code.push('}');
137
+ return;
138
+ }
139
+ code.push('} else {');
140
+ const before = body !== undefined && tail ? code.name('b') : '';
141
+ if (before) code.push(`const ${before} = c.count;`);
142
+ if (body !== undefined) body();
143
+ if (before) code.push(`if (c.count === ${before}) {`);
144
+ if (tail) emitTail(type, x, key, state, rules);
145
+ if (before) code.push('}');
146
+ code.push('}');
147
+ };
148
+
149
+ const emitScalar = (type, x, key, state) => {
150
+ const { scalar } = type;
151
+ typed(type, x, key, state, `typeof ${x} !== ${quote(scalar)}`, typeIssue(state, scalar, x, key));
152
+ };
153
+
154
+ const emitInteger = (type, x, key, state) =>
155
+ typed(type, x, key, state, `!Number.isInteger(${x})`, typeIssue(state, 'integer', x, key));
156
+
157
+ const emitDate = (type, x, key, state) => {
158
+ const fails = `!(${x}?.constructor?.name === "Date" && !Number.isNaN(${x}.getTime()))`;
159
+ typed(type, x, key, state, fails, typeIssue(state, 'date', x, key));
160
+ };
161
+
162
+ const emitNull = (type, x, key, state) =>
163
+ typed(type, x, key, state, `${x} !== null`, typeIssue(state, 'null', x, key));
164
+
165
+ const emitJson = (type, x, key, state) => {
166
+ const fails = `${x} === null || typeof ${x} !== "object"`;
167
+ typed(type, x, key, state, fails, typeIssue(state, 'object', x, key));
168
+ };
169
+
170
+ // Any value at all; only a validate function can say otherwise.
171
+ const emitAny = (type, x, key, state) => emitTail(type, x, key, state, []);
172
+
173
+ const emitEnum = (type, x, key, state) => {
174
+ const { code } = state;
175
+ const values = type.enum;
176
+ const { length } = values;
177
+ let fails;
178
+ if (length > ENUM_SET_SIZE) {
179
+ fails = `!${code.ref(new Set(values))}.has(${x})`;
180
+ } else {
181
+ // A chain of comparisons with the literals, unless a value has none
182
+ // (NaN, an object): then the list itself, as the closure backend scans it.
183
+ let chain = '';
184
+ for (let index = 0; index < length; index += 1) {
185
+ const text = literal(values[index]);
186
+ if (text === undefined) {
187
+ chain = null;
188
+ break;
189
+ }
190
+ chain += `${index === 0 ? '' : ' && '}${x} !== ${text}`;
191
+ }
192
+ fails = chain === null ? `!${code.ref(values)}.includes(${x})` : chain;
193
+ }
194
+ const failure = issue(state, 'enum', `${code.ref(values)}, ${keyOf(key)}`);
195
+ typed(type, x, key, state, fails, failure);
196
+ };
197
+
198
+ const emitObject = (type, x, key, state) => {
199
+ const { code } = state;
200
+ const failure = typeIssue(state, type.type, x, key);
201
+ typed(type, x, key, state, notObject(x), failure, () => {
202
+ const children = inside(state, key);
203
+ const count = code.name('t');
204
+ const name = code.name('n');
205
+ const label = code.name('o');
206
+ code.push(`let ${count} = 0;`);
207
+ code.push(`${label}: for (const ${name} in ${x}) {`);
208
+ code.push(`if (!Object.hasOwn(${x}, ${name})) continue;`);
209
+ code.push(`${count} += 1;`);
210
+ if (type.key === 'string') {
211
+ const item = code.name('x');
212
+ code.push(`const ${item} = ${x}[${name}];`);
213
+ emitField(type.value, item, name, children);
214
+ } else {
215
+ // A key of an object is a string, so any other key type fails on the
216
+ // first key, as it does in the closure backend.
217
+ record(children, issue(state, 'key', `${quote(type.key)}, ${name}`));
218
+ code.push(`break ${label};`);
219
+ }
220
+ code.push('}');
221
+ if (!type.required) return;
222
+ code.push(`if (${count} === 0) {`);
223
+ record(state, issue(state, 'required', keyOf(key)));
224
+ code.push('}');
225
+ });
226
+ };
227
+
228
+ const emitMap = (type, x, key, state) => {
229
+ const { code } = state;
230
+ const failure = typeIssue(state, type.type, x, key);
231
+ typed(type, x, key, state, `${x}?.constructor?.name !== "Map"`, failure, () => {
232
+ if (type.required) {
233
+ code.push(`if (${x}.size === 0) {`);
234
+ record(state, issue(state, 'required', keyOf(key)));
235
+ code.push('} else {');
236
+ } else {
237
+ code.push(`if (${x}.size !== 0) {`);
238
+ }
239
+ const children = inside(state, key);
240
+ const label = code.name('m');
241
+ const pair = code.name('p');
242
+ const name = code.name('n');
243
+ const item = code.name('x');
244
+ code.push(`${label}: for (const ${pair} of ${x}) {`);
245
+ code.push(`const ${name} = ${pair}[0];`);
246
+ code.push(`if (typeof ${name} !== ${quote(type.key)}) {`);
247
+ record(children, issue(state, 'key', `${quote(type.key)}, ${name}`));
248
+ code.push(`break ${label};`);
249
+ code.push('}');
250
+ code.push(`const ${item} = ${pair}[1];`);
251
+ emitField(type.value, item, name, children);
252
+ code.push('}');
253
+ code.push('}');
254
+ });
255
+ };
256
+
257
+ // An array by index, a Set through its iterator; only the type test differs.
258
+ const emitList = (type, x, key, state) => {
259
+ const { code } = state;
260
+ const set = type.isInstance === collections.set.isInstance;
261
+ const fails = set ? `${x}?.constructor?.name !== "Set"` : `!Array.isArray(${x})`;
262
+ typed(type, x, key, state, fails, typeIssue(state, type.type, x, key), () => {
263
+ const children = inside(state, key);
264
+ const index = code.name('i');
265
+ const item = code.name('x');
266
+ if (set) {
267
+ code.push(`let ${index} = 0;`);
268
+ code.push(`for (const ${item} of ${x}) {`);
269
+ emitField(type.value, item, index, children);
270
+ code.push(`${index} += 1;`);
271
+ } else {
272
+ code.push(`for (let ${index} = 0; ${index} < ${x}.length; ${index} += 1) {`);
273
+ code.push(`const ${item} = ${x}[${index}];`);
274
+ emitField(type.value, item, index, children);
275
+ }
276
+ code.push('}');
277
+ });
278
+ };
279
+
280
+ const emitTuple = (type, x, key, state) => {
281
+ const { code } = state;
282
+ const elements = type.value;
283
+ const { length } = elements;
284
+ typed(type, x, key, state, `!Array.isArray(${x})`, typeIssue(state, type.type, x, key), () => {
285
+ code.push(`if (${x}.length > ${length}) {`);
286
+ record(state, issue(state, 'length', `void 0, ${length}, ${x}.length, ${keyOf(key)}`));
287
+ code.push('} else {');
288
+ const children = inside(state, key);
289
+ for (let index = 0; index < length; index += 1) {
290
+ const item = code.name('x');
291
+ code.push(`const ${item} = ${x}[${index}];`);
292
+ emitField(elements[index], item, String(index), children);
293
+ }
294
+ code.push('}');
295
+ });
296
+ };
297
+
298
+ // The fields of a struct over `x`: a keyed load per field, `Object.hasOwn`
299
+ // only to tell a missing required key from one set to undefined (first for a
300
+ // field named after a member of Object.prototype), and the unknown-keys scan
301
+ // only when the value has more keys than the plan found.
302
+ const emitStruct = (fields, x, key, state) => {
303
+ const { code } = state;
304
+ const { plan, known } = fields[STRUCT];
305
+ const children = inside(state, key);
306
+ const found = code.name('f');
307
+ code.push(`let ${found} = 0;`);
308
+ for (const entry of plan) {
309
+ const { required, own } = entry;
310
+ const name = quote(entry.key);
311
+ const item = code.name('x');
312
+ code.push(`const ${item} = ${prop(x, entry.key)};`);
313
+ if (required) {
314
+ const missing = own ? '' : `${item} === undefined && `;
315
+ code.push(`if (${missing}!Object.hasOwn(${x}, ${name})) {`);
316
+ record(children, issue(state, 'required', name));
317
+ code.push('} else {');
318
+ } else {
319
+ const present = own ? ` && Object.hasOwn(${x}, ${name})` : '';
320
+ code.push(`if (${item} !== undefined${present}) {`);
321
+ }
322
+ code.push(`${found} += 1;`);
323
+ emitField(entry.type, item, name, children);
324
+ code.push('}');
325
+ }
326
+ const total = code.name('t');
327
+ const name = code.name('n');
328
+ const unexpected = code.name('u');
329
+ code.push('if (c.unknown === "reject") {');
330
+ code.push(`let ${total} = 0;`);
331
+ code.push(`for (const ${name} in ${x}) ${total} += 1;`);
332
+ code.push(`if (${total} !== ${found}) {`);
333
+ // The scan of struct.js with the known keys as cases: a key for...in
334
+ // yields is an internalized string, so a case is a pointer comparison
335
+ // where a dictionary lookup would hash it.
336
+ let cases = '';
337
+ for (const field in known) cases += `case ${quote(field)}: `;
338
+ code.push(`let ${unexpected} = null;`);
339
+ code.push(`for (const ${name} in ${x}) {`);
340
+ if (cases !== '') code.push(`switch (${name}) { ${cases}continue; }`);
341
+ code.push(`if (!Object.hasOwn(${x}, ${name})) continue;`);
342
+ code.push(`if (${unexpected} === null) ${unexpected} = [];`);
343
+ code.push(`${unexpected}.push(${name});`);
344
+ code.push('}');
345
+ code.push(`if (${unexpected} !== null) {`);
346
+ record(children, issue(state, 'unexpected', unexpected));
347
+ code.push('}');
348
+ code.push('}');
349
+ code.push('}');
350
+ };
351
+
352
+ // A nested struct: its fields, then the validate function it carries. A
353
+ // Schema instance of one type used as a field is that type (its validate, if
354
+ // any, is the field's own: a schema of one type has no schema-level one).
355
+ const emitSchema = (type, x, key, state) => {
356
+ const fields = type.schema;
357
+ if (!isStruct(fields)) {
358
+ emitField(fields, x, key, state);
359
+ return;
360
+ }
361
+ const body = () => emitStruct(fields, x, key, state);
362
+ typed(type, x, key, state, notObject(x), typeIssue(state, 'object', x, key), body);
363
+ };
364
+
365
+ // Without a discriminator the branches are tried in order and what a failed
366
+ // branch recorded is dropped, so the error limit inside a branch stops that
367
+ // branch only. With one, the branch is picked by the value of that field.
368
+ const emitUnion = (type, x, key, state) => {
369
+ const { code } = state;
370
+ const { discriminator } = type;
371
+ const branches = type.union;
372
+ if (discriminator === undefined) {
373
+ const before = code.name('b');
374
+ const pending = code.name('a');
375
+ const label = code.name('u');
376
+ code.push(`const ${before} = c.count;`);
377
+ // The validators a failed branch set aside in an async check go with its
378
+ // issues, as in the closure backend.
379
+ code.push(`const ${pending} = c.async === null ? 0 : c.async.length;`);
380
+ code.push(`${label}: {`);
381
+ for (const branch of branches) {
382
+ const own = code.name('u');
383
+ code.push(`${own}: {`);
384
+ emitField(branch, x, key, { ...state, label: own });
385
+ code.push('}');
386
+ code.push(`if (c.count === ${before}) break ${label};`);
387
+ code.push(`c.issues.length = ${before}; c.count = ${before};`);
388
+ code.push(`if (c.async !== null) c.async.length = ${pending};`);
389
+ }
390
+ const names = [];
391
+ for (let index = 0; index < branches.length; index += 1) names.push(nameOf(branches[index]));
392
+ record(state, issue(state, 'union', `${code.ref(names)}, void 0, ${keyOf(key)}`));
393
+ code.push('}');
394
+ if (!type.validate) return;
395
+ code.push(`if (c.count === ${before}) {`);
396
+ emitTail(type, x, key, state, []);
397
+ code.push('}');
398
+ return;
399
+ }
400
+ const fails = `${x} === null || typeof ${x} !== "object"`;
401
+ typed(type, x, key, state, fails, typeIssue(state, 'object', x, key), () => {
402
+ // The literals of the discriminator values, by branch; a value with no
403
+ // literal (NaN, an object) selects its branch through the table of value
404
+ // to branch index the closure backend uses.
405
+ const expected = [];
406
+ const cases = [];
407
+ let direct = true;
408
+ for (let index = 0; index < branches.length; index += 1) {
409
+ const values = branches[index].schema[discriminator].enum;
410
+ const texts = [];
411
+ for (let at = 0; at < values.length; at += 1) {
412
+ const text = literal(values[at]);
413
+ if (text === undefined) direct = false;
414
+ expected.push(values[at]);
415
+ texts.push(text);
416
+ }
417
+ cases.push(texts);
418
+ }
419
+ const subject = prop(x, discriminator);
420
+ code.push(`switch (${direct ? subject : `${code.ref(tableOf(type))}.get(${subject})`}) {`);
421
+ for (let index = 0; index < branches.length; index += 1) {
422
+ if (direct) {
423
+ const texts = cases[index];
424
+ for (let at = 0; at < texts.length; at += 1) code.push(`case ${texts[at]}:`);
425
+ } else {
426
+ code.push(`case ${index}:`);
427
+ }
428
+ code.push('{');
429
+ emitField(branches[index], x, key, state);
430
+ code.push('break;');
431
+ code.push('}');
432
+ }
433
+ code.push('default: {');
434
+ const name = quote(discriminator);
435
+ record(inside(state, key), issue(state, 'union', `${code.ref(expected)}, ${name}, ${name}`));
436
+ code.push('}');
437
+ code.push('}');
438
+ });
439
+ };
440
+
441
+ const EMITTERS = new Map([
442
+ [scalars.string.compile, emitScalar],
443
+ [scalars.integer.compile, emitInteger],
444
+ [scalars.date.compile, emitDate],
445
+ [scalars.null.compile, emitNull],
446
+ [scalars.any.compile, emitAny],
447
+ [scalars.enum.compile, emitEnum],
448
+ [json.compile, emitJson],
449
+ [collections.object.compile, emitObject],
450
+ [collections.map.compile, emitMap],
451
+ [collections.array.compile, emitList],
452
+ [tuple.compile, emitTuple],
453
+ [union.compile, emitUnion],
454
+ [schema.compile, emitSchema],
455
+ ]);
456
+
457
+ // The check of one field over the local `x`. A built-in prototype is
458
+ // inlined by the emitter of its `compile`; a reference, a custom type or a
459
+ // prototype with a compile of its own is its closure, which does everything
460
+ // (rules, validate and nullable included). An optional field skips null and
461
+ // undefined, a nullable one null, before anything else.
462
+ const emitField = (type, x, key, state) => {
463
+ const emitter = EMITTERS.get(type.compile);
464
+ if (emitter === undefined) {
465
+ record(state, `${state.code.ref(type.check)}(${x}, c, ${keyOf(key)});`);
466
+ return;
467
+ }
468
+ const { code } = state;
469
+ const { required } = type;
470
+ let guard = null;
471
+ if (!required) guard = `${x} != null`;
472
+ else if (type.nullable === true) guard = `${x} !== null`;
473
+ if (guard !== null) code.push(`if (${guard}) {`);
474
+ emitter(type, x, key, state);
475
+ if (guard !== null) code.push('}');
476
+ };
477
+
478
+ // The body of a schema's check, `(v, c, k)`: the key the root was called
479
+ // with (through a reference) is pushed on the path at entry, so the root
480
+ // records with no key of its own and everything under it carries `k`; the
481
+ // schema-level validate runs last, on a value whose fields all passed.
482
+ const emitRoot = (target, code) => {
483
+ const { fields, options } = target;
484
+ const { validate } = options;
485
+ const state = { code, label: 'r', prefix: [] };
486
+ const before = validate ? code.name('b') : '';
487
+ if (validate) code.push(`const ${before} = c.count;`);
488
+ code.push('if (k !== undefined) c.path.push(k);');
489
+ code.push('r: {');
490
+ if (isStruct(fields)) {
491
+ const body = () => emitStruct(fields, 'v', undefined, state);
492
+ typed(
493
+ null,
494
+ 'v',
495
+ undefined,
496
+ state,
497
+ notObject('v'),
498
+ typeIssue(state, 'object', 'v', undefined),
499
+ body,
500
+ );
501
+ } else {
502
+ emitField(fields, 'v', undefined, state);
503
+ }
504
+ code.push('}');
505
+ if (validate) {
506
+ const call = `${code.ref(runValidate)}(${code.ref(target)}, ${code.ref(validate)}, v, c);`;
507
+ code.push(`if (c.count === ${before}) ${call}`);
508
+ }
509
+ code.push('if (k !== undefined) c.path.pop();');
510
+ };
511
+
512
+ module.exports = { emitRoot };
@@ -0,0 +1,38 @@
1
+ import type { Model, Schema, SchemaDefinitionError } from '../../index.js';
2
+
3
+ export interface CompileOptions {
4
+ // 'auto' (the default) generates the check where the environment allows
5
+ // code generation from strings and keeps the closure backend silently where
6
+ // it does not; true throws `SchemaDefinitionError` with the code
7
+ // `ERR_NO_EVAL` instead of falling back; false never generates code.
8
+ jit?: 'auto' | boolean;
9
+ // Told of every schema the default mode could not compile, with the
10
+ // `ERR_JIT_BUILD` error (the error of the generator as its `cause`); the
11
+ // schema keeps its closures.
12
+ onFallback?: (schema: Schema, error: SchemaDefinitionError) => void;
13
+ }
14
+
15
+ export interface Compiled {
16
+ // Whether the check runs generated code now; false in the fallback, where
17
+ // the closure backend is left as it is.
18
+ accelerated: boolean;
19
+ // What stopped the first check that could not be generated (`ERR_JIT_BUILD`,
20
+ // the generator's error as its `cause`); absent where the environment allows
21
+ // no code generation at all, and after `{ jit: false }`.
22
+ error?: SchemaDefinitionError;
23
+ }
24
+
25
+ // Replaces the check of a schema, or of every entity of a model, with the
26
+ // generated one. The issues are the ones the closure backend records, in the
27
+ // same order. A target that is neither is a `TypeError`. With `jit: true` a
28
+ // check that cannot be generated throws `ERR_JIT_BUILD` and nothing is
29
+ // installed; `{ jit: false }` puts the closures back.
30
+ export function compile(target: Schema | Model, options?: CompileOptions): Compiled;
31
+
32
+ // Compiles every schema built from now on with these options; a later call
33
+ // replaces them, `{ jit: false }` stops it. A schema built before the call is
34
+ // not touched: pass it to `compile`.
35
+ export function register(options?: CompileOptions): void;
36
+
37
+ // Whether this environment allows code generation from strings; probed once.
38
+ export function canEval(): boolean;