@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,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 } = 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 new TypeError('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 ADDED
@@ -0,0 +1,141 @@
1
+ // The state of one `check` call. Validation used to keep the current ancestors
2
+ // and the error limit in module globals, which only worked because validation
3
+ // is synchronous; a context per call keeps two checks independent of each
4
+ // other and leaves the door open to async validators.
5
+ const en = require('./locales/en.js');
6
+
7
+ const { NONE } = require('./issues.js');
8
+
9
+ // The limit when there is none: the largest small integer, so the comparison
10
+ // with the count on every field stays an integer comparison.
11
+ const UNLIMITED = 2 ** 30 - 1;
12
+
13
+ const shown = (value) =>
14
+ typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
15
+
16
+ const invalid = (name, expected, value) =>
17
+ new TypeError(`${name} must be ${expected}, got ${shown(value)}`);
18
+
19
+ // A whole number of issues, or no limit at all.
20
+ const maxErrorsOf = (maxErrors) => {
21
+ const valid = (Number.isInteger(maxErrors) || maxErrors === Infinity) && maxErrors >= 1;
22
+ if (!valid) throw invalid('maxErrors', 'an integer of at least 1', maxErrors);
23
+ return Math.min(maxErrors, UNLIMITED);
24
+ };
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
+
42
+ const messagesOf = (messages) => {
43
+ if (typeof messages === 'function') return messages;
44
+ if (messages === null || typeof messages !== 'object') {
45
+ throw invalid('messages', 'a locale table or a function', messages);
46
+ }
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;
54
+ };
55
+
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;
61
+ }
62
+ throw invalid(
63
+ 'unknown',
64
+ parsing ? '"reject", "ignore" or "strip"' : '"reject" or "ignore"',
65
+ unknown,
66
+ );
67
+ };
68
+
69
+ const referencesOf = (references) => {
70
+ if (references !== 'kind' && references !== 'embed' && references !== 'id') {
71
+ throw invalid('references', '"kind", "embed" or "id"', references);
72
+ }
73
+ return references;
74
+ };
75
+
76
+ const rootOf = (root) => {
77
+ if (typeof root !== 'string') throw invalid('root', 'a string', root);
78
+ return root;
79
+ };
80
+
81
+ // The 1.x signature was check(value, path, options); a string here is that
82
+ // path, and the message says where it went.
83
+ const optionsOf = (options) => {
84
+ if (options !== null && typeof options === 'object') return options;
85
+ const hint = typeof options === 'string' ? ' (the path is options.root now)' : '';
86
+ throw invalid('check options', `an object${hint}`, options);
87
+ };
88
+
89
+ // The options of a call, checked and written over the defaults. Kept out of
90
+ // createContext so that the allocation stays small enough for V8 to inline
91
+ // into Schema#check: a check without options is the common call.
92
+ const configure = (context, options, parsing) => {
93
+ optionsOf(options);
94
+ if (options.maxErrors !== undefined) context.limit = maxErrorsOf(options.maxErrors);
95
+ if (options.maxDepth !== undefined) context.maxDepth = maxDepthOf(options.maxDepth);
96
+ if (options.messages !== undefined) context.messages = messagesOf(options.messages);
97
+ if (options.unknown !== undefined) context.unknown = unknownOf(options.unknown, parsing);
98
+ if (options.references !== undefined) context.references = referencesOf(options.references);
99
+ if (options.root !== undefined) context.root = rootOf(options.root);
100
+ };
101
+
102
+ // One object shape for every context: the keys are always present, in this
103
+ // order, so the hot path sees a single hidden class. `unknown` is what the
104
+ // schema being checked says (its unknown-keys policy); an option of the call
105
+ // wins over it. `parsing` is set by parse, whose options accept `strip`.
106
+ const createContext = (options, name = '', unknown = 'reject', parsing = false) => {
107
+ const context = {
108
+ issues: NONE,
109
+ count: 0,
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,
114
+ path: [],
115
+ // The objects on the current path, created at the first object met so a
116
+ // check over scalars never allocates it.
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,
123
+ unknown,
124
+ // How a reference is checked: by the kind of its target ('kind'), as
125
+ // the record itself ('embed') or as its id ('id').
126
+ references: 'kind',
127
+ root: name,
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
+ };
137
+ if (options !== undefined) configure(context, options, parsing);
138
+ return context;
139
+ };
140
+
141
+ module.exports = { createContext, UNLIMITED, MAX_DEPTH };
package/src/errors.js CHANGED
@@ -25,4 +25,13 @@ 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
+ module.exports = { SchemaDefinitionError, asyncReturn };
@@ -0,0 +1,29 @@
1
+ import type {
2
+ InterfaceOptions,
3
+ JSONSchema,
4
+ JSONSchemaOptions,
5
+ Model,
6
+ ModelJSONSchemaOptions,
7
+ Schema,
8
+ } from '../../index.js';
9
+
10
+ // The JSON Schema document of a schema, or of a model: every entity as a
11
+ // definition, or the document of the entity `options.root`.
12
+ export function toJSONSchema(target: Schema, options?: JSONSchemaOptions): JSONSchema;
13
+ export function toJSONSchema(target: Model, options?: ModelJSONSchemaOptions): JSONSchema;
14
+
15
+ // The TypeScript interface of a schema (a type alias for a schema of one
16
+ // type), or the interfaces of every entity of a model in dependency order.
17
+ export function toTypeScript(target: Schema | Model, options?: InterfaceOptions): string;
18
+
19
+ // Writes `toTypeScript(target, options)` to a file. Rejects in the browser.
20
+ export function saveTypes(
21
+ outputFile: string,
22
+ target: Schema | Model,
23
+ options?: InterfaceOptions,
24
+ ): Promise<void>;
25
+
26
+ // Installs `schema.toJSONSchema`, `schema.toInterface`, `model.toJSONSchema`,
27
+ // `model.toTypeScript`, `model.dts` and `schema['~standard'].jsonSchema`.
28
+ // Once per process; later calls do nothing.
29
+ export function register(): void;
@@ -0,0 +1,90 @@
1
+ // The `./generators` subpath: what a schema or a model is rendered into
2
+ // (JSON Schema, TypeScript), kept out of the core entry so that a program
3
+ // that only validates does not carry it. The functions take a Schema or a
4
+ // Model; `register()` installs them as methods, and the Standard JSON Schema
5
+ // converter on `~standard`, for the programs that want the methods.
6
+ const { hasBrand } = require('../util.js');
7
+ const { Schema } = require('../schema.js');
8
+ const { Model } = require('../model.js');
9
+ const { writeFile } = require('../runtime/node.js');
10
+ const generators = require('./jsonschema.js');
11
+ const typescript = require('./typescript.js');
12
+
13
+ const isModel = (target) => {
14
+ if (hasBrand(target, 'Schema')) return false;
15
+ if (hasBrand(target, 'Model')) return true;
16
+ throw new TypeError('A Schema or a Model is expected');
17
+ };
18
+
19
+ // The JSON Schema document of a schema, or of a model (every entity as a
20
+ // definition, or the entity `options.root`).
21
+ const toJSONSchema = (target, options) =>
22
+ isModel(target)
23
+ ? generators.modelToJSONSchema(target, options)
24
+ : generators.toJSONSchema(target, options);
25
+
26
+ // The TypeScript interface of a schema, or the interfaces of every entity
27
+ // of a model in dependency order.
28
+ const toTypeScript = (target, options) =>
29
+ isModel(target)
30
+ ? typescript.modelToTypeScript(target, options)
31
+ : typescript.toInterface(target, options);
32
+
33
+ // Async, so that an error of the rendering (a target that is neither, a type
34
+ // with no form) is the rejection the typings promise, never a throw.
35
+ const saveTypes = async (outputFile, target, options) =>
36
+ writeFile(outputFile, toTypeScript(target, options));
37
+
38
+ const schemaMethods = {
39
+ toJSONSchema(options) {
40
+ return generators.toJSONSchema(this, options);
41
+ },
42
+ toInterface(options) {
43
+ return typescript.toInterface(this, options);
44
+ },
45
+ };
46
+
47
+ const modelMethods = {
48
+ toJSONSchema(options) {
49
+ return generators.modelToJSONSchema(this, options);
50
+ },
51
+ toTypeScript(options) {
52
+ return typescript.modelToTypeScript(this, options);
53
+ },
54
+ get dts() {
55
+ return typescript.modelToTypeScript(this);
56
+ },
57
+ };
58
+
59
+ // Installed like class members: not enumerable, so a loop over a schema
60
+ // never sees them.
61
+ const install = (prototype, members) => {
62
+ const descriptors = Object.getOwnPropertyDescriptors(members);
63
+ for (const name in descriptors) {
64
+ descriptors[name].enumerable = false;
65
+ Object.defineProperty(prototype, name, descriptors[name]);
66
+ }
67
+ };
68
+
69
+ let registered = false;
70
+
71
+ // Adds `toJSONSchema` and `toInterface` to every schema, `toJSONSchema`,
72
+ // `toTypeScript` and `dts` to every model, and the `jsonSchema` converter of
73
+ // Standard JSON Schema to `schema['~standard']` (built once per schema, on
74
+ // top of the props the core builds). Once per process.
75
+ const register = () => {
76
+ if (registered) return;
77
+ registered = true;
78
+ install(Schema.prototype, schemaMethods);
79
+ install(Model.prototype, modelMethods);
80
+ const standard = Object.getOwnPropertyDescriptor(Schema.prototype, '~standard');
81
+ const { get } = standard;
82
+ standard.get = function withConverter() {
83
+ const props = get.call(this);
84
+ if (props.jsonSchema === undefined) props.jsonSchema = generators.standardConverter(this);
85
+ return props;
86
+ };
87
+ Object.defineProperty(Schema.prototype, '~standard', standard);
88
+ };
89
+
90
+ module.exports = { toJSONSchema, toTypeScript, saveTypes, register };