@alexify/metaschema 3.1.0 → 3.2.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 +193 -1
- package/README.md +459 -20
- package/SECURITY.md +26 -7
- package/index.d.ts +120 -2
- package/package.json +38 -5
- package/src/codec.js +77 -43
- 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 +5 -9
- package/src/errors.js +9 -1
- package/src/formats/index.d.ts +19 -0
- package/src/formats/index.js +146 -0
- package/src/generators/fromjsonschema.js +11 -14
- package/src/generators/index.js +2 -1
- package/src/generators/jsonschema.js +2 -0
- package/src/issues.js +37 -20
- package/src/locales/en.js +11 -2
- package/src/locales/uk.js +10 -2
- package/src/metadata.js +3 -2
- 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 +1 -0
- package/src/model/restore.js +3 -3
- package/src/model/sample.js +6 -2
- package/src/model.js +5 -1
- package/src/preprocessor.js +1 -0
- 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 +17 -5
- 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 +14 -1
- package/src/util.js +18 -0
|
@@ -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');
|
|
@@ -59,6 +59,18 @@ const parsed = (context, output) => {
|
|
|
59
59
|
const standardize = (result) =>
|
|
60
60
|
result.valid ? { value: result.value } : { issues: result.issues };
|
|
61
61
|
|
|
62
|
+
// The walk of an async check: a throw out of it (a getter of the value that
|
|
63
|
+
// throws, the engine's limit on a pattern) leaves the promises the walk
|
|
64
|
+
// queued observed, so that none of them rejects unhandled.
|
|
65
|
+
const walkAsync = (schema, value, context) => {
|
|
66
|
+
try {
|
|
67
|
+
schema[RUN](value, context);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
release(context.async, 0);
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
62
74
|
class Schema extends SchemaMetadata {
|
|
63
75
|
// The merged type table of the attached namespaces, rebuilt only when they
|
|
64
76
|
// change.
|
|
@@ -204,13 +216,13 @@ class Schema extends SchemaMetadata {
|
|
|
204
216
|
return resultOf(context);
|
|
205
217
|
}
|
|
206
218
|
|
|
207
|
-
// The same check, with the validators that return a promise
|
|
208
|
-
// the walk, in field order.
|
|
219
|
+
// The same check, with the validators that return a promise in flight
|
|
220
|
+
// together and settled after the walk, in field order.
|
|
209
221
|
async checkAsync(source, options) {
|
|
210
222
|
const context = createContext(options, this.name, this.unknown);
|
|
211
223
|
context.async = [];
|
|
212
224
|
if (this.#tracked) context.source = source;
|
|
213
|
-
this
|
|
225
|
+
walkAsync(this, source, context);
|
|
214
226
|
if (context.async.length > 0) await settle(context);
|
|
215
227
|
return resultOf(context);
|
|
216
228
|
}
|
|
@@ -249,7 +261,7 @@ class Schema extends SchemaMetadata {
|
|
|
249
261
|
const context = createContext(options, this.name, this.unknown, true);
|
|
250
262
|
context.async = [];
|
|
251
263
|
const value = this.#prepare(source, context);
|
|
252
|
-
this
|
|
264
|
+
walkAsync(this, value, context);
|
|
253
265
|
if (context.async.length > 0) await settle(context);
|
|
254
266
|
let output;
|
|
255
267
|
if (context.count === 0) {
|
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;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
EachAsyncOptions,
|
|
3
|
+
EachOptions,
|
|
4
|
+
Infer,
|
|
5
|
+
InferOutput,
|
|
6
|
+
ParseEachOptions,
|
|
7
|
+
ParseResult,
|
|
8
|
+
RecordEntry,
|
|
9
|
+
Schema,
|
|
10
|
+
TransformOptions,
|
|
11
|
+
ValidationResult,
|
|
12
|
+
} from '../../index.js';
|
|
13
|
+
|
|
14
|
+
// `check` on every record of an iterable, as a generator of
|
|
15
|
+
// `{ index, record, result }` in the order of the records; the options are
|
|
16
|
+
// those of `check`, plus `maxInvalid`, the number of invalid records after
|
|
17
|
+
// which the iteration ends. A target that is not a Schema, or a source that
|
|
18
|
+
// is not iterable, is a `TypeError` with the code `ERR_INVALID_TARGET`.
|
|
19
|
+
export function checkEach<T>(
|
|
20
|
+
schema: Schema,
|
|
21
|
+
records: Iterable<T>,
|
|
22
|
+
options?: EachOptions,
|
|
23
|
+
): Generator<RecordEntry<T, ValidationResult>, void, undefined>;
|
|
24
|
+
|
|
25
|
+
// `parse` on every record of an iterable: the same, with the result of
|
|
26
|
+
// `parse` in each entry.
|
|
27
|
+
export function parseEach<T, D extends string | object>(
|
|
28
|
+
schema: Schema<D>,
|
|
29
|
+
records: Iterable<T>,
|
|
30
|
+
options?: ParseEachOptions,
|
|
31
|
+
): Generator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
|
|
32
|
+
|
|
33
|
+
// `checkAsync` on every record of a sync or async iterable, as an async
|
|
34
|
+
// generator in the order of the records, with up to `concurrency` records
|
|
35
|
+
// in flight (one by default).
|
|
36
|
+
export function checkEachAsync<T>(
|
|
37
|
+
schema: Schema,
|
|
38
|
+
records: Iterable<T> | AsyncIterable<T>,
|
|
39
|
+
options?: EachOptions & EachAsyncOptions,
|
|
40
|
+
): AsyncGenerator<RecordEntry<T, ValidationResult>, void, undefined>;
|
|
41
|
+
|
|
42
|
+
// `parseAsync` on every record of a sync or async iterable: the same, with
|
|
43
|
+
// the result of `parseAsync` in each entry.
|
|
44
|
+
export function parseEachAsync<T, D extends string | object>(
|
|
45
|
+
schema: Schema<D>,
|
|
46
|
+
records: Iterable<T> | AsyncIterable<T>,
|
|
47
|
+
options?: ParseEachOptions & EachAsyncOptions,
|
|
48
|
+
): AsyncGenerator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
|
|
49
|
+
|
|
50
|
+
// A TransformStream over the records of a stream: a valid record goes on as
|
|
51
|
+
// its parsed value (`mode: 'parse'`, the default) or as it is
|
|
52
|
+
// (`mode: 'check'`); an invalid one is handed to `onInvalid` and dropped, or
|
|
53
|
+
// ends the stream with a `TypeError` of the code `ERR_INVALID_RECORD` (with
|
|
54
|
+
// `index`, `record` and `result` on it) when there is no `onInvalid` or
|
|
55
|
+
// `maxInvalid` is reached. `async: true` runs the async methods.
|
|
56
|
+
export function transform<D extends string | object>(
|
|
57
|
+
schema: Schema<D>,
|
|
58
|
+
options: TransformOptions & { mode: 'check' },
|
|
59
|
+
): TransformStream<unknown, Infer<D>>;
|
|
60
|
+
export function transform<D extends string | object>(
|
|
61
|
+
schema: Schema<D>,
|
|
62
|
+
options?: TransformOptions,
|
|
63
|
+
): TransformStream<unknown, InferOutput<D>>;
|
|
64
|
+
|
|
65
|
+
// Installs `schema.checkEach`, `schema.parseEach`, `schema.checkEachAsync`,
|
|
66
|
+
// `schema.parseEachAsync` and `schema.transform`. Once per process; later
|
|
67
|
+
// calls do nothing.
|
|
68
|
+
export function register(): void;
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// The `./stream` subpath: a schema over a sequence of records. `checkEach`
|
|
2
|
+
// and `parseEach` run `check` or `parse` on every record of an iterable and
|
|
3
|
+
// yield `{ index, record, result }` in the order of the records; the async
|
|
4
|
+
// pair does the same over a sync or async iterable with `checkAsync` or
|
|
5
|
+
// `parseAsync`, keeping up to `concurrency` records in flight; `transform`
|
|
6
|
+
// is a TransformStream that lets the valid records (or their parsed values)
|
|
7
|
+
// through and reports the others. Kept out of the core entry so that a
|
|
8
|
+
// program that validates one value at a time does not carry it; `register()`
|
|
9
|
+
// installs the methods on Schema for the programs that want them.
|
|
10
|
+
const { hasBrand } = require('../util.js');
|
|
11
|
+
const { abandon } = require('../issues.js');
|
|
12
|
+
const { invalidTarget, invalidOption: invalid } = require('../errors.js');
|
|
13
|
+
const { Schema } = require('../schema.js');
|
|
14
|
+
|
|
15
|
+
const optionsOf = (options) => {
|
|
16
|
+
if (options === undefined || (options !== null && typeof options === 'object')) return options;
|
|
17
|
+
throw invalid('options', 'an object', options);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// How many invalid records end the iteration: a whole number, or no limit.
|
|
21
|
+
const limitOf = (options) => {
|
|
22
|
+
const limit = optionsOf(options)?.maxInvalid;
|
|
23
|
+
if (limit === undefined) return Infinity;
|
|
24
|
+
if ((Number.isInteger(limit) || limit === Infinity) && limit >= 1) return limit;
|
|
25
|
+
throw invalid('maxInvalid', 'an integer of at least 1', limit);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// How many records an async iteration keeps in flight: one unless asked.
|
|
29
|
+
const widthOf = (options) => {
|
|
30
|
+
const width = options?.concurrency;
|
|
31
|
+
if (width === undefined) return 1;
|
|
32
|
+
if (Number.isInteger(width) && width >= 1) return width;
|
|
33
|
+
throw invalid('concurrency', 'an integer of at least 1', width);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const modeOf = (options) => {
|
|
37
|
+
const mode = options?.mode;
|
|
38
|
+
if (mode === undefined) return 'parse';
|
|
39
|
+
if (mode === 'parse' || mode === 'check') return mode;
|
|
40
|
+
throw invalid('mode', '"parse" or "check"', mode);
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const asyncOf = (options) => {
|
|
44
|
+
const async = options?.async;
|
|
45
|
+
if (async === undefined || typeof async === 'boolean') return async === true;
|
|
46
|
+
throw invalid('async', 'a boolean', async);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const callbackOf = (options) => {
|
|
50
|
+
const onInvalid = options?.onInvalid;
|
|
51
|
+
if (onInvalid === undefined || typeof onInvalid === 'function') return onInvalid;
|
|
52
|
+
throw invalid('onInvalid', 'a function', onInvalid);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const schemaOf = (schema) => {
|
|
56
|
+
if (!hasBrand(schema, 'Schema')) throw invalidTarget('A Schema is expected');
|
|
57
|
+
return schema;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// A sequence of records: anything with an iterator, or an async one where
|
|
61
|
+
// the iteration is async. A string is iterable and surely a mistake.
|
|
62
|
+
const recordsOf = (records, async) => {
|
|
63
|
+
const iterable =
|
|
64
|
+
records !== null &&
|
|
65
|
+
records !== undefined &&
|
|
66
|
+
typeof records !== 'string' &&
|
|
67
|
+
(typeof records[Symbol.iterator] === 'function' ||
|
|
68
|
+
(async && typeof records[Symbol.asyncIterator] === 'function'));
|
|
69
|
+
if (!iterable) throw invalidTarget('An iterable of records is expected');
|
|
70
|
+
return records;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// The method of the schema a function of the subpath runs on each record.
|
|
74
|
+
const CHECK = (schema, record, options) => schema.check(record, options);
|
|
75
|
+
const PARSE = (schema, record, options) => schema.parse(record, options);
|
|
76
|
+
const CHECK_ASYNC = (schema, record, options) => schema.checkAsync(record, options);
|
|
77
|
+
const PARSE_ASYNC = (schema, record, options) => schema.parseAsync(record, options);
|
|
78
|
+
|
|
79
|
+
// One record after the other. The entry of a record carries its position,
|
|
80
|
+
// since an iterator has none, and the record itself, since a stream cannot
|
|
81
|
+
// be read again. The options are handed to check or parse as given (they
|
|
82
|
+
// read the keys they know), so nothing is allocated per record beyond what
|
|
83
|
+
// the check itself allocates and the entry.
|
|
84
|
+
const each = function* (schema, records, options, limit, call) {
|
|
85
|
+
let failed = 0;
|
|
86
|
+
let index = 0;
|
|
87
|
+
for (const record of records) {
|
|
88
|
+
const result = call(schema, record, options);
|
|
89
|
+
yield { index, record, result };
|
|
90
|
+
index += 1;
|
|
91
|
+
if (!result.valid && (failed += 1) >= limit) return;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// The async pair over a sync or async iterable: up to `width` records are
|
|
96
|
+
// checked at once, the entries come out in the order of the records, and the
|
|
97
|
+
// promises still in flight when the iteration ends early (`maxInvalid`, a
|
|
98
|
+
// consumer that stops, a record whose parse throws) are observed, never
|
|
99
|
+
// awaited. The queue is as long as `width`, which is small by design.
|
|
100
|
+
const eachAsync = async function* (schema, records, options, limit, width, call) {
|
|
101
|
+
const queue = [];
|
|
102
|
+
let failed = 0;
|
|
103
|
+
let index = 0;
|
|
104
|
+
try {
|
|
105
|
+
for await (const record of records) {
|
|
106
|
+
const result = call(schema, record, options);
|
|
107
|
+
// Observed from the start: a record that rejects while an earlier one
|
|
108
|
+
// is still awaited would reject unhandled before its turn (the await
|
|
109
|
+
// of its entry still throws it).
|
|
110
|
+
abandon(result);
|
|
111
|
+
queue.push({ index, record, result });
|
|
112
|
+
index += 1;
|
|
113
|
+
if (queue.length < width) continue;
|
|
114
|
+
const entry = queue.shift();
|
|
115
|
+
entry.result = await entry.result;
|
|
116
|
+
yield entry;
|
|
117
|
+
if (!entry.result.valid && (failed += 1) >= limit) return;
|
|
118
|
+
}
|
|
119
|
+
while (queue.length > 0) {
|
|
120
|
+
const entry = queue.shift();
|
|
121
|
+
entry.result = await entry.result;
|
|
122
|
+
yield entry;
|
|
123
|
+
if (!entry.result.valid && (failed += 1) >= limit) return;
|
|
124
|
+
}
|
|
125
|
+
} finally {
|
|
126
|
+
for (let at = 0; at < queue.length; at += 1) abandon(queue[at].result);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const checkEach = (schema, records, options) =>
|
|
131
|
+
each(schemaOf(schema), recordsOf(records, false), options, limitOf(options), CHECK);
|
|
132
|
+
|
|
133
|
+
const parseEach = (schema, records, options) =>
|
|
134
|
+
each(schemaOf(schema), recordsOf(records, false), options, limitOf(options), PARSE);
|
|
135
|
+
|
|
136
|
+
const checkEachAsync = (schema, records, options) => {
|
|
137
|
+
const limit = limitOf(options);
|
|
138
|
+
return eachAsync(
|
|
139
|
+
schemaOf(schema),
|
|
140
|
+
recordsOf(records, true),
|
|
141
|
+
options,
|
|
142
|
+
limit,
|
|
143
|
+
widthOf(options),
|
|
144
|
+
CHECK_ASYNC,
|
|
145
|
+
);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const parseEachAsync = (schema, records, options) => {
|
|
149
|
+
const limit = limitOf(options);
|
|
150
|
+
return eachAsync(
|
|
151
|
+
schemaOf(schema),
|
|
152
|
+
recordsOf(records, true),
|
|
153
|
+
options,
|
|
154
|
+
limit,
|
|
155
|
+
widthOf(options),
|
|
156
|
+
PARSE_ASYNC,
|
|
157
|
+
);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// The error a stream ends with: the record, its position and its result
|
|
161
|
+
// travel on it, since the stream carries them no further.
|
|
162
|
+
const invalidRecord = (index, record, result) => {
|
|
163
|
+
const error = new TypeError(`Record ${index} is invalid`);
|
|
164
|
+
error.code = 'ERR_INVALID_RECORD';
|
|
165
|
+
error.index = index;
|
|
166
|
+
error.record = record;
|
|
167
|
+
error.result = result;
|
|
168
|
+
return error;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
// A TransformStream over the records of a stream: a valid record goes on as
|
|
172
|
+
// its parsed value (or as it is, in `check` mode); an invalid one is handed
|
|
173
|
+
// to `onInvalid` and dropped, or ends the stream with the error when there
|
|
174
|
+
// is no `onInvalid` or `maxInvalid` is reached. A stream that ends looks
|
|
175
|
+
// complete to what reads it, so it cannot stop quietly as a generator does.
|
|
176
|
+
// The stream handles one record at a time, so the async methods settle in
|
|
177
|
+
// order too.
|
|
178
|
+
const transform = (schema, options) => {
|
|
179
|
+
schemaOf(schema);
|
|
180
|
+
const limit = limitOf(options);
|
|
181
|
+
const mode = modeOf(options);
|
|
182
|
+
const async = asyncOf(options);
|
|
183
|
+
const onInvalid = callbackOf(options);
|
|
184
|
+
const parse = mode === 'parse';
|
|
185
|
+
const call = async ? (parse ? PARSE_ASYNC : CHECK_ASYNC) : parse ? PARSE : CHECK;
|
|
186
|
+
let failed = 0;
|
|
187
|
+
let index = 0;
|
|
188
|
+
const settle = (record, result, controller) => {
|
|
189
|
+
const at = index;
|
|
190
|
+
index += 1;
|
|
191
|
+
if (result.valid) {
|
|
192
|
+
controller.enqueue(parse ? result.value : record);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
failed += 1;
|
|
196
|
+
if (onInvalid !== undefined) onInvalid(record, result, at);
|
|
197
|
+
if (onInvalid === undefined || failed >= limit) {
|
|
198
|
+
controller.error(invalidRecord(at, record, result));
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
return new TransformStream({
|
|
202
|
+
transform(record, controller) {
|
|
203
|
+
const result = call(schema, record, options);
|
|
204
|
+
if (!async) return settle(record, result, controller);
|
|
205
|
+
return result.then((settled) => settle(record, settled, controller));
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
// Installed like class members: not enumerable. A copy per subpath rather
|
|
211
|
+
// than a helper of the core: the core is measured on its own, the subpaths
|
|
212
|
+
// on top of it.
|
|
213
|
+
const install = (target, members) => {
|
|
214
|
+
const descriptors = Object.getOwnPropertyDescriptors(members);
|
|
215
|
+
for (const name in descriptors) {
|
|
216
|
+
descriptors[name].enumerable = false;
|
|
217
|
+
Object.defineProperty(target, name, descriptors[name]);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
let registered = false;
|
|
222
|
+
|
|
223
|
+
// Adds `schema.checkEach`, `schema.parseEach`, `schema.checkEachAsync`,
|
|
224
|
+
// `schema.parseEachAsync` and `schema.transform`. Once per process.
|
|
225
|
+
const register = () => {
|
|
226
|
+
if (registered) return;
|
|
227
|
+
registered = true;
|
|
228
|
+
install(Schema.prototype, {
|
|
229
|
+
checkEach(records, options) {
|
|
230
|
+
return checkEach(this, records, options);
|
|
231
|
+
},
|
|
232
|
+
parseEach(records, options) {
|
|
233
|
+
return parseEach(this, records, options);
|
|
234
|
+
},
|
|
235
|
+
checkEachAsync(records, options) {
|
|
236
|
+
return checkEachAsync(this, records, options);
|
|
237
|
+
},
|
|
238
|
+
parseEachAsync(records, options) {
|
|
239
|
+
return parseEachAsync(this, records, options);
|
|
240
|
+
},
|
|
241
|
+
transform(options) {
|
|
242
|
+
return transform(this, options);
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
module.exports = { checkEach, parseEach, checkEachAsync, parseEachAsync, transform, register };
|
package/src/struct.js
CHANGED
|
@@ -131,7 +131,7 @@ const createStruct = (defs, prep) => {
|
|
|
131
131
|
const calculated = [];
|
|
132
132
|
for (const key of Object.keys(defs)) {
|
|
133
133
|
const entry = defs[key];
|
|
134
|
-
const { field, required } = formatters.key(key
|
|
134
|
+
const { field, required } = formatters.key(key);
|
|
135
135
|
try {
|
|
136
136
|
const { Type, defs: typeDefs } = prep.parse(entry);
|
|
137
137
|
if (!Type) {
|
package/src/types.js
CHANGED
|
@@ -7,6 +7,7 @@ const { tuple } = require('./prototypes/tuple.js');
|
|
|
7
7
|
const { union } = require('./prototypes/union.js');
|
|
8
8
|
const { json } = require('./prototypes/json.js');
|
|
9
9
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
10
|
+
const { firstKey, isFirstUpper } = require('./metautil.js');
|
|
10
11
|
|
|
11
12
|
const PROTOTYPES = {
|
|
12
13
|
...scalars,
|
|
@@ -58,6 +59,18 @@ const TYPES = createTypes(PROTOTYPES);
|
|
|
58
59
|
|
|
59
60
|
const createRegistry = () => createTypes(PROTOTYPES);
|
|
60
61
|
|
|
62
|
+
// Whether a dictionary of fields reads as a struct under the first-key rule
|
|
63
|
+
// (`preprocessor.js`): the first key that starts with a letter is a kind
|
|
64
|
+
// when capitalized, the long form when it is `type` and a shorthand when it
|
|
65
|
+
// is a type name of the registry; a struct that reads otherwise needs the
|
|
66
|
+
// `schema` shorthand around it. What generates a definition asks here.
|
|
67
|
+
const readsAsStruct = (fields, types = TYPES) => {
|
|
68
|
+
const first = firstKey(fields);
|
|
69
|
+
if (first === undefined) return true;
|
|
70
|
+
const key = first.endsWith('?') ? first.slice(0, -1) : first;
|
|
71
|
+
return key !== 'type' && types[key] === undefined && !isFirstUpper(key);
|
|
72
|
+
};
|
|
73
|
+
|
|
61
74
|
// The own keys of the metadata given, as data: the table has no prototype.
|
|
62
75
|
const updateTypeMetadata = (Type, metadata) => {
|
|
63
76
|
Object.assign(Type.metadata, metadata);
|
|
@@ -124,4 +137,4 @@ const typeFactory = (customTypes, registry = TYPES) => {
|
|
|
124
137
|
return registry;
|
|
125
138
|
};
|
|
126
139
|
|
|
127
|
-
module.exports = { TYPES, createRegistry, typeFactory };
|
|
140
|
+
module.exports = { TYPES, createRegistry, readsAsStruct, typeFactory };
|
package/src/util.js
CHANGED
|
@@ -9,6 +9,21 @@ const INSPECT = Symbol.for('nodejs.util.inspect.custom');
|
|
|
9
9
|
|
|
10
10
|
const hasBrand = (value, name) => value?.[BRAND] === name;
|
|
11
11
|
|
|
12
|
+
// A built-in is recognised by the name of its constructor, which nothing
|
|
13
|
+
// renames, and by its shape, which a value parsed from JSON cannot fake: an
|
|
14
|
+
// own key called `constructor` holding `{ name: 'Map' }` is data, and
|
|
15
|
+
// iterating such a value, or calling `getTime` on it, would throw out of a
|
|
16
|
+
// check. The name is tested first, since most values fail it at once.
|
|
17
|
+
const iterableNamed = (name) => (value) =>
|
|
18
|
+
value?.constructor?.name === name && typeof value[Symbol.iterator] === 'function';
|
|
19
|
+
|
|
20
|
+
const isMap = iterableNamed('Map');
|
|
21
|
+
|
|
22
|
+
const isSet = iterableNamed('Set');
|
|
23
|
+
|
|
24
|
+
const isDate = (value) =>
|
|
25
|
+
value?.constructor?.name === 'Date' && typeof value.getTime === 'function';
|
|
26
|
+
|
|
12
27
|
// A JavaScript identifier: what generated code may write as `object.key` and
|
|
13
28
|
// a TypeScript declaration as a bare name.
|
|
14
29
|
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
@@ -77,6 +92,9 @@ module.exports = {
|
|
|
77
92
|
BRAND,
|
|
78
93
|
INSPECT,
|
|
79
94
|
hasBrand,
|
|
95
|
+
isMap,
|
|
96
|
+
isSet,
|
|
97
|
+
isDate,
|
|
80
98
|
IDENTIFIER,
|
|
81
99
|
define,
|
|
82
100
|
RUN,
|