@alexify/metaschema 2.0.0 → 3.1.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 (51) hide show
  1. package/CHANGELOG.md +443 -1
  2. package/README.md +124 -12
  3. package/SECURITY.md +27 -8
  4. package/index.d.ts +537 -84
  5. package/package.json +25 -6
  6. package/src/codec.js +544 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +540 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +68 -19
  12. package/src/errors.js +19 -1
  13. package/src/generators/fromjsonschema.js +520 -0
  14. package/src/generators/index.d.ts +46 -0
  15. package/src/generators/index.js +95 -0
  16. package/src/generators/jsonschema.js +535 -0
  17. package/src/generators/typescript.js +237 -0
  18. package/src/index.js +0 -2
  19. package/src/issues.js +117 -22
  20. package/src/kinds.js +9 -12
  21. package/src/lint.js +31 -14
  22. package/src/locales/en.js +10 -2
  23. package/src/locales/uk.js +7 -2
  24. package/src/metadata.js +41 -44
  25. package/src/metautil.js +8 -1
  26. package/src/model/data.js +122 -0
  27. package/src/model/diff.js +438 -0
  28. package/src/model/index.d.ts +56 -0
  29. package/src/model/index.js +42 -0
  30. package/src/model/merge.js +254 -0
  31. package/src/model/pattern.js +322 -0
  32. package/src/model/restore.js +226 -0
  33. package/src/model/sample.js +394 -0
  34. package/src/model.js +18 -15
  35. package/src/preprocessor.js +9 -11
  36. package/src/prototypes/abstract.js +14 -1
  37. package/src/prototypes/collections.js +20 -3
  38. package/src/prototypes/reference.js +17 -3
  39. package/src/prototypes/scalars.js +1 -3
  40. package/src/prototypes/schema.js +15 -2
  41. package/src/prototypes/tuple.js +14 -9
  42. package/src/prototypes/union.js +57 -18
  43. package/src/result.js +5 -14
  44. package/src/rules.js +55 -26
  45. package/src/runtime/browser.js +2 -2
  46. package/src/runtime/node.js +4 -2
  47. package/src/schema.js +129 -101
  48. package/src/snapshot.js +111 -0
  49. package/src/struct.js +80 -23
  50. package/src/types.js +5 -11
  51. package/src/util.js +39 -0
@@ -0,0 +1,176 @@
1
+ // The `./compile` subpath: the JIT backend of validation. `compile(target)`
2
+ // renders the check of a schema (or of every entity of a model) into
3
+ // straight-line JavaScript over the plan the closure backend walks, builds it
4
+ // with `new Function` and installs it as the schema's check; the issues are
5
+ // the ones the closures record, in the same order. Where code generation
6
+ // from strings is not allowed (a Content Security Policy, Cloudflare Workers,
7
+ // `node --disallow-code-generation-from-strings`) the closures stay, silently
8
+ // in the default mode. Nothing happens on import.
9
+ const { hasBrand, RUN, HOOK } = require('../util.js');
10
+ const { Schema } = require('../schema.js');
11
+ const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
12
+ const { Code } = require('./code.js');
13
+ const { emitRoot } = require('./emit.js');
14
+
15
+ const invalidOptions = (reason) => new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
16
+
17
+ // The options of compile and register: the mode, and the function told of
18
+ // every schema the default mode could not compile.
19
+ const optionsOf = (options) => {
20
+ if (options === null || typeof options !== 'object') {
21
+ throw invalidOptions(`Compile options must be an object, got ${JSON.stringify(options)}`);
22
+ }
23
+ const { jit = 'auto', onFallback } = options;
24
+ if (jit !== 'auto' && jit !== true && jit !== false) {
25
+ const got = JSON.stringify(jit);
26
+ throw invalidOptions(`Compile option "jit" must be "auto", true or false, got ${got}`);
27
+ }
28
+ if (onFallback !== undefined && typeof onFallback !== 'function') {
29
+ throw invalidOptions('Compile option "onFallback" must be a function');
30
+ }
31
+ return { mode: jit, onFallback };
32
+ };
33
+
34
+ let evaluates = null;
35
+
36
+ // Whether this environment builds a function from source, probed once.
37
+ const canEval = () => {
38
+ if (evaluates === null) {
39
+ try {
40
+ // oxlint-disable-next-line no-new-func
41
+ evaluates = typeof new Function('') === 'function';
42
+ } catch {
43
+ evaluates = false;
44
+ }
45
+ }
46
+ return evaluates;
47
+ };
48
+
49
+ const noEval = () => {
50
+ const reason =
51
+ 'Code generation from strings is not allowed in this environment; ' +
52
+ 'jit: "auto" keeps the closure backend instead';
53
+ return new SchemaDefinitionError('ERR_NO_EVAL', reason);
54
+ };
55
+
56
+ // Whether a mode generates code here: never for false, where it can for
57
+ // 'auto', and for true only where it can, otherwise an error.
58
+ const accelerates = (mode) => {
59
+ if (mode === false) return false;
60
+ if (canEval()) return true;
61
+ if (mode === true) throw noEval();
62
+ return false;
63
+ };
64
+
65
+ // What went wrong when the check of a schema could not be generated: the
66
+ // error of the emitter or of `new Function` as the cause, under one code.
67
+ const failure = (target, error) => {
68
+ const reason = `The check of "${target.name}" could not be generated: ${error.message}`;
69
+ const wrapped = new SchemaDefinitionError('ERR_JIT_BUILD', reason);
70
+ wrapped.cause = error;
71
+ return wrapped;
72
+ };
73
+
74
+ const build = (target) => {
75
+ const code = new Code();
76
+ emitRoot(target, code);
77
+ // oxlint-disable-next-line no-new-func
78
+ const factory = new Function('scope', code.source(target.name));
79
+ return factory(code.values);
80
+ };
81
+
82
+ // The generated check, or ERR_JIT_BUILD: the JIT was demanded.
83
+ const generate = (target) => {
84
+ try {
85
+ return build(target);
86
+ } catch (error) {
87
+ throw failure(target, error);
88
+ }
89
+ };
90
+
91
+ // The check a schema was built with, kept when the generated one replaces it
92
+ // so that `{ jit: false }` can put it back.
93
+ const ORIGINAL = new WeakMap();
94
+
95
+ const replace = (target, run) => {
96
+ if (!ORIGINAL.has(target)) ORIGINAL.set(target, target[RUN]);
97
+ target[RUN] = run;
98
+ };
99
+
100
+ const restore = (target) => {
101
+ const run = ORIGINAL.get(target);
102
+ if (run !== undefined) target[RUN] = run;
103
+ };
104
+
105
+ // Replaces the check of a schema with the generated one; a failure to build
106
+ // it is a fallback, reported to `onFallback` and returned.
107
+ const install = (target, onFallback) => {
108
+ let run;
109
+ try {
110
+ run = build(target);
111
+ } catch (error) {
112
+ const wrapped = failure(target, error);
113
+ if (onFallback !== undefined) onFallback(target, wrapped);
114
+ return wrapped;
115
+ }
116
+ replace(target, run);
117
+ return undefined;
118
+ };
119
+
120
+ const schemasOf = (target) => {
121
+ if (hasBrand(target, 'Schema')) return [target];
122
+ if (!hasBrand(target, 'Model')) throw invalidTarget('A Schema or a Model is expected');
123
+ const schemas = [];
124
+ for (const schema of target.entities.values()) schemas.push(schema);
125
+ return schemas;
126
+ };
127
+
128
+ // `{ accelerated, error }`: whether the check of the schema (of every entity
129
+ // of the model) runs generated code now, and what stopped the first one that
130
+ // does not; false without an error where the environment allows no code
131
+ // generation and after `{ jit: false }`, which puts the closures back. When
132
+ // the JIT is demanded every check is built before any is installed, so an
133
+ // error leaves the model as it was.
134
+ const compile = (target, options = {}) => {
135
+ const { mode, onFallback } = optionsOf(options);
136
+ const schemas = schemasOf(target);
137
+ const { length } = schemas;
138
+ if (!accelerates(mode)) {
139
+ for (let index = 0; index < length; index += 1) restore(schemas[index]);
140
+ return { accelerated: false };
141
+ }
142
+ if (mode === true) {
143
+ const runs = [];
144
+ for (let index = 0; index < length; index += 1) runs.push(generate(schemas[index]));
145
+ for (let index = 0; index < length; index += 1) replace(schemas[index], runs[index]);
146
+ return { accelerated: true };
147
+ }
148
+ let error;
149
+ for (let index = 0; index < length; index += 1) {
150
+ const failed = install(schemas[index], onFallback);
151
+ if (failed !== undefined && error === undefined) error = failed;
152
+ }
153
+ return error === undefined ? { accelerated: true } : { accelerated: false, error };
154
+ };
155
+
156
+ // Compiles every schema built from now on, with these options; a later call
157
+ // replaces them, and `{ jit: false }` stops it. A schema built before the
158
+ // call is not touched. In the default mode `onFallback` is told of every
159
+ // schema that keeps its closures because its check could not be generated.
160
+ const register = (options = {}) => {
161
+ const { mode, onFallback } = optionsOf(options);
162
+ if (!accelerates(mode)) {
163
+ Schema[HOOK] = undefined;
164
+ return;
165
+ }
166
+ Schema[HOOK] =
167
+ mode === true
168
+ ? (schema) => {
169
+ replace(schema, generate(schema));
170
+ }
171
+ : (schema) => {
172
+ install(schema, onFallback);
173
+ };
174
+ };
175
+
176
+ module.exports = { compile, register, canEval };
package/src/context.js CHANGED
@@ -10,34 +10,64 @@ const { NONE } = require('./issues.js');
10
10
  // with the count on every field stays an integer comparison.
11
11
  const UNLIMITED = 2 ** 30 - 1;
12
12
 
13
+ const shown = (value) =>
14
+ typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
15
+
13
16
  const invalid = (name, expected, value) =>
14
- new TypeError(`${name} must be ${expected}, got ${JSON.stringify(value) ?? String(value)}`);
17
+ new TypeError(`${name} must be ${expected}, got ${shown(value)}`);
15
18
 
19
+ // A whole number of issues, or no limit at all.
16
20
  const maxErrorsOf = (maxErrors) => {
17
- const valid = typeof maxErrors === 'number' && maxErrors >= 1;
18
- if (!valid) throw invalid('maxErrors', 'a number of at least 1', maxErrors);
21
+ const valid = (Number.isInteger(maxErrors) || maxErrors === Infinity) && maxErrors >= 1;
22
+ if (!valid) throw invalid('maxErrors', 'an integer of at least 1', maxErrors);
19
23
  return Math.min(maxErrors, UNLIMITED);
20
24
  };
21
25
 
26
+ // How deep a value may nest through embedded references before the check
27
+ // gives up on it: a graph that deep is a `depth` issue, not a stack overflow.
28
+ const MAX_DEPTH = 128;
29
+
30
+ const maxDepthOf = (maxDepth) => {
31
+ if (!Number.isInteger(maxDepth) || maxDepth < 1) {
32
+ throw invalid('maxDepth', 'an integer of at least 1', maxDepth);
33
+ }
34
+ return maxDepth;
35
+ };
36
+
37
+ // A caller's locale table as a null-prototype copy, made once per table: the
38
+ // renderers are looked up by issue code, and a code a validator made up must
39
+ // find nothing on Object.prototype.
40
+ const TABLES = new WeakMap();
41
+
22
42
  const messagesOf = (messages) => {
23
- const isTable = messages !== null && typeof messages === 'object';
24
- if (!isTable && typeof messages !== 'function') {
43
+ if (typeof messages === 'function') return messages;
44
+ if (messages === null || typeof messages !== 'object') {
25
45
  throw invalid('messages', 'a locale table or a function', messages);
26
46
  }
27
- return messages;
47
+ if (Object.getPrototypeOf(messages) === null) return messages;
48
+ let table = TABLES.get(messages);
49
+ if (table === undefined) {
50
+ table = Object.assign(Object.create(null), messages);
51
+ TABLES.set(messages, table);
52
+ }
53
+ return table;
28
54
  };
29
55
 
30
- const unknownOf = (unknown) => {
31
- if (unknown !== 'reject' && unknown !== 'ignore') {
32
- throw invalid('unknown', '"reject" or "ignore"', unknown);
56
+ // `strip` is a policy of parse alone: the check behind it treats it as
57
+ // `ignore`, and the pass that builds the output drops the keys.
58
+ const unknownOf = (unknown, parsing) => {
59
+ if (unknown === 'reject' || unknown === 'ignore' || (parsing && unknown === 'strip')) {
60
+ return unknown;
33
61
  }
34
- return unknown;
62
+ throw invalid(
63
+ 'unknown',
64
+ parsing ? '"reject", "ignore" or "strip"' : '"reject" or "ignore"',
65
+ unknown,
66
+ );
35
67
  };
36
68
 
37
- const REFERENCES = ['kind', 'embed', 'id'];
38
-
39
69
  const referencesOf = (references) => {
40
- if (!REFERENCES.includes(references)) {
70
+ if (references !== 'kind' && references !== 'embed' && references !== 'id') {
41
71
  throw invalid('references', '"kind", "embed" or "id"', references);
42
72
  }
43
73
  return references;
@@ -59,11 +89,12 @@ const optionsOf = (options) => {
59
89
  // The options of a call, checked and written over the defaults. Kept out of
60
90
  // createContext so that the allocation stays small enough for V8 to inline
61
91
  // into Schema#check: a check without options is the common call.
62
- const configure = (context, options) => {
92
+ const configure = (context, options, parsing) => {
63
93
  optionsOf(options);
64
94
  if (options.maxErrors !== undefined) context.limit = maxErrorsOf(options.maxErrors);
95
+ if (options.maxDepth !== undefined) context.maxDepth = maxDepthOf(options.maxDepth);
65
96
  if (options.messages !== undefined) context.messages = messagesOf(options.messages);
66
- if (options.unknown !== undefined) context.unknown = unknownOf(options.unknown);
97
+ if (options.unknown !== undefined) context.unknown = unknownOf(options.unknown, parsing);
67
98
  if (options.references !== undefined) context.references = referencesOf(options.references);
68
99
  if (options.root !== undefined) context.root = rootOf(options.root);
69
100
  };
@@ -71,25 +102,43 @@ const configure = (context, options) => {
71
102
  // One object shape for every context: the keys are always present, in this
72
103
  // order, so the hot path sees a single hidden class. `unknown` is what the
73
104
  // schema being checked says (its unknown-keys policy); an option of the call
74
- // wins over it.
75
- const createContext = (options, name = '', unknown = 'reject') => {
105
+ // wins over it. `parsing` is set by parse, whose options accept `strip`.
106
+ const createContext = (options, name = '', unknown = 'reject', parsing = false) => {
76
107
  const context = {
77
108
  issues: NONE,
78
109
  count: 0,
79
110
  limit: UNLIMITED,
111
+ // How many embedded records the check is inside, and how many it may be.
112
+ depth: 0,
113
+ maxDepth: MAX_DEPTH,
80
114
  path: [],
81
115
  // The objects on the current path, created at the first object met so a
82
116
  // check over scalars never allocates it.
83
117
  seen: null,
118
+ // The value the check started from, when the schema can reach it again
119
+ // through a reference (Schema#check sets it): it joins `seen` when the
120
+ // first embedded record creates the set, so a check that embeds nothing
121
+ // never allocates it.
122
+ source: null,
84
123
  unknown,
85
124
  // How a reference is checked: by the kind of its target ('kind'), as
86
125
  // the record itself ('embed') or as its id ('id').
87
126
  references: 'kind',
88
127
  root: name,
89
128
  messages: en,
129
+ // The validators that returned a promise, in field order, settled after
130
+ // the walk by checkAsync and parseAsync; null in a synchronous check,
131
+ // where such a promise is an error.
132
+ async: null,
133
+ // The context parse tries the branches of a plain union in, made at the
134
+ // first such union of a pass and reused for the rest; null in a check.
135
+ scratch: null,
136
+ // Whether the check read a field from one of its aliases: the pass
137
+ // after it renames only when it did.
138
+ renamed: false,
90
139
  };
91
- if (options !== undefined) configure(context, options);
140
+ if (options !== undefined) configure(context, options, parsing);
92
141
  return context;
93
142
  };
94
143
 
95
- module.exports = { createContext, UNLIMITED };
144
+ module.exports = { createContext, UNLIMITED, MAX_DEPTH };
package/src/errors.js CHANGED
@@ -25,4 +25,22 @@ class SchemaDefinitionError extends TypeError {
25
25
 
26
26
  SchemaDefinitionError.prototype.name = 'SchemaDefinitionError';
27
27
 
28
- module.exports = { SchemaDefinitionError };
28
+ // A validator, a custom checkType or a decoder returned a promise to a
29
+ // synchronous check or parse: a programming error of the call, not of the
30
+ // value, so it throws with a code of its own and names the method to use.
31
+ const asyncReturn = (what, where, method) => {
32
+ const error = new TypeError(`The ${what} of "${where}" returned a promise; use ${method}`);
33
+ error.code = 'ERR_ASYNC_VALIDATOR';
34
+ return error;
35
+ };
36
+
37
+ // A function of a subpath was given something other than what it takes (a
38
+ // Schema, a Model, a snapshot, a list of changes): the call is wrong, not a
39
+ // definition, so a plain TypeError with a code of its own, like asyncReturn.
40
+ const invalidTarget = (message) => {
41
+ const error = new TypeError(message);
42
+ error.code = 'ERR_INVALID_TARGET';
43
+ return error;
44
+ };
45
+
46
+ module.exports = { SchemaDefinitionError, asyncReturn, invalidTarget };