@alexify/metaschema 3.1.0 → 3.3.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 +314 -1
- package/README.md +535 -20
- package/SECURITY.md +26 -7
- package/index.d.ts +496 -2
- package/package.json +53 -5
- package/src/codec.js +239 -74
- package/src/coerce/index.d.ts +34 -0
- package/src/coerce/index.js +352 -0
- package/src/compile/code.js +1 -1
- package/src/compile/emit.js +32 -7
- package/src/compile/index.d.ts +6 -0
- package/src/compile/index.js +12 -1
- package/src/context.js +11 -10
- package/src/derive/index.d.ts +86 -0
- package/src/derive/index.js +266 -0
- package/src/errors.js +28 -1
- package/src/formats/index.d.ts +31 -0
- package/src/formats/index.js +557 -0
- package/src/generators/fromjsonschema.js +16 -14
- package/src/generators/index.js +2 -1
- package/src/generators/jsonschema.js +47 -13
- package/src/issues.js +37 -20
- package/src/kinds.js +11 -2
- package/src/lint.js +24 -0
- package/src/locales/en.js +11 -2
- package/src/locales/uk.js +10 -2
- package/src/metadata.js +7 -2
- package/src/model/data.js +17 -0
- package/src/model/diff.js +1 -0
- package/src/model/index.d.ts +14 -2
- package/src/model/index.js +13 -10
- package/src/model/infer.js +483 -0
- package/src/model/merge.js +10 -6
- package/src/model/restore.js +3 -3
- package/src/model/sample.js +8 -5
- package/src/model.js +34 -4
- package/src/mongodb/bson.js +118 -0
- package/src/mongodb/document.js +209 -0
- package/src/mongodb/index.d.ts +133 -0
- package/src/mongodb/index.js +24 -0
- package/src/mongodb/indexes.js +79 -0
- package/src/mongodb/update.js +258 -0
- package/src/preprocessor.js +1 -0
- package/src/prototypes/abstract.js +9 -3
- package/src/prototypes/collections.js +4 -3
- package/src/prototypes/scalars.js +4 -4
- package/src/prototypes/union.js +2 -2
- package/src/result.js +6 -0
- package/src/rules.js +53 -4
- package/src/schema.js +53 -28
- package/src/snapshot.js +1 -1
- package/src/stream/index.d.ts +68 -0
- package/src/stream/index.js +247 -0
- package/src/struct.js +1 -1
- package/src/types.js +33 -1
- package/src/util.js +18 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// An update of MongoDB against a schema: the fields its dotted paths name
|
|
2
|
+
// (`'address.city'`, `'items.$.qty'`), the values its operators set, push or
|
|
3
|
+
// add to. What depends on the document stored (a length after a `$push`, a
|
|
4
|
+
// bound after an `$inc`, a parent a dotted `$set` creates) is the
|
|
5
|
+
// collection validator's to check; a union, `any` and `json` are not
|
|
6
|
+
// entered. A deep partial schema is not the shape of an update: `$set`
|
|
7
|
+
// replaces what a path names whole, and names nested fields by their paths.
|
|
8
|
+
const { hasBrand, define, RUN } = require('../util.js');
|
|
9
|
+
const { isStruct } = require('../struct.js');
|
|
10
|
+
const { embeds } = require('../prototypes/reference.js');
|
|
11
|
+
const { infoOf, apply, SERIALIZE } = require('../codec.js');
|
|
12
|
+
const { createContext } = require('../context.js');
|
|
13
|
+
const { issues, finalize } = require('../issues.js');
|
|
14
|
+
const { ValidationResult } = require('../result.js');
|
|
15
|
+
const { baseTypeOf } = require('../types.js');
|
|
16
|
+
const { invalidTarget } = require('../errors.js');
|
|
17
|
+
const { ID: KEY, idOf } = require('./bson.js');
|
|
18
|
+
const { SHAPES, walk, idValue, stateOf, listOf } = require('./document.js');
|
|
19
|
+
|
|
20
|
+
const { NESTED, LIST, KEYED, TUPLE, REFERENCE } = SHAPES;
|
|
21
|
+
|
|
22
|
+
// A place an update is not checked at: a union, any, json.
|
|
23
|
+
const LOOSE = Symbol('loose');
|
|
24
|
+
// An element of a list of ids: a string.
|
|
25
|
+
const ID = Symbol('id');
|
|
26
|
+
// A part a node does not have (an element of a string, a field of an id):
|
|
27
|
+
// the path is malformed whatever the policy for unknown keys says, which
|
|
28
|
+
// decides `null`, a key a struct does not have.
|
|
29
|
+
const NONE = Symbol('none');
|
|
30
|
+
// A path through more embedded records than `maxDepth`.
|
|
31
|
+
const DEEP = Symbol('deep');
|
|
32
|
+
|
|
33
|
+
const ELEMENT = /^(?:\d+|\$|\$\[\w*\])$/;
|
|
34
|
+
const INDEX = /^\d+$/;
|
|
35
|
+
|
|
36
|
+
// The operators of the values a path is set to, of the lists it adds to or
|
|
37
|
+
// takes from, and every operator of an update the subpath reads.
|
|
38
|
+
const VALUES = ['$set', '$setOnInsert', '$min', '$max'];
|
|
39
|
+
const LISTS = ['$push', '$addToSet', '$pull', '$pullAll'];
|
|
40
|
+
const OPERATORS = [...VALUES, ...LISTS, '$unset', '$inc', '$mul', '$currentDate', '$pop'];
|
|
41
|
+
|
|
42
|
+
// The type a field is of, through the aliases of custom types.
|
|
43
|
+
const baseOf = (field) => baseTypeOf(field).type;
|
|
44
|
+
|
|
45
|
+
// The record of a reference where it is embedded, else null.
|
|
46
|
+
const targetOf = (node, references) => {
|
|
47
|
+
const target = node.root.findReference(node.one || node.many);
|
|
48
|
+
return target !== null && embeds(target, node.embed, references) ? target : null;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
// What one segment of a path names from a node: the field of a struct, the
|
|
52
|
+
// element of a list (an index, `$`, `$[]`, `$[name]`) or of a tuple, the
|
|
53
|
+
// value of a dictionary, a field of the record a reference embeds; null for
|
|
54
|
+
// a key a struct does not have, NONE for a part a node cannot have.
|
|
55
|
+
const step = (node, segment, references) => {
|
|
56
|
+
if (hasBrand(node, 'Schema')) return step(node.fields, segment, references);
|
|
57
|
+
if (isStruct(node)) return hasBrand(node[segment], 'Type') ? node[segment] : null;
|
|
58
|
+
const { shape } = infoOf(node);
|
|
59
|
+
if (shape === NESTED) return step(node.schema, segment, references);
|
|
60
|
+
if (shape === LIST) return ELEMENT.test(segment) ? node.value : NONE;
|
|
61
|
+
if (shape === KEYED) return node.value;
|
|
62
|
+
if (shape === TUPLE) {
|
|
63
|
+
if (INDEX.test(segment)) return node.value[Number(segment)] ?? NONE;
|
|
64
|
+
return ELEMENT.test(segment) ? LOOSE : NONE;
|
|
65
|
+
}
|
|
66
|
+
if (shape === REFERENCE) {
|
|
67
|
+
const target = targetOf(node, references);
|
|
68
|
+
// An id has no parts; an element of a list of ids is an id.
|
|
69
|
+
if (node.one) return target === null ? NONE : step(target, segment, references);
|
|
70
|
+
if (!ELEMENT.test(segment)) return NONE;
|
|
71
|
+
return target === null ? ID : target;
|
|
72
|
+
}
|
|
73
|
+
const base = baseOf(node);
|
|
74
|
+
return base === 'union' || base === 'any' || base === 'unknown' || base === 'json' ? LOOSE : NONE;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// The node a path names, or null, NONE, LOOSE or DEEP: the records a path
|
|
78
|
+
// goes through are counted as the check counts the records it enters.
|
|
79
|
+
const resolve = (target, segments, references, maxDepth) => {
|
|
80
|
+
let node = target;
|
|
81
|
+
let depth = 0;
|
|
82
|
+
for (let index = 0; index < segments.length && node !== LOOSE; index += 1) {
|
|
83
|
+
if (node === ID) return NONE;
|
|
84
|
+
if (hasBrand(node, 'Type') && infoOf(node).shape === REFERENCE) {
|
|
85
|
+
depth += 1;
|
|
86
|
+
if (depth > maxDepth) return DEEP;
|
|
87
|
+
}
|
|
88
|
+
node = step(node, segments[index], references);
|
|
89
|
+
if (node === null || node === NONE) return node;
|
|
90
|
+
}
|
|
91
|
+
return node;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// The element a `$push` or a `$addToSet` adds to the field, or null when it
|
|
95
|
+
// is no list.
|
|
96
|
+
const elementOf = (node, references) => {
|
|
97
|
+
if (typeof node === 'symbol' || !hasBrand(node, 'Type')) return null;
|
|
98
|
+
const { shape } = infoOf(node);
|
|
99
|
+
if (shape === LIST) return node.value;
|
|
100
|
+
if (shape !== REFERENCE || !node.many) return null;
|
|
101
|
+
return targetOf(node, references) ?? ID;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// The values a list operator carries: one, or the list of `$each`.
|
|
105
|
+
const itemsOf = (value) =>
|
|
106
|
+
value !== null && typeof value === 'object' && Array.isArray(value.$each) ? value.$each : [value];
|
|
107
|
+
|
|
108
|
+
const checkAt = (node, value, context, key) => {
|
|
109
|
+
if (node === ID) {
|
|
110
|
+
if (typeof value !== 'string') issues.type(context, 'string', value, key);
|
|
111
|
+
} else if (hasBrand(node, 'Schema')) node[RUN](value, context, key);
|
|
112
|
+
else node.check(value, context, key);
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// An operand of `$inc` or `$mul`: a number for a field of numbers (a whole
|
|
116
|
+
// one for an integer, a bigint for a bigint), never a field of another type;
|
|
117
|
+
// the issue names what the operator takes, not the type of the field.
|
|
118
|
+
const checkStep = (node, value, context, key) => {
|
|
119
|
+
const base = hasBrand(node, 'Type') ? baseOf(node) : '';
|
|
120
|
+
const fits =
|
|
121
|
+
base === 'bigint'
|
|
122
|
+
? typeof value === 'bigint'
|
|
123
|
+
: typeof value === 'number' &&
|
|
124
|
+
(base === 'number' || (base === 'integer' && Number.isInteger(value)));
|
|
125
|
+
if (!fits) {
|
|
126
|
+
const expected = base === 'bigint' || base === 'integer' ? base : 'number';
|
|
127
|
+
issues.type(context, expected, value, key);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const checkOperation = (operator, node, value, context, key) => {
|
|
132
|
+
if (VALUES.includes(operator)) checkAt(node, value, context, key);
|
|
133
|
+
else if (operator === '$unset') {
|
|
134
|
+
if (hasBrand(node, 'Type') && node.required) issues.required(context, key);
|
|
135
|
+
} else if (operator === '$inc' || operator === '$mul') checkStep(node, value, context, key);
|
|
136
|
+
else if (operator === '$currentDate') checkAt(node, new Date(), context, key);
|
|
137
|
+
else if (operator === '$push' || operator === '$addToSet') {
|
|
138
|
+
const element = elementOf(node, context.references);
|
|
139
|
+
if (element === null) issues.type(context, 'array', value, key);
|
|
140
|
+
else for (const item of itemsOf(value)) checkAt(element, item, context, key);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const segmentOf = (segment) => (INDEX.test(segment) ? Number(segment) : segment);
|
|
145
|
+
|
|
146
|
+
// One path of an operator: the parents on the path of the context, the
|
|
147
|
+
// field it names checked by what the operator does. The id of a stored
|
|
148
|
+
// record (its field, or the `_id` of the document it is written to) is set
|
|
149
|
+
// by an insert only; a path with an empty segment, or into a part a node
|
|
150
|
+
// cannot have, names nothing whatever the policy for unknown keys says.
|
|
151
|
+
const checkPath = (target, id, operator, path, value, context) => {
|
|
152
|
+
const segments = path.split('.');
|
|
153
|
+
const last = segments.length - 1;
|
|
154
|
+
for (let index = 0; index < last; index += 1) context.path.push(segmentOf(segments[index]));
|
|
155
|
+
const key = segmentOf(segments[last]);
|
|
156
|
+
const first = segments[0];
|
|
157
|
+
const immutable =
|
|
158
|
+
(first === id || (first === KEY && !(KEY in target.fields))) && operator !== '$setOnInsert';
|
|
159
|
+
const malformed = immutable || segments.includes('');
|
|
160
|
+
const node = malformed ? NONE : resolve(target, segments, context.references, context.maxDepth);
|
|
161
|
+
if (node === DEEP) issues.depth(context, context.maxDepth, key);
|
|
162
|
+
else if (node === NONE || (node === null && context.unknown === 'reject')) {
|
|
163
|
+
issues.unexpected(context, [segments[last]]);
|
|
164
|
+
} else if (node !== null && node !== LOOSE) checkOperation(operator, node, value, context, key);
|
|
165
|
+
context.path.length -= last;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
169
|
+
|
|
170
|
+
const sourceOf = (target, update) => {
|
|
171
|
+
if (!hasBrand(target, 'Schema') || !isStruct(target.fields)) {
|
|
172
|
+
throw invalidTarget('A Schema of a struct is expected');
|
|
173
|
+
}
|
|
174
|
+
if (!isObject(update)) throw invalidTarget('An update is an object of operators');
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// The issues of an update against the schema, as a ValidationResult: the
|
|
178
|
+
// options of check (`unknown` decides what a path the schema does not have
|
|
179
|
+
// is, `references` which records are entered, `maxErrors`, `messages`,
|
|
180
|
+
// `root`). An operator the subpath does not know, or that has no object of
|
|
181
|
+
// paths, is one `unexpected` issue at the root.
|
|
182
|
+
const checkUpdate = (target, update, options) => {
|
|
183
|
+
sourceOf(target, update);
|
|
184
|
+
const context = createContext(options, target.name, target.unknown);
|
|
185
|
+
const id = idOf(target);
|
|
186
|
+
const unknown = [];
|
|
187
|
+
for (const operator of Object.keys(update)) {
|
|
188
|
+
const operand = update[operator];
|
|
189
|
+
if (!OPERATORS.includes(operator) || !isObject(operand)) {
|
|
190
|
+
unknown.push(operator);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
for (const path of Object.keys(operand)) {
|
|
194
|
+
if (context.count >= context.limit) break;
|
|
195
|
+
checkPath(target, id, operator, path, operand[path], context);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (unknown.length > 0 && context.count < context.limit) issues.unexpected(context, unknown);
|
|
199
|
+
finalize(context.issues, context.messages);
|
|
200
|
+
return new ValidationResult(context);
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// A value of an update as the document holds it: its serializers run, its
|
|
204
|
+
// ids made ObjectIds.
|
|
205
|
+
const valueOf = (state, context, node, value) => {
|
|
206
|
+
if (node === ID) return idValue(state, value);
|
|
207
|
+
const serialized = apply(infoOf(node), node, value, context, undefined, SERIALIZE, SERIALIZE);
|
|
208
|
+
return walk(state, node, serialized);
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const operandOf = (state, context, operator, node, value) => {
|
|
212
|
+
if (VALUES.includes(operator)) return valueOf(state, context, node, value);
|
|
213
|
+
if (!LISTS.includes(operator)) return value;
|
|
214
|
+
const element = elementOf(node, state.references);
|
|
215
|
+
if (element === null) return value;
|
|
216
|
+
const each = (item) => valueOf(state, context, element, item);
|
|
217
|
+
if (operator === '$pullAll') return Array.isArray(value) ? listOf(value, each) : value;
|
|
218
|
+
if (isObject(value)) {
|
|
219
|
+
if (!Array.isArray(value.$each)) return value;
|
|
220
|
+
return { ...value, $each: listOf(value.$each, each) };
|
|
221
|
+
}
|
|
222
|
+
return each(value);
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// The update as the database takes it: the values the schema knows
|
|
226
|
+
// serialized and their ids made ObjectIds, the id of the record as `_id`.
|
|
227
|
+
// What `checkUpdate` would reject is not checked here: check first.
|
|
228
|
+
const toUpdate = (target, update, options) => {
|
|
229
|
+
sourceOf(target, update);
|
|
230
|
+
const state = stateOf(target, options, true);
|
|
231
|
+
const context = createContext({ references: state.references }, target.name, target.unknown);
|
|
232
|
+
const id = idOf(target);
|
|
233
|
+
const out = {};
|
|
234
|
+
for (const operator of Object.keys(update)) {
|
|
235
|
+
const operand = update[operator];
|
|
236
|
+
if (!isObject(operand)) {
|
|
237
|
+
define(out, operator, operand);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const next = {};
|
|
241
|
+
for (const path of Object.keys(operand)) {
|
|
242
|
+
const segments = path.split('.');
|
|
243
|
+
const node = resolve(target, segments, state.references, state.maxDepth);
|
|
244
|
+
let value = operand[path];
|
|
245
|
+
if (segments[0] === id) {
|
|
246
|
+
segments[0] = KEY;
|
|
247
|
+
if (segments.length === 1) value = idValue(state, value);
|
|
248
|
+
} else if (node !== null && (node === ID || typeof node !== 'symbol')) {
|
|
249
|
+
value = operandOf(state, context, operator, node, value);
|
|
250
|
+
}
|
|
251
|
+
define(next, segments.join('.'), value);
|
|
252
|
+
}
|
|
253
|
+
define(out, operator, next);
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
module.exports = { checkUpdate, toUpdate };
|
package/src/preprocessor.js
CHANGED
|
@@ -11,8 +11,12 @@ const RESERVED = new Set(['__proto__', 'prototype', 'check', 'checkType', 'compi
|
|
|
11
11
|
const reservedKey = (key) =>
|
|
12
12
|
new SchemaDefinitionError('ERR_RESERVED_KEY', `Key "${key}" is reserved in a field definition`);
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
// The options of a field that are flags: `nullable` (null in place of a
|
|
15
|
+
// value) and `coerce` (whether parse converts the input of its subtree).
|
|
16
|
+
const FLAGS = ['nullable', 'coerce'];
|
|
17
|
+
|
|
18
|
+
const invalidFlag = (key) =>
|
|
19
|
+
new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a boolean`);
|
|
16
20
|
|
|
17
21
|
const invalidCodec = (key) =>
|
|
18
22
|
new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a function`);
|
|
@@ -86,7 +90,9 @@ class AbstractType {
|
|
|
86
90
|
}
|
|
87
91
|
this.construct(def, preprocessor);
|
|
88
92
|
if (this.type) this.root.references.add(this.type);
|
|
89
|
-
|
|
93
|
+
for (const key of FLAGS) {
|
|
94
|
+
if (this[key] !== undefined && typeof this[key] !== 'boolean') throw invalidFlag(key);
|
|
95
|
+
}
|
|
90
96
|
checkCodecs(this);
|
|
91
97
|
// The rule checks that apply to this field, compiled once: a field
|
|
92
98
|
// without rules is its type check alone, and check is the hot path.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const { issues } = require('../issues.js');
|
|
2
2
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
3
|
+
const { isMap, isSet } = require('../util.js');
|
|
3
4
|
|
|
4
5
|
// The keys of a keyed collection are strings or numbers; anything else can
|
|
5
6
|
// never match a key, and the JIT quotes the key type into its source.
|
|
@@ -77,7 +78,7 @@ const map = {
|
|
|
77
78
|
const { required, type, key: keyType } = this;
|
|
78
79
|
const { check } = this.value;
|
|
79
80
|
return (value, context, key) => {
|
|
80
|
-
if (value
|
|
81
|
+
if (!isMap(value)) {
|
|
81
82
|
if (!required && value == null) return;
|
|
82
83
|
issues.type(context, type, value, key);
|
|
83
84
|
return;
|
|
@@ -103,7 +104,7 @@ const map = {
|
|
|
103
104
|
},
|
|
104
105
|
|
|
105
106
|
isInstance(value) {
|
|
106
|
-
return value
|
|
107
|
+
return isMap(value);
|
|
107
108
|
},
|
|
108
109
|
};
|
|
109
110
|
|
|
@@ -156,7 +157,7 @@ const set = {
|
|
|
156
157
|
...array,
|
|
157
158
|
|
|
158
159
|
isInstance(value) {
|
|
159
|
-
return value
|
|
160
|
+
return isSet(value);
|
|
160
161
|
},
|
|
161
162
|
};
|
|
162
163
|
|
|
@@ -1,6 +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
|
+
const { ENUM_SET_SIZE, isDate } = require('../util.js');
|
|
4
4
|
|
|
5
5
|
const missingEnum = (type) => {
|
|
6
6
|
const hint = `Type "${type}" needs a list of values: { type: '${type}', enum: [...] }`;
|
|
@@ -86,7 +86,7 @@ const date = {
|
|
|
86
86
|
compile() {
|
|
87
87
|
const { required } = this;
|
|
88
88
|
return (value, context, key) => {
|
|
89
|
-
if (value
|
|
89
|
+
if (isDate(value) && !Number.isNaN(value.getTime())) return;
|
|
90
90
|
if (!required && value == null) return;
|
|
91
91
|
issues.type(context, 'date', value, key);
|
|
92
92
|
};
|
|
@@ -131,8 +131,8 @@ const unknown = { ...any, scalar: 'unknown' };
|
|
|
131
131
|
const string = {
|
|
132
132
|
...scalar,
|
|
133
133
|
scalar: 'string',
|
|
134
|
-
rules: ['length', 'pattern'],
|
|
135
|
-
options: ['length', 'unicode', 'pattern'],
|
|
134
|
+
rules: ['length', 'pattern', 'format'],
|
|
135
|
+
options: ['length', 'unicode', 'pattern', 'format'],
|
|
136
136
|
};
|
|
137
137
|
const number = { ...scalar, scalar: 'number', rules: ['min', 'max'], options: ['min', 'max'] };
|
|
138
138
|
const bigint = { ...scalar, scalar: 'bigint', rules: ['min', 'max'], options: ['min', 'max'] };
|
package/src/prototypes/union.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
2
|
-
const { issues } = require('../issues.js');
|
|
2
|
+
const { issues, release } = require('../issues.js');
|
|
3
3
|
|
|
4
4
|
const invalidUnion = (reason) => new SchemaDefinitionError('ERR_INVALID_UNION', `Union ${reason}`);
|
|
5
5
|
|
|
@@ -129,7 +129,7 @@ const union = {
|
|
|
129
129
|
if (context.count === count) return;
|
|
130
130
|
context.issues.length = count;
|
|
131
131
|
context.count = count;
|
|
132
|
-
if (context.async !== null) context.async
|
|
132
|
+
if (context.async !== null) release(context.async, pending);
|
|
133
133
|
}
|
|
134
134
|
issues.union(context, expected, undefined, key);
|
|
135
135
|
};
|
package/src/result.js
CHANGED
|
@@ -104,6 +104,12 @@ class ValidationResult {
|
|
|
104
104
|
return hasBrand(error, 'ValidationResult');
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
// The result as data, for a log or a response: JSON.stringify(result) has
|
|
108
|
+
// the verdict beside the issues (`errors` is derived from them).
|
|
109
|
+
toJSON() {
|
|
110
|
+
return { valid: this.valid, issues: this.issues };
|
|
111
|
+
}
|
|
112
|
+
|
|
107
113
|
[INSPECT](depth, options, inspect) {
|
|
108
114
|
const { valid, errors, issues } = this;
|
|
109
115
|
return `ValidationResult ${inspect({ valid, errors, issues }, options)}`;
|
package/src/rules.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// the type check.
|
|
7
7
|
const { issues } = require('./issues.js');
|
|
8
8
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
9
|
+
const { isMap, isSet } = require('./util.js');
|
|
9
10
|
|
|
10
11
|
const invalidRule = (reason) => new SchemaDefinitionError('ERR_INVALID_RULE', reason);
|
|
11
12
|
|
|
@@ -52,11 +53,28 @@ const formatPattern = (value) => {
|
|
|
52
53
|
|
|
53
54
|
// The formatter of each rule, by name; the names are the rules that exist. A
|
|
54
55
|
// null-prototype dictionary: a definition key may be called `constructor`.
|
|
56
|
+
// The formats a string may name (`format: 'email'`): a null-prototype table
|
|
57
|
+
// of `{ test, examples }` entries, empty until `register()` of the formats
|
|
58
|
+
// subpath fills it (the core knows the rule, the subpath the formats), read
|
|
59
|
+
// when the field is built. A name the table lacks is a definition error with
|
|
60
|
+
// the hint, never a check that passes everything.
|
|
61
|
+
const FORMATS = Object.create(null);
|
|
62
|
+
|
|
63
|
+
const formatName = (value) => {
|
|
64
|
+
if (typeof value !== 'string') throw invalidRule('Rule "format" needs the name of a format');
|
|
65
|
+
if (FORMATS[value] === undefined) {
|
|
66
|
+
const hint = 'register() of @alexify/metaschema/formats';
|
|
67
|
+
throw invalidRule(`Rule "format" names a format that is not registered: "${value}" (${hint})`);
|
|
68
|
+
}
|
|
69
|
+
return value;
|
|
70
|
+
};
|
|
71
|
+
|
|
55
72
|
const FORMAT = Object.assign(Object.create(null), {
|
|
56
73
|
length: formatLength,
|
|
57
74
|
min: formatLimit('min'),
|
|
58
75
|
max: formatLimit('max'),
|
|
59
76
|
pattern: formatPattern,
|
|
77
|
+
format: formatName,
|
|
60
78
|
});
|
|
61
79
|
|
|
62
80
|
const notApplicable = (rule, type, rules) => {
|
|
@@ -92,8 +110,7 @@ const keyCount = (value) => {
|
|
|
92
110
|
// length of an array, the size of a Set or a Map, the own keys of an object.
|
|
93
111
|
const lengthOf = (value) => {
|
|
94
112
|
if (typeof value === 'string' || Array.isArray(value)) return value.length;
|
|
95
|
-
|
|
96
|
-
return name === 'Set' || name === 'Map' ? value.size : keyCount(value);
|
|
113
|
+
return isMap(value) || isSet(value) ? value.size : keyCount(value);
|
|
97
114
|
};
|
|
98
115
|
|
|
99
116
|
// A string field measures its units, or its code points when it asks for
|
|
@@ -145,11 +162,33 @@ const compileRange = (type) => {
|
|
|
145
162
|
};
|
|
146
163
|
};
|
|
147
164
|
|
|
165
|
+
// The units a pattern may be run over: `length.max` (twice it when the
|
|
166
|
+
// length counts code points, each at most two units), so that a string past
|
|
167
|
+
// the bound, reported for its length already, never reaches a pattern that
|
|
168
|
+
// backtracks over it; no limit without the bound.
|
|
169
|
+
const patternLimit = (type) => {
|
|
170
|
+
const max = type.length?.max;
|
|
171
|
+
if (max === undefined) return Infinity;
|
|
172
|
+
return type.unicode === true ? 2 * max : max;
|
|
173
|
+
};
|
|
174
|
+
|
|
148
175
|
const compilePattern = (type) => {
|
|
149
176
|
const { pattern } = type;
|
|
150
177
|
const { source } = pattern;
|
|
178
|
+
const limit = patternLimit(type);
|
|
151
179
|
return (value, context, key) => {
|
|
152
|
-
if (!pattern.test(value)) issues.pattern(context, source, key);
|
|
180
|
+
if (value.length <= limit && !pattern.test(value)) issues.pattern(context, source, key);
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// A format is the test the subpath registered under its name, run after the
|
|
185
|
+
// pattern and under the same bound.
|
|
186
|
+
const compileFormat = (type) => {
|
|
187
|
+
const { format } = type;
|
|
188
|
+
const { test } = FORMATS[format];
|
|
189
|
+
const limit = patternLimit(type);
|
|
190
|
+
return (value, context, key) => {
|
|
191
|
+
if (value.length <= limit && !test(value)) issues.format(context, format, key);
|
|
153
192
|
};
|
|
154
193
|
};
|
|
155
194
|
|
|
@@ -171,6 +210,7 @@ const ruleNames = (type) => {
|
|
|
171
210
|
const COMPILERS = Object.assign(Object.create(null), {
|
|
172
211
|
length: compileLength,
|
|
173
212
|
pattern: compilePattern,
|
|
213
|
+
format: compileFormat,
|
|
174
214
|
range: compileRange,
|
|
175
215
|
});
|
|
176
216
|
|
|
@@ -182,4 +222,13 @@ const compileRules = (type) => {
|
|
|
182
222
|
return checks;
|
|
183
223
|
};
|
|
184
224
|
|
|
185
|
-
module.exports = {
|
|
225
|
+
module.exports = {
|
|
226
|
+
FORMAT,
|
|
227
|
+
FORMATS,
|
|
228
|
+
notApplicable,
|
|
229
|
+
ruleNames,
|
|
230
|
+
compileRules,
|
|
231
|
+
patternLimit,
|
|
232
|
+
codePoints,
|
|
233
|
+
lengthOf,
|
|
234
|
+
};
|
package/src/schema.js
CHANGED
|
@@ -6,7 +6,7 @@ const { TYPES } = require('./types.js');
|
|
|
6
6
|
const { Preprocessor } = require('./preprocessor.js');
|
|
7
7
|
const { SchemaMetadata } = require('./metadata.js');
|
|
8
8
|
const { ValidationResult } = require('./result.js');
|
|
9
|
-
const { finalize, runValidate, settle } = require('./issues.js');
|
|
9
|
+
const { finalize, runValidate, settle, release } = require('./issues.js');
|
|
10
10
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
11
11
|
const { createStruct, isStruct, checkOf } = require('./struct.js');
|
|
12
12
|
const { warning, lintSchema } = require('./lint.js');
|
|
@@ -14,6 +14,7 @@ const {
|
|
|
14
14
|
PREPARE,
|
|
15
15
|
FINISH,
|
|
16
16
|
SERIALIZE,
|
|
17
|
+
COERCE,
|
|
17
18
|
infoOf,
|
|
18
19
|
apply,
|
|
19
20
|
looped,
|
|
@@ -59,6 +60,18 @@ const parsed = (context, output) => {
|
|
|
59
60
|
const standardize = (result) =>
|
|
60
61
|
result.valid ? { value: result.value } : { issues: result.issues };
|
|
61
62
|
|
|
63
|
+
// The walk of an async check: a throw out of it (a getter of the value that
|
|
64
|
+
// throws, the engine's limit on a pattern) leaves the promises the walk
|
|
65
|
+
// queued observed, so that none of them rejects unhandled.
|
|
66
|
+
const walkAsync = (schema, value, context) => {
|
|
67
|
+
try {
|
|
68
|
+
schema[RUN](value, context);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
release(context.async, 0);
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
62
75
|
class Schema extends SchemaMetadata {
|
|
63
76
|
// The merged type table of the attached namespaces, rebuilt only when they
|
|
64
77
|
// change.
|
|
@@ -78,6 +91,11 @@ class Schema extends SchemaMetadata {
|
|
|
78
91
|
// What the passes of parse and serialize know about the schema, on first use.
|
|
79
92
|
#codec = null;
|
|
80
93
|
|
|
94
|
+
// Whether parse coerces the input unless the call says otherwise: the
|
|
95
|
+
// `coerce` of the kind metadata, read once (an own property would shadow
|
|
96
|
+
// the method the `./coerce` subpath installs).
|
|
97
|
+
#coerce = false;
|
|
98
|
+
|
|
81
99
|
static from(source, namespaces) {
|
|
82
100
|
return new Schema('', source, namespaces);
|
|
83
101
|
}
|
|
@@ -117,6 +135,7 @@ class Schema extends SchemaMetadata {
|
|
|
117
135
|
this.fields = createStruct(combined, preprocessor);
|
|
118
136
|
}
|
|
119
137
|
this.#tracked = isSchemaType && this.relations.size > 0;
|
|
138
|
+
this.#coerce = Object.hasOwn(this.custom, 'coerce') && this.custom.coerce === true;
|
|
120
139
|
this[RUN] = compileSchema(this);
|
|
121
140
|
const hook = Schema[HOOK];
|
|
122
141
|
if (hook !== undefined) hook(this);
|
|
@@ -204,57 +223,63 @@ class Schema extends SchemaMetadata {
|
|
|
204
223
|
return resultOf(context);
|
|
205
224
|
}
|
|
206
225
|
|
|
207
|
-
// The same check, with the validators that return a promise
|
|
208
|
-
// the walk, in field order.
|
|
226
|
+
// The same check, with the validators that return a promise in flight
|
|
227
|
+
// together and settled after the walk, in field order.
|
|
209
228
|
async checkAsync(source, options) {
|
|
210
229
|
const context = createContext(options, this.name, this.unknown);
|
|
211
230
|
context.async = [];
|
|
212
231
|
if (this.#tracked) context.source = source;
|
|
213
|
-
this
|
|
232
|
+
walkAsync(this, source, context);
|
|
214
233
|
if (context.async.length > 0) await settle(context);
|
|
215
234
|
return resultOf(context);
|
|
216
235
|
}
|
|
217
236
|
|
|
218
|
-
#pass(phase, source, context) {
|
|
237
|
+
#pass(phase, source, context, extra) {
|
|
219
238
|
if (this.#codec === null) this.#codec = infoOf(this);
|
|
220
|
-
|
|
239
|
+
const want = wantOf(phase, context) | extra;
|
|
240
|
+
return apply(this.#codec, this, source, context, undefined, phase, want);
|
|
221
241
|
}
|
|
222
242
|
|
|
223
|
-
//
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
|
|
227
|
-
|
|
243
|
+
// Validates a value and builds the value of the program from it: the input
|
|
244
|
+
// coerced (when the call, else the schema, asks for it) and the defaults
|
|
245
|
+
// filled in, the check, and on a valid value `unknown: 'strip'`, the
|
|
246
|
+
// decoders of its fields (the parts of a value before the value) and the
|
|
247
|
+
// schema's own `parse`. `{ valid, value, issues }`: the value is undefined
|
|
248
|
+
// when invalid, and the value given when there was nothing to apply; the
|
|
249
|
+
// value given is never written to. The objects met before the check are
|
|
250
|
+
// not the check's, and a value that loops through its references is
|
|
251
|
+
// checked as it was given. The pass before the check is written out here
|
|
252
|
+
// and in parseAsync, not in a method of its own: with coercion such a
|
|
253
|
+
// method no longer fit the bytecode V8 inlines into parse, and the call
|
|
254
|
+
// cost the JIT backend 13%.
|
|
255
|
+
parse(source, options) {
|
|
256
|
+
const context = createContext(options, this.name, this.unknown, true);
|
|
257
|
+
const own = options === undefined ? undefined : options.coerce;
|
|
258
|
+
const coerce = own === undefined ? this.#coerce : own;
|
|
259
|
+
const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
|
|
228
260
|
const value = looped(context) ? source : prepared;
|
|
229
261
|
context.seen = null;
|
|
230
262
|
if (this.#tracked) context.source = value;
|
|
231
|
-
return value;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// Validates a value and builds the value of the program from it: the
|
|
235
|
-
// defaults fill the missing keys, the check runs, and a valid value goes
|
|
236
|
-
// through `unknown: 'strip'`, the decoders of its fields (the parts of a
|
|
237
|
-
// value before the value) and the schema's own `parse`. `{ valid, value,
|
|
238
|
-
// issues }`: the value is undefined when invalid, and the value given when
|
|
239
|
-
// there was nothing to apply; the value given is never written to.
|
|
240
|
-
parse(source, options) {
|
|
241
|
-
const context = createContext(options, this.name, this.unknown, true);
|
|
242
|
-
const value = this.#prepare(source, context);
|
|
243
263
|
this[RUN](value, context);
|
|
244
|
-
const output = context.count === 0 ? this.#pass(FINISH, value, context) : undefined;
|
|
264
|
+
const output = context.count === 0 ? this.#pass(FINISH, value, context, 0) : undefined;
|
|
245
265
|
return parsed(context, output);
|
|
246
266
|
}
|
|
247
267
|
|
|
248
268
|
async parseAsync(source, options) {
|
|
249
269
|
const context = createContext(options, this.name, this.unknown, true);
|
|
250
270
|
context.async = [];
|
|
251
|
-
const
|
|
252
|
-
this
|
|
271
|
+
const own = options === undefined ? undefined : options.coerce;
|
|
272
|
+
const coerce = own === undefined ? this.#coerce : own;
|
|
273
|
+
const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
|
|
274
|
+
const value = looped(context) ? source : prepared;
|
|
275
|
+
context.seen = null;
|
|
276
|
+
if (this.#tracked) context.source = value;
|
|
277
|
+
walkAsync(this, value, context);
|
|
253
278
|
if (context.async.length > 0) await settle(context);
|
|
254
279
|
let output;
|
|
255
280
|
if (context.count === 0) {
|
|
256
281
|
// Only a promise of the pass is awaited: a thenable in the value is data.
|
|
257
|
-
output = this.#pass(FINISH, value, context);
|
|
282
|
+
output = this.#pass(FINISH, value, context, 0);
|
|
258
283
|
if (output instanceof Promise) output = (await output).value;
|
|
259
284
|
}
|
|
260
285
|
return parsed(context, output);
|
|
@@ -265,7 +290,7 @@ class Schema extends SchemaMetadata {
|
|
|
265
290
|
// `options.check` the verdict of `check` over the result as well.
|
|
266
291
|
serialize(source, options) {
|
|
267
292
|
const context = createContext(options, this.name, this.unknown);
|
|
268
|
-
const value = this.#pass(SERIALIZE, source, context);
|
|
293
|
+
const value = this.#pass(SERIALIZE, source, context, 0);
|
|
269
294
|
if (options === undefined || options.check !== true) return { value };
|
|
270
295
|
context.seen = null;
|
|
271
296
|
if (this.#tracked) context.source = value;
|
package/src/snapshot.js
CHANGED
|
@@ -68,7 +68,7 @@ const entityOf = (schema) => {
|
|
|
68
68
|
} else out.type = fieldOf(fields);
|
|
69
69
|
const own = {};
|
|
70
70
|
// A `many` field is recorded with the indexes and is not one.
|
|
71
|
-
for (const key in indexes) if (indexes[key].many === undefined) own
|
|
71
|
+
for (const key in indexes) if (indexes[key].many === undefined) define(own, key, indexes[key]);
|
|
72
72
|
out.indexes = own;
|
|
73
73
|
out.relations = valueOf(Array.from(schema.relations));
|
|
74
74
|
return out;
|