@alexify/metaschema 2.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.
- package/CHANGELOG.md +324 -1
- package/README.md +117 -12
- package/SECURITY.md +27 -8
- package/index.d.ts +319 -83
- package/package.json +21 -6
- package/src/codec.js +490 -0
- package/src/compile/code.js +92 -0
- package/src/compile/emit.js +512 -0
- package/src/compile/index.d.ts +38 -0
- package/src/compile/index.js +176 -0
- package/src/context.js +65 -19
- package/src/errors.js +10 -1
- package/src/generators/index.d.ts +29 -0
- package/src/generators/index.js +90 -0
- package/src/generators/jsonschema.js +535 -0
- package/src/generators/typescript.js +237 -0
- package/src/index.js +0 -2
- package/src/issues.js +117 -22
- package/src/kinds.js +9 -12
- package/src/lint.js +20 -12
- package/src/locales/en.js +10 -2
- package/src/locales/uk.js +7 -2
- package/src/metadata.js +41 -44
- package/src/metautil.js +8 -1
- package/src/model.js +10 -15
- package/src/preprocessor.js +5 -10
- package/src/prototypes/abstract.js +14 -1
- package/src/prototypes/collections.js +20 -3
- package/src/prototypes/reference.js +17 -3
- package/src/prototypes/scalars.js +1 -3
- package/src/prototypes/schema.js +12 -0
- package/src/prototypes/tuple.js +14 -9
- package/src/prototypes/union.js +57 -18
- package/src/result.js +5 -14
- package/src/rules.js +55 -26
- package/src/runtime/browser.js +2 -2
- package/src/runtime/node.js +4 -2
- package/src/schema.js +120 -101
- package/src/struct.js +18 -7
- package/src/types.js +5 -11
- package/src/util.js +39 -0
package/src/metadata.js
CHANGED
|
@@ -1,50 +1,47 @@
|
|
|
1
1
|
const { getKindMetadata } = require('./kinds.js');
|
|
2
2
|
const { ValidationResult } = require('./result.js');
|
|
3
|
-
const { SchemaDefinitionError } = require('./errors.js');
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
const { SchemaDefinitionError, asyncReturn } = require('./errors.js');
|
|
4
|
+
const { isThenable } = require('./issues.js');
|
|
5
|
+
|
|
6
|
+
// The functions of a schema definition that are the schema's own: its
|
|
7
|
+
// validate, its decoder, its serializer and `format`.
|
|
8
|
+
const OPTIONS = new Set(['validate', 'parse', 'serialize', 'format']);
|
|
7
9
|
|
|
8
10
|
// The unknown-keys policy of a schema is the default of its `check`, so a
|
|
9
11
|
// value with keys the schema does not have is rejected or ignored without
|
|
10
12
|
// an option on every call; the option of a call still wins.
|
|
11
13
|
const unknownOf = (unknown) => {
|
|
12
14
|
if (unknown === undefined) return 'reject';
|
|
13
|
-
if (
|
|
15
|
+
if (unknown !== 'reject' && unknown !== 'ignore') {
|
|
14
16
|
const reason = `Schema metadata "unknown" must be "reject" or "ignore", got ${JSON.stringify(unknown)}`;
|
|
15
17
|
throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
16
18
|
}
|
|
17
19
|
return unknown;
|
|
18
20
|
};
|
|
19
21
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
}
|
|
22
|
+
// `indexes` is a null-prototype dictionary keyed by definition keys, which may
|
|
23
|
+
// be called `extract` or `constructor`; `options` only ever holds the four
|
|
24
|
+
// keys below and stays a plain object with fast properties: the compiled
|
|
25
|
+
// check reads `options.validate` on every call, and V8 keeps an object made
|
|
26
|
+
// by `Object.create(null)` in dictionary mode.
|
|
27
|
+
const createOptions = () => ({ validate: null, format: null, parse: null, serialize: null });
|
|
27
28
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
}
|
|
29
|
+
const extractOption = (options, key, field) => {
|
|
30
|
+
const isOption = typeof field === 'function' && OPTIONS.has(key);
|
|
31
|
+
if (isOption) options[key] = field;
|
|
32
|
+
return isOption;
|
|
33
|
+
};
|
|
35
34
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
}
|
|
35
|
+
// Index definitions (`index`, `primary`, `unique` arrays) are taken out of the
|
|
36
|
+
// fields; a `many` relation is recorded as well but stays a field, so only
|
|
37
|
+
// whether the entry was taken is reported.
|
|
38
|
+
const extractIndex = (indexes, key, field) => {
|
|
39
|
+
if (field === null || typeof field !== 'object') return false;
|
|
40
|
+
const { index, primary, unique, many } = field;
|
|
41
|
+
const isIndex = Array.isArray(index || primary || unique);
|
|
42
|
+
if (isIndex || many) indexes[key] = field;
|
|
43
|
+
return isIndex;
|
|
44
|
+
};
|
|
48
45
|
|
|
49
46
|
class SchemaMetadata {
|
|
50
47
|
constructor() {
|
|
@@ -54,8 +51,8 @@ class SchemaMetadata {
|
|
|
54
51
|
this.allow = 'write';
|
|
55
52
|
this.parent = '';
|
|
56
53
|
this.unknown = 'reject';
|
|
57
|
-
this.indexes =
|
|
58
|
-
this.options =
|
|
54
|
+
this.indexes = Object.create(null);
|
|
55
|
+
this.options = createOptions();
|
|
59
56
|
this.custom = {};
|
|
60
57
|
this.references = new Set();
|
|
61
58
|
this.relations = new Set();
|
|
@@ -85,26 +82,26 @@ class SchemaMetadata {
|
|
|
85
82
|
|
|
86
83
|
extractMetadata(defs) {
|
|
87
84
|
const fields = Object.create(null);
|
|
88
|
-
for (const
|
|
89
|
-
const
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
const taken = this[collection].extract(key, field);
|
|
94
|
-
if (taken) extracted = true;
|
|
95
|
-
}
|
|
96
|
-
if (!extracted) fields[key] = field;
|
|
85
|
+
for (const key of Object.keys(defs)) {
|
|
86
|
+
const field = defs[key];
|
|
87
|
+
const option = extractOption(this.options, key, field);
|
|
88
|
+
const index = extractIndex(this.indexes, key, field);
|
|
89
|
+
if (!option && !index) fields[key] = field;
|
|
97
90
|
}
|
|
98
91
|
return fields;
|
|
99
92
|
}
|
|
100
93
|
|
|
101
|
-
// Runs only the schema-level validate function, as a result of its own
|
|
94
|
+
// Runs only the schema-level validate function, as a result of its own; a
|
|
95
|
+
// function that returns a promise is an error here, as in check.
|
|
102
96
|
validate(value, path = '') {
|
|
103
97
|
if (!this.options.validate) return null;
|
|
104
98
|
const result = new ValidationResult();
|
|
105
99
|
try {
|
|
106
|
-
|
|
100
|
+
const output = this.options.validate.call(this, value, path);
|
|
101
|
+
if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
|
|
102
|
+
return result.add(output);
|
|
107
103
|
} catch (error) {
|
|
104
|
+
if (error.code === 'ERR_ASYNC_VALIDATOR') throw error;
|
|
108
105
|
return result.add({
|
|
109
106
|
code: 'exception',
|
|
110
107
|
message: `validation failed ${error}`,
|
package/src/metautil.js
CHANGED
|
@@ -11,7 +11,14 @@ const isFirstLetter = (s) => isFirstUpper(s) || isFirstLower(s);
|
|
|
11
11
|
|
|
12
12
|
const toLowerCamel = (s) => s.charAt(0).toLowerCase() + s.slice(1);
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
// The first own key that starts with a letter, without a list of the keys:
|
|
15
|
+
// this runs once for every object of a definition.
|
|
16
|
+
const firstKey = (obj) => {
|
|
17
|
+
for (const key in obj) {
|
|
18
|
+
if (Object.hasOwn(obj, key) && isFirstLetter(key)) return key;
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
};
|
|
15
22
|
|
|
16
23
|
module.exports = {
|
|
17
24
|
inRange,
|
package/src/model.js
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
const { firstKey } = require('./metautil.js');
|
|
2
2
|
|
|
3
|
+
const { BRAND } = require('./util.js');
|
|
3
4
|
const { Schema } = require('./schema.js');
|
|
4
5
|
const { TYPES, createRegistry, typeFactory } = require('./types.js');
|
|
5
6
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
6
7
|
const { warning } = require('./lint.js');
|
|
7
8
|
|
|
8
|
-
const REGISTRIES = ['shared', 'isolated'];
|
|
9
|
-
|
|
10
9
|
const registryFor = (options) => {
|
|
11
10
|
const { registry = 'shared' } = options;
|
|
12
|
-
if (
|
|
11
|
+
if (registry !== 'shared' && registry !== 'isolated') {
|
|
13
12
|
const reason = `Model option "registry" must be "shared" or "isolated", got ${JSON.stringify(registry)}`;
|
|
14
13
|
throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
15
14
|
}
|
|
@@ -53,13 +52,17 @@ class Model {
|
|
|
53
52
|
get warnings() {
|
|
54
53
|
if (this.#warnings !== null) return this.#warnings;
|
|
55
54
|
const warnings = [];
|
|
55
|
+
const add = (list) => {
|
|
56
|
+
for (let index = 0; index < list.length; index += 1) warnings.push(list[index]);
|
|
57
|
+
};
|
|
56
58
|
for (const pair of this.entities) {
|
|
57
59
|
const name = pair[0];
|
|
58
60
|
const entity = pair[1];
|
|
59
61
|
if (name.startsWith('.')) continue;
|
|
60
|
-
|
|
62
|
+
add(entity.warnings);
|
|
63
|
+
add(entity.checkConsistency());
|
|
61
64
|
}
|
|
62
|
-
|
|
65
|
+
add(this.#cycles);
|
|
63
66
|
this.#warnings = warnings;
|
|
64
67
|
return warnings;
|
|
65
68
|
}
|
|
@@ -93,16 +96,8 @@ class Model {
|
|
|
93
96
|
visiting.delete(name);
|
|
94
97
|
this.order.add(name);
|
|
95
98
|
}
|
|
96
|
-
|
|
97
|
-
get dts() {
|
|
98
|
-
const { entities, order } = this;
|
|
99
|
-
const dts = [];
|
|
100
|
-
for (const name of order) {
|
|
101
|
-
const schema = entities.get(name);
|
|
102
|
-
dts.push(schema.toInterface());
|
|
103
|
-
}
|
|
104
|
-
return `${dts.join('\n\n')}\n`;
|
|
105
|
-
}
|
|
106
99
|
}
|
|
107
100
|
|
|
101
|
+
Model.prototype[BRAND] = 'Model';
|
|
102
|
+
|
|
108
103
|
module.exports = { Model };
|
package/src/preprocessor.js
CHANGED
|
@@ -2,11 +2,12 @@ const { isFirstUpper, toLowerCamel, firstKey } = require('./metautil.js');
|
|
|
2
2
|
|
|
3
3
|
const { hasBrand, formatters } = require('./util.js');
|
|
4
4
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
5
|
+
const { typeOf } = require('./issues.js');
|
|
5
6
|
|
|
6
7
|
// The first key of an object decides what it is: a Schema or a built field is
|
|
7
8
|
// used as it is, a capitalized key is a kind, `type` is the long form, a type
|
|
8
9
|
// name is that type's shorthand, and anything else is a nested struct.
|
|
9
|
-
const PARSERS = {
|
|
10
|
+
const PARSERS = Object.assign(Object.create(null), {
|
|
10
11
|
string: ['stringShorthand'],
|
|
11
12
|
object: [
|
|
12
13
|
'schemaInstance',
|
|
@@ -18,15 +19,9 @@ const PARSERS = {
|
|
|
18
19
|
],
|
|
19
20
|
function: ['functionField'],
|
|
20
21
|
array: ['tupleShorthand'],
|
|
21
|
-
};
|
|
22
|
+
});
|
|
22
23
|
|
|
23
|
-
const
|
|
24
|
-
if (src === null) return 'null';
|
|
25
|
-
if (Array.isArray(src)) return 'array';
|
|
26
|
-
return typeof src;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
const invalid = (source, srcType = sourceType(source)) =>
|
|
24
|
+
const invalid = (source, srcType = typeOf(source)) =>
|
|
30
25
|
new SchemaDefinitionError(
|
|
31
26
|
'ERR_INVALID_DEFINITION',
|
|
32
27
|
`Invalid definition: "${source}" of type ${srcType}`,
|
|
@@ -42,7 +37,7 @@ class Preprocessor {
|
|
|
42
37
|
// The first key of an object is read once here and handed to the parsers
|
|
43
38
|
// that look at it.
|
|
44
39
|
parse(source) {
|
|
45
|
-
const srcType =
|
|
40
|
+
const srcType = typeOf(source);
|
|
46
41
|
const parsers = PARSERS[srcType];
|
|
47
42
|
if (parsers) {
|
|
48
43
|
const first = srcType === 'object' ? firstKey(source) : undefined;
|
|
@@ -14,6 +14,18 @@ const reservedKey = (key) =>
|
|
|
14
14
|
const invalidNullable = () =>
|
|
15
15
|
new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "nullable" needs a boolean');
|
|
16
16
|
|
|
17
|
+
const invalidCodec = (key) =>
|
|
18
|
+
new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a function`);
|
|
19
|
+
|
|
20
|
+
// `parse` (the decoder) and `serialize` are read by parse and serialize, on
|
|
21
|
+
// any type; a definition that gave them anything else can never work.
|
|
22
|
+
const checkCodecs = (type) => {
|
|
23
|
+
if (type.parse !== undefined && typeof type.parse !== 'function') throw invalidCodec('parse');
|
|
24
|
+
if (type.serialize !== undefined && typeof type.serialize !== 'function') {
|
|
25
|
+
throw invalidCodec('serialize');
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
17
29
|
// A nullable field accepts null in place of a value of its type, whatever
|
|
18
30
|
// its rules; `required` still says whether the key must be there.
|
|
19
31
|
const nullable = (inner) => (value, context, key) => {
|
|
@@ -75,9 +87,10 @@ class AbstractType {
|
|
|
75
87
|
this.construct(def, preprocessor);
|
|
76
88
|
if (this.type) this.root.references.add(this.type);
|
|
77
89
|
if (this.nullable !== undefined && typeof this.nullable !== 'boolean') throw invalidNullable();
|
|
90
|
+
checkCodecs(this);
|
|
78
91
|
// The rule checks that apply to this field, compiled once: a field
|
|
79
92
|
// without rules is its type check alone, and check is the hot path.
|
|
80
|
-
const checks = compileRules(this
|
|
93
|
+
const checks = compileRules(this);
|
|
81
94
|
const inner = this.compile();
|
|
82
95
|
const plain = checks.length === 0 && !this.validate;
|
|
83
96
|
const check = plain ? inner : withRules(this, inner, checks);
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
const { issues } = require('../issues.js');
|
|
2
|
+
const { SchemaDefinitionError } = require('../errors.js');
|
|
3
|
+
|
|
4
|
+
// The keys of a keyed collection are strings or numbers; anything else can
|
|
5
|
+
// never match a key, and the JIT quotes the key type into its source.
|
|
6
|
+
const invalidKey = (type) => {
|
|
7
|
+
const reason = `Type "${type}" needs a key type of "string" or "number"`;
|
|
8
|
+
return new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason);
|
|
9
|
+
};
|
|
2
10
|
|
|
3
11
|
// Collections iterate their source directly: an object with for...in over
|
|
4
12
|
// its own keys, a Map and a Set through their iterators, an array by index.
|
|
@@ -12,9 +20,18 @@ const object = {
|
|
|
12
20
|
construct(def, prep) {
|
|
13
21
|
const { type } = this;
|
|
14
22
|
const { [type]: short, key, value } = def;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
23
|
+
let keyType = key;
|
|
24
|
+
let valueDef = value;
|
|
25
|
+
// The shorthand holds one pair: `{ object: { string: 'number' } }`.
|
|
26
|
+
if (short !== null && typeof short === 'object') {
|
|
27
|
+
for (const name in short) {
|
|
28
|
+
if (!Object.hasOwn(short, name)) continue;
|
|
29
|
+
keyType = name;
|
|
30
|
+
valueDef = short[name];
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (keyType !== 'string' && keyType !== 'number') throw invalidKey(type);
|
|
18
35
|
this.key = keyType;
|
|
19
36
|
const { Type, defs } = prep.parse(valueDef);
|
|
20
37
|
this.value = new Type(defs, prep);
|
|
@@ -7,20 +7,34 @@ const invalidEmbed = () =>
|
|
|
7
7
|
|
|
8
8
|
// A reference is the one place a schema can recurse (Category.parent is a
|
|
9
9
|
// Category), so it is where a value met again while it is still being
|
|
10
|
-
// checked is a cycle, reported instead of recursed into
|
|
10
|
+
// checked is a cycle, reported instead of recursed into, and where a graph
|
|
11
|
+
// nested deeper than the check allows is reported instead of overflowing the
|
|
12
|
+
// stack.
|
|
11
13
|
const runReferenced = (schema, value, context, key) => {
|
|
12
14
|
if (value === null || typeof value !== 'object') {
|
|
13
15
|
schema[RUN](value, context, key);
|
|
14
16
|
return;
|
|
15
17
|
}
|
|
16
|
-
if (context.
|
|
17
|
-
|
|
18
|
+
if (context.depth >= context.maxDepth) {
|
|
19
|
+
issues.depth(context, context.maxDepth, key);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
let { seen } = context;
|
|
23
|
+
if (seen === null) {
|
|
24
|
+
// The first embedded record creates the set, and the value the check
|
|
25
|
+
// started from joins it then, so a check that embeds nothing pays nothing.
|
|
26
|
+
seen = new Set();
|
|
27
|
+
if (context.source !== null) seen.add(context.source);
|
|
28
|
+
context.seen = seen;
|
|
29
|
+
}
|
|
18
30
|
if (seen.has(value)) {
|
|
19
31
|
issues.circular(context, key);
|
|
20
32
|
return;
|
|
21
33
|
}
|
|
22
34
|
seen.add(value);
|
|
35
|
+
context.depth += 1;
|
|
23
36
|
schema[RUN](value, context, key);
|
|
37
|
+
context.depth -= 1;
|
|
24
38
|
seen.delete(value);
|
|
25
39
|
};
|
|
26
40
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
2
2
|
const { issues } = require('../issues.js');
|
|
3
|
+
const { ENUM_SET_SIZE } = require('../util.js');
|
|
3
4
|
|
|
4
5
|
const missingEnum = (type) => {
|
|
5
6
|
const hint = `Type "${type}" needs a list of values: { type: '${type}', enum: [...] }`;
|
|
@@ -26,9 +27,6 @@ const scalar = {
|
|
|
26
27
|
},
|
|
27
28
|
};
|
|
28
29
|
|
|
29
|
-
// Past this many values a Set lookup beats a linear scan.
|
|
30
|
-
const ENUM_SET_SIZE = 8;
|
|
31
|
-
|
|
32
30
|
const enumerable = {
|
|
33
31
|
kind: 'scalar',
|
|
34
32
|
options: ['enum'],
|
package/src/prototypes/schema.js
CHANGED
|
@@ -10,6 +10,16 @@ const missingSchema = (type) => {
|
|
|
10
10
|
const isDefinition = (value) =>
|
|
11
11
|
value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
12
12
|
|
|
13
|
+
// The decoder and the serializer of a nested struct: the functions of its
|
|
14
|
+
// definition (the options of a Schema it reuses), as its validate is, unless
|
|
15
|
+
// the field's own definition gave them.
|
|
16
|
+
const adopt = (type, source) => {
|
|
17
|
+
if (type.parse === undefined && typeof source.parse === 'function') type.parse = source.parse;
|
|
18
|
+
if (type.serialize === undefined && typeof source.serialize === 'function') {
|
|
19
|
+
type.serialize = source.serialize;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
13
23
|
// A nested struct: built from a definition object, or borrowed from a Schema
|
|
14
24
|
// instance, whose fields, references and schema-level validate are reused.
|
|
15
25
|
const schema = {
|
|
@@ -24,11 +34,13 @@ const schema = {
|
|
|
24
34
|
prep.root.updateFromSchema(definition);
|
|
25
35
|
this.schema = definition.fields;
|
|
26
36
|
this.validate = definition.options.validate || undefined;
|
|
37
|
+
adopt(this, definition.options);
|
|
27
38
|
return;
|
|
28
39
|
}
|
|
29
40
|
if (isStruct(definition)) this.schema = definition;
|
|
30
41
|
else this.schema = createStruct(definition, prep);
|
|
31
42
|
this.validate = definition.validate || undefined;
|
|
43
|
+
adopt(this, definition);
|
|
32
44
|
},
|
|
33
45
|
|
|
34
46
|
compile() {
|
package/src/prototypes/tuple.js
CHANGED
|
@@ -24,25 +24,30 @@ const tuple = {
|
|
|
24
24
|
construct(def, prep) {
|
|
25
25
|
const elements = def.value || def.tuple;
|
|
26
26
|
if (!Array.isArray(elements)) throw invalidTuple('needs a list of element definitions');
|
|
27
|
-
|
|
27
|
+
const built = [];
|
|
28
|
+
for (let index = 0; index < elements.length; index += 1) {
|
|
29
|
+
const element = elements[index];
|
|
28
30
|
const key = nameOf(element, prep.types);
|
|
29
31
|
const source = key === null ? element : element[key];
|
|
30
32
|
const { Type, defs } = prep.parse(source);
|
|
31
33
|
if (!Type) throw invalidTuple(`element ${index} cannot be a function`);
|
|
34
|
+
let name = null;
|
|
32
35
|
if (key !== null) {
|
|
33
|
-
const
|
|
34
|
-
defs.required = (defs.required ?? true) && required;
|
|
35
|
-
|
|
36
|
-
type.name = field;
|
|
37
|
-
return type;
|
|
36
|
+
const parsed = formatters.key(key);
|
|
37
|
+
defs.required = (defs.required ?? true) && parsed.required;
|
|
38
|
+
name = parsed.field;
|
|
38
39
|
}
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
const type = new Type(defs, prep);
|
|
41
|
+
if (name !== null) type.name = name;
|
|
42
|
+
built.push(type);
|
|
43
|
+
}
|
|
44
|
+
this.value = built;
|
|
41
45
|
},
|
|
42
46
|
|
|
43
47
|
compile() {
|
|
44
48
|
const { required, type } = this;
|
|
45
|
-
const checks =
|
|
49
|
+
const checks = [];
|
|
50
|
+
for (let index = 0; index < this.value.length; index += 1) checks.push(this.value[index].check);
|
|
46
51
|
const { length } = checks;
|
|
47
52
|
return (value, context, key) => {
|
|
48
53
|
if (!Array.isArray(value)) {
|
package/src/prototypes/union.js
CHANGED
|
@@ -18,6 +18,25 @@ const valuesOf = (branch, discriminator, index) => {
|
|
|
18
18
|
return field.enum;
|
|
19
19
|
};
|
|
20
20
|
|
|
21
|
+
// The branch of a discriminated union by the value of its discriminator, as
|
|
22
|
+
// a Map of value to branch index: built once per field, on first use, and
|
|
23
|
+
// shared by the check, the passes of parse and the JIT.
|
|
24
|
+
const TABLES = new WeakMap();
|
|
25
|
+
|
|
26
|
+
const tableOf = (field) => {
|
|
27
|
+
let table = TABLES.get(field);
|
|
28
|
+
if (table === undefined) {
|
|
29
|
+
table = new Map();
|
|
30
|
+
const { union: branches, discriminator } = field;
|
|
31
|
+
for (let index = 0; index < branches.length; index += 1) {
|
|
32
|
+
const values = branches[index].schema[discriminator].enum;
|
|
33
|
+
for (let at = 0; at < values.length; at += 1) table.set(values[at], index);
|
|
34
|
+
}
|
|
35
|
+
TABLES.set(field, table);
|
|
36
|
+
}
|
|
37
|
+
return table;
|
|
38
|
+
};
|
|
39
|
+
|
|
21
40
|
// A value of one of several definitions. Without a discriminator the
|
|
22
41
|
// branches are tried in order and the first one that records nothing wins;
|
|
23
42
|
// what a failed branch recorded is dropped. With one, the branch is picked
|
|
@@ -31,45 +50,56 @@ const union = {
|
|
|
31
50
|
if (!Array.isArray(branches) || branches.length === 0) {
|
|
32
51
|
throw invalidUnion('needs a list of branches: { union: [...] }');
|
|
33
52
|
}
|
|
34
|
-
|
|
35
|
-
|
|
53
|
+
const built = [];
|
|
54
|
+
for (let index = 0; index < branches.length; index += 1) {
|
|
55
|
+
const { Type, defs } = prep.parse(branches[index]);
|
|
36
56
|
if (!Type) throw invalidUnion(`branch ${index} cannot be a function`);
|
|
37
|
-
|
|
38
|
-
}
|
|
57
|
+
built.push(new Type(defs, prep));
|
|
58
|
+
}
|
|
59
|
+
this.union = built;
|
|
39
60
|
const { discriminator } = this;
|
|
40
61
|
if (discriminator === undefined) return;
|
|
41
62
|
if (typeof discriminator !== 'string' || discriminator === '') {
|
|
42
63
|
throw invalidUnion('discriminator needs a field name');
|
|
43
64
|
}
|
|
44
65
|
const seen = new Set();
|
|
45
|
-
|
|
46
|
-
|
|
66
|
+
for (let index = 0; index < built.length; index += 1) {
|
|
67
|
+
const values = valuesOf(built[index], discriminator, index);
|
|
68
|
+
// The branch is picked by the value before any default is applied, so
|
|
69
|
+
// a default on the discriminator could never decide anything.
|
|
70
|
+
if (built[index].schema[discriminator].default !== undefined) {
|
|
71
|
+
throw invalidUnion(
|
|
72
|
+
`discriminator "${discriminator}" of branch ${index} cannot have a default`,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
for (let at = 0; at < values.length; at += 1) {
|
|
76
|
+
const value = values[at];
|
|
47
77
|
if (seen.has(value)) {
|
|
48
78
|
const shown = JSON.stringify(value);
|
|
49
79
|
throw invalidUnion(`discriminator value ${shown} is in two branches`);
|
|
50
80
|
}
|
|
51
81
|
seen.add(value);
|
|
52
82
|
}
|
|
53
|
-
}
|
|
83
|
+
}
|
|
54
84
|
},
|
|
55
85
|
|
|
56
86
|
compile() {
|
|
57
87
|
const { required, discriminator } = this;
|
|
58
88
|
if (discriminator === undefined) return this.compilePlain(required);
|
|
59
|
-
const
|
|
60
|
-
for (
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const
|
|
89
|
+
const checks = [];
|
|
90
|
+
for (let index = 0; index < this.union.length; index += 1) checks.push(this.union[index].check);
|
|
91
|
+
const table = tableOf(this);
|
|
92
|
+
const expected = [];
|
|
93
|
+
for (const value of table.keys()) expected.push(value);
|
|
64
94
|
return (value, context, key) => {
|
|
65
95
|
if (value === null || typeof value !== 'object') {
|
|
66
96
|
if (!required && value == null) return;
|
|
67
97
|
issues.type(context, 'object', value, key);
|
|
68
98
|
return;
|
|
69
99
|
}
|
|
70
|
-
const
|
|
71
|
-
if (
|
|
72
|
-
|
|
100
|
+
const index = table.get(value[discriminator]);
|
|
101
|
+
if (index !== undefined) {
|
|
102
|
+
checks[index](value, context, key);
|
|
73
103
|
return;
|
|
74
104
|
}
|
|
75
105
|
const nested = key !== undefined;
|
|
@@ -80,21 +110,30 @@ const union = {
|
|
|
80
110
|
},
|
|
81
111
|
|
|
82
112
|
compilePlain(required) {
|
|
83
|
-
const checks =
|
|
84
|
-
const expected =
|
|
113
|
+
const checks = [];
|
|
114
|
+
const expected = [];
|
|
115
|
+
for (let index = 0; index < this.union.length; index += 1) {
|
|
116
|
+
const branch = this.union[index];
|
|
117
|
+
checks.push(branch.check);
|
|
118
|
+
expected.push(nameOf(branch));
|
|
119
|
+
}
|
|
85
120
|
const { length } = checks;
|
|
86
121
|
return (value, context, key) => {
|
|
87
122
|
if (!required && value == null) return;
|
|
88
123
|
const { count } = context;
|
|
124
|
+
// The validators a failed branch set aside in an async check go with
|
|
125
|
+
// its issues: they belong to a branch the value does not match.
|
|
126
|
+
const pending = context.async === null ? 0 : context.async.length;
|
|
89
127
|
for (let index = 0; index < length; index += 1) {
|
|
90
128
|
checks[index](value, context, key);
|
|
91
129
|
if (context.count === count) return;
|
|
92
130
|
context.issues.length = count;
|
|
93
131
|
context.count = count;
|
|
132
|
+
if (context.async !== null) context.async.length = pending;
|
|
94
133
|
}
|
|
95
134
|
issues.union(context, expected, undefined, key);
|
|
96
135
|
};
|
|
97
136
|
},
|
|
98
137
|
};
|
|
99
138
|
|
|
100
|
-
module.exports = { union };
|
|
139
|
+
module.exports = { union, nameOf, tableOf };
|
package/src/result.js
CHANGED
|
@@ -1,23 +1,12 @@
|
|
|
1
|
-
const { BRAND, INSPECT, hasBrand } = require('./util.js');
|
|
1
|
+
const { BRAND, INSPECT, hasBrand, define } = require('./util.js');
|
|
2
2
|
const { EMPTY, NONE, absorb, finalize, describe, toDotPath } = require('./issues.js');
|
|
3
3
|
const en = require('./locales/en.js');
|
|
4
4
|
|
|
5
|
-
// Defines an own data property, so a key such as `__proto__` taken from a
|
|
6
|
-
// path lands on the object instead of changing its prototype.
|
|
7
|
-
const define = (target, key, value) => {
|
|
8
|
-
Object.defineProperty(target, key, {
|
|
9
|
-
value,
|
|
10
|
-
enumerable: true,
|
|
11
|
-
writable: true,
|
|
12
|
-
configurable: true,
|
|
13
|
-
});
|
|
14
|
-
return value;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
5
|
class ValidationResult {
|
|
18
6
|
#root;
|
|
19
7
|
#messages;
|
|
20
8
|
#errors = null;
|
|
9
|
+
#summary = null;
|
|
21
10
|
|
|
22
11
|
// A check builds its result from its context, which carries the root label,
|
|
23
12
|
// the locale of the call and the issues under these names; a validator that
|
|
@@ -45,7 +34,8 @@ class ValidationResult {
|
|
|
45
34
|
}
|
|
46
35
|
|
|
47
36
|
get summary() {
|
|
48
|
-
|
|
37
|
+
if (this.#summary === null) this.#summary = this.errors.join('\n');
|
|
38
|
+
return this.#summary;
|
|
49
39
|
}
|
|
50
40
|
|
|
51
41
|
add(error, code = 'custom') {
|
|
@@ -54,6 +44,7 @@ class ValidationResult {
|
|
|
54
44
|
this.issues = context.issues;
|
|
55
45
|
finalize(this.issues, this.#messages);
|
|
56
46
|
this.#errors = null;
|
|
47
|
+
this.#summary = null;
|
|
57
48
|
return this;
|
|
58
49
|
}
|
|
59
50
|
|