@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,34 @@
|
|
|
1
|
+
import type { CoerceOptions, Coercion, FieldType, Schema } from '../../index.js';
|
|
2
|
+
|
|
3
|
+
// A converter: the value of a field of its type read from what the input
|
|
4
|
+
// gave, or the value itself when it cannot be read (the check then reports
|
|
5
|
+
// it as given). It never throws on purpose: a throw is taken as "cannot".
|
|
6
|
+
// Declared with the core (`ModelOptions.coercions` takes them too).
|
|
7
|
+
export type { Coercion };
|
|
8
|
+
|
|
9
|
+
// The converters by type name: the built-in ones (`string`, `number`,
|
|
10
|
+
// `integer`, `bigint`, `boolean`, `date`, `enum`, `array`, `set`, `map`) and
|
|
11
|
+
// the program's own, once `register()` ran.
|
|
12
|
+
export const COERCIONS: { readonly [name: string]: Coercion | undefined };
|
|
13
|
+
|
|
14
|
+
// The value with the conversions of the schema applied, and its defaults:
|
|
15
|
+
// the pass parse runs before its check with coercion on, nothing checked.
|
|
16
|
+
// The value given is never written to, and comes back itself when nothing
|
|
17
|
+
// changed. Needs `register()`: without it a conversion is a TypeError with
|
|
18
|
+
// `code: 'ERR_NOT_REGISTERED'`.
|
|
19
|
+
export function coerce(schema: Schema, value: unknown, options?: CoerceOptions): unknown;
|
|
20
|
+
|
|
21
|
+
// The options of `register`: `onError` is told of a converter that threw
|
|
22
|
+
// (the value is left to the check as if the converter could not read it, so
|
|
23
|
+
// a bug in a converter of the program would look the same without it).
|
|
24
|
+
export interface RegisterOptions {
|
|
25
|
+
onError?: (error: unknown, field: FieldType) => void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Fills the table with the built-in converters and the program's own, by
|
|
29
|
+
// type name, once per name and process-wide (another function under a
|
|
30
|
+
// registered name is `ERR_COERCION_REGISTERED`, a name that is not one of a
|
|
31
|
+
// type or an entry that is not a function `ERR_INVALID_COERCION`; every
|
|
32
|
+
// entry is checked before any is written), and adds
|
|
33
|
+
// `schema.coerce(value, options)`. Importing the subpath registers nothing.
|
|
34
|
+
export function register(custom?: Record<string, Coercion>, options?: RegisterOptions): void;
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
// The `./coerce` subpath: the converters of coercion, by type name. The core
|
|
2
|
+
// has the policy (`coerce` of a parse call, of the kind metadata, of a field)
|
|
3
|
+
// and the step in the pass before the check; it converts nothing until
|
|
4
|
+
// register() installed the table here. The converters are strict: a string
|
|
5
|
+
// is a number only when it is written as one, a boolean only as `true`,
|
|
6
|
+
// `false`, `1` or `0`, a date only with its zone, and the empty string is
|
|
7
|
+
// never converted. A value a converter cannot read comes back as it was, so
|
|
8
|
+
// the check reports it as given.
|
|
9
|
+
const { hasBrand, isSet, isMap } = require('../util.js');
|
|
10
|
+
const { isFirstLower } = require('../metautil.js');
|
|
11
|
+
const { Schema } = require('../schema.js');
|
|
12
|
+
const { createContext } = require('../context.js');
|
|
13
|
+
const { COERCE, COERCION, PREPARE, infoOf, apply, wantOf, looped } = require('../codec.js');
|
|
14
|
+
const { SchemaDefinitionError, invalidTarget, invalidOption } = require('../errors.js');
|
|
15
|
+
|
|
16
|
+
// The integer digits and the fraction are told apart by the dot alone:
|
|
17
|
+
// `\d+\.?\d*` reads a run of digits two ways and is quadratic on a run
|
|
18
|
+
// that ends in something else.
|
|
19
|
+
const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
20
|
+
const INTEGER = /^[+-]?\d+$/;
|
|
21
|
+
const ISO =
|
|
22
|
+
/^(\d{4})-(\d{2})-(\d{2})(?:[Tt ]([01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d))?$/;
|
|
23
|
+
const SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
24
|
+
|
|
25
|
+
const toNumber = (value) => {
|
|
26
|
+
if (typeof value === 'string') {
|
|
27
|
+
if (!DECIMAL.test(value)) return value;
|
|
28
|
+
const number = Number(value);
|
|
29
|
+
return Number.isFinite(number) ? number : value;
|
|
30
|
+
}
|
|
31
|
+
if (typeof value === 'bigint' && value >= -SAFE && value <= SAFE) return Number(value);
|
|
32
|
+
return value;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const toInteger = (value) => {
|
|
36
|
+
const number = toNumber(value);
|
|
37
|
+
return Number.isSafeInteger(number) ? number : value;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const toBigint = (value) => {
|
|
41
|
+
if (typeof value === 'string') return INTEGER.test(value) ? BigInt(value) : value;
|
|
42
|
+
return Number.isSafeInteger(value) ? BigInt(value) : value;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const toBoolean = (value) => {
|
|
46
|
+
if (value === 'true' || value === '1' || value === 1) return true;
|
|
47
|
+
if (value === 'false' || value === '0' || value === 0) return false;
|
|
48
|
+
return value;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const isLeap = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
52
|
+
|
|
53
|
+
const daysIn = (year, month) => {
|
|
54
|
+
if (month === 2) return isLeap(year) ? 29 : 28;
|
|
55
|
+
return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// A calendar date (midnight UTC) or a date-time with its zone: a local time
|
|
59
|
+
// would depend on the zone of the server. The engine rolls `2026-02-31`
|
|
60
|
+
// over to March, so the day is checked here.
|
|
61
|
+
const toDate = (value) => {
|
|
62
|
+
if (typeof value === 'number') {
|
|
63
|
+
const date = new Date(value);
|
|
64
|
+
return Number.isNaN(date.getTime()) ? value : date;
|
|
65
|
+
}
|
|
66
|
+
if (typeof value !== 'string') return value;
|
|
67
|
+
const match = ISO.exec(value);
|
|
68
|
+
if (match === null) return value;
|
|
69
|
+
const month = Number(match[2]);
|
|
70
|
+
const day = Number(match[3]);
|
|
71
|
+
if (month < 1 || month > 12 || day < 1 || day > daysIn(Number(match[1]), month)) return value;
|
|
72
|
+
const text = match[4] === undefined ? value : `${value.slice(0, 10)}T${value.slice(11)}`;
|
|
73
|
+
const date = new Date(text.toUpperCase());
|
|
74
|
+
return Number.isNaN(date.getTime()) ? value : date;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const toText = (value) => {
|
|
78
|
+
const type = typeof value;
|
|
79
|
+
if (type === 'number') return Number.isFinite(value) ? String(value) : value;
|
|
80
|
+
return type === 'bigint' || type === 'boolean' ? String(value) : value;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const isPrimitive = (value) => {
|
|
84
|
+
const type = typeof value;
|
|
85
|
+
return type === 'number' || type === 'boolean' || type === 'bigint';
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// The member a value is written as: a string for a number, a boolean or a
|
|
89
|
+
// bigint member, or one of those for a string member.
|
|
90
|
+
const toEnum = (value, field) => {
|
|
91
|
+
const members = field.enum;
|
|
92
|
+
if (members.includes(value)) return value;
|
|
93
|
+
const text = typeof value === 'string';
|
|
94
|
+
if (!text && !isPrimitive(value)) return value;
|
|
95
|
+
for (const member of members) {
|
|
96
|
+
if (text ? isPrimitive(member) && String(member) === value : member === String(value)) {
|
|
97
|
+
return member;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
// The same, with the members and their written forms indexed once for the
|
|
104
|
+
// field: a visit of a large enum is a lookup, not a scan.
|
|
105
|
+
const enumConverterOf = (field) => {
|
|
106
|
+
const members = new Set(field.enum);
|
|
107
|
+
const written = new Map();
|
|
108
|
+
const strings = new Set();
|
|
109
|
+
for (const member of field.enum) {
|
|
110
|
+
if (typeof member === 'string') strings.add(member);
|
|
111
|
+
else if (isPrimitive(member)) {
|
|
112
|
+
const text = String(member);
|
|
113
|
+
if (!written.has(text)) written.set(text, member);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return (value) => {
|
|
117
|
+
if (members.has(value)) return value;
|
|
118
|
+
if (typeof value === 'string') return written.has(value) ? written.get(value) : value;
|
|
119
|
+
if (!isPrimitive(value)) return value;
|
|
120
|
+
const text = String(value);
|
|
121
|
+
return strings.has(text) ? text : value;
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
// A single value where a list is expected (`?tag=a` against `?tag=a&tag=b`).
|
|
126
|
+
const isItem = (value) => (typeof value === 'string' ? value !== '' : isPrimitive(value));
|
|
127
|
+
|
|
128
|
+
const toArray = (value) => {
|
|
129
|
+
if (isSet(value)) return Array.from(value);
|
|
130
|
+
return isItem(value) ? [value] : value;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const toSet = (value) => {
|
|
134
|
+
if (Array.isArray(value)) return new Set(value);
|
|
135
|
+
return isItem(value) ? new Set([value]) : value;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const isPairs = (value) => {
|
|
139
|
+
for (const pair of value) if (!Array.isArray(pair) || pair.length !== 2) return false;
|
|
140
|
+
return true;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// A plain object of any realm: a Set, a Date or a typed array has a
|
|
144
|
+
// prototype in between, and its entries are not the entries of a map.
|
|
145
|
+
const isPlain = (value) => {
|
|
146
|
+
const prototype = Object.getPrototypeOf(value);
|
|
147
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// A plain object or a list of pairs; the keys of a map of numbers that are
|
|
151
|
+
// written as numbers become numbers.
|
|
152
|
+
const toMap = (value, field) => {
|
|
153
|
+
if (value === null || typeof value !== 'object') return value;
|
|
154
|
+
const list = Array.isArray(value);
|
|
155
|
+
if (list ? !isPairs(value) : !isPlain(value)) return value;
|
|
156
|
+
const map = new Map();
|
|
157
|
+
for (const pair of list ? value : Object.entries(value)) {
|
|
158
|
+
const key = field.key === 'number' && typeof pair[0] === 'string' ? toNumber(pair[0]) : pair[0];
|
|
159
|
+
map.set(key, pair[1]);
|
|
160
|
+
}
|
|
161
|
+
return map;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const BUILT_IN = {
|
|
165
|
+
string: toText,
|
|
166
|
+
number: toNumber,
|
|
167
|
+
integer: toInteger,
|
|
168
|
+
bigint: toBigint,
|
|
169
|
+
boolean: toBoolean,
|
|
170
|
+
date: toDate,
|
|
171
|
+
enum: toEnum,
|
|
172
|
+
array: toArray,
|
|
173
|
+
set: toSet,
|
|
174
|
+
map: toMap,
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// The table: a converter by type name, `(value, field) => value`.
|
|
178
|
+
const COERCIONS = Object.create(null);
|
|
179
|
+
|
|
180
|
+
const invalidCoercion = (reason) => new SchemaDefinitionError('ERR_INVALID_COERCION', reason);
|
|
181
|
+
|
|
182
|
+
// The converter of a field: its type's, or the one of the type it is an
|
|
183
|
+
// alias of (`{ money: { js: 'number' } }` converts as a number); an alias
|
|
184
|
+
// names a type registered before it, so the chain ends. The core keeps what
|
|
185
|
+
// is resolved on the info of the node, under the version of the table.
|
|
186
|
+
// The converter a model of the field's own gave for a type name
|
|
187
|
+
// (`new Model(types, entities, database, { coercions })`), before the
|
|
188
|
+
// process-wide one: the models among the namespaces of the schema.
|
|
189
|
+
const ownConverterOf = (root, name) => {
|
|
190
|
+
for (const namespace of root.namespaces) {
|
|
191
|
+
const own = namespace.coercions;
|
|
192
|
+
if (own != null && own[name] !== undefined) return own[name];
|
|
193
|
+
}
|
|
194
|
+
return undefined;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const converterOf = (field) => {
|
|
198
|
+
let Type = field.constructor;
|
|
199
|
+
let name = field.type;
|
|
200
|
+
for (;;) {
|
|
201
|
+
const converter = ownConverterOf(field.root, name) ?? COERCIONS[name];
|
|
202
|
+
if (converter !== undefined) return converter;
|
|
203
|
+
const js = Type?.source?.js;
|
|
204
|
+
if (typeof js !== 'string') return null;
|
|
205
|
+
name = js;
|
|
206
|
+
Type = field.root.types[js];
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
// The hook `register({ onError })` gives: told of a converter that threw,
|
|
211
|
+
// with the field, since the value is left to the check as if the converter
|
|
212
|
+
// could not read it, and a bug in a converter of the program would look the
|
|
213
|
+
// same.
|
|
214
|
+
let onError = null;
|
|
215
|
+
|
|
216
|
+
// What the core asks once per node of a coercing pass (and again after a
|
|
217
|
+
// register()): the converter of the node, closed over it, or null for a
|
|
218
|
+
// node that is not a field (a schema, a struct) or whose type has none. A
|
|
219
|
+
// converter that throws leaves the value to the check.
|
|
220
|
+
const resolve = (node) => {
|
|
221
|
+
const converter = hasBrand(node, 'Type') ? converterOf(node) : null;
|
|
222
|
+
if (converter === null) return null;
|
|
223
|
+
const run = converter === toEnum ? enumConverterOf(node) : converter;
|
|
224
|
+
return (value) => {
|
|
225
|
+
try {
|
|
226
|
+
return run(value, node);
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (onError !== null) onError(error, node);
|
|
229
|
+
return value;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
// An entry of the program: the name of a type, a function, and not another
|
|
235
|
+
// function under a name the table has (a built-in name included).
|
|
236
|
+
const check = (name, converter) => {
|
|
237
|
+
if (!isFirstLower(name)) throw invalidCoercion(`Converter "${name}" needs the name of a type`);
|
|
238
|
+
if (typeof converter !== 'function') {
|
|
239
|
+
throw invalidCoercion(`Converter "${name}" must be a function`);
|
|
240
|
+
}
|
|
241
|
+
const known = COERCIONS[name] ?? BUILT_IN[name];
|
|
242
|
+
if (known !== undefined && known !== converter) {
|
|
243
|
+
const reason = `Converter "${name}" is registered already with another function`;
|
|
244
|
+
throw new SchemaDefinitionError('ERR_COERCION_REGISTERED', reason);
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
// The paths of the keys the pass changed (a value converted, a default
|
|
249
|
+
// filled in), read off the output beside the input: a container is copied
|
|
250
|
+
// only where a part of it changed, and a part given back as it is is the
|
|
251
|
+
// same reference, so what differs is what changed. The paths are those of
|
|
252
|
+
// an issue (`PropertyKey[]`, the root `[]`).
|
|
253
|
+
const report = (input, output, path, paths) => {
|
|
254
|
+
if (output === input) return;
|
|
255
|
+
const container = output !== null && typeof output === 'object';
|
|
256
|
+
const given = input !== null && typeof input === 'object';
|
|
257
|
+
if (!container || !given) {
|
|
258
|
+
paths.push(path);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (Array.isArray(output)) {
|
|
262
|
+
if (!Array.isArray(input)) {
|
|
263
|
+
paths.push(path);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
for (let index = 0; index < output.length; index += 1) {
|
|
267
|
+
report(input[index], output[index], [...path, index], paths);
|
|
268
|
+
}
|
|
269
|
+
} else if (isMap(output)) {
|
|
270
|
+
if (!isMap(input)) {
|
|
271
|
+
paths.push(path);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
for (const pair of output) report(input.get(pair[0]), pair[1], [...path, pair[0]], paths);
|
|
275
|
+
} else if (!isPlain(output) || !isPlain(input)) {
|
|
276
|
+
paths.push(path);
|
|
277
|
+
} else {
|
|
278
|
+
for (const key of Object.keys(output)) {
|
|
279
|
+
const before = Object.hasOwn(input, key) ? input[key] : undefined;
|
|
280
|
+
report(before, output[key], [...path, key], paths);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
// The value with the conversions of the schema applied, and its defaults:
|
|
286
|
+
// the pass parse runs before its check, with coercion on and nothing
|
|
287
|
+
// checked. The value given is never written to; it comes back itself when
|
|
288
|
+
// nothing changed, and as it was when it loops through its references.
|
|
289
|
+
// `options.report`, an array, is given the path of every key the pass
|
|
290
|
+
// changed.
|
|
291
|
+
const coerce = (schema, value, options) => {
|
|
292
|
+
if (!hasBrand(schema, 'Schema')) throw invalidTarget('A Schema is expected');
|
|
293
|
+
const context = createContext(options, schema.name, schema.unknown, true);
|
|
294
|
+
const paths = options === undefined ? undefined : options.report;
|
|
295
|
+
if (paths !== undefined && !Array.isArray(paths)) {
|
|
296
|
+
throw invalidOption('report', 'an array', paths);
|
|
297
|
+
}
|
|
298
|
+
const want = wantOf(PREPARE, context) | COERCE;
|
|
299
|
+
const out = apply(infoOf(schema), schema, value, context, undefined, PREPARE, want);
|
|
300
|
+
const result = looped(context) ? value : out;
|
|
301
|
+
if (paths !== undefined) report(value, result, [], paths);
|
|
302
|
+
return result;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
// Installed like class members: not enumerable. A copy per subpath rather
|
|
306
|
+
// than a helper of the core: the core is measured on its own, the subpaths
|
|
307
|
+
// on top of it.
|
|
308
|
+
const install = (target, members) => {
|
|
309
|
+
const descriptors = Object.getOwnPropertyDescriptors(members);
|
|
310
|
+
for (const name in descriptors) {
|
|
311
|
+
descriptors[name].enumerable = false;
|
|
312
|
+
Object.defineProperty(target, name, descriptors[name]);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
let installed = false;
|
|
317
|
+
|
|
318
|
+
// Fills the table with the built-in converters and the program's own, once
|
|
319
|
+
// per name, process-wide (another function under a registered name is
|
|
320
|
+
// ERR_COERCION_REGISTERED; a converter of an alias type is the way to read a
|
|
321
|
+
// type differently), and adds `schema.coerce(value, options)`. Every entry
|
|
322
|
+
// is checked before any is written, so a call that throws leaves the table
|
|
323
|
+
// as it was. `options.onError` is told of a converter that threw.
|
|
324
|
+
const register = (custom = {}, settings = {}) => {
|
|
325
|
+
if (custom === null || typeof custom !== 'object' || Array.isArray(custom)) {
|
|
326
|
+
throw invalidCoercion('The converters must be an object of functions by type name');
|
|
327
|
+
}
|
|
328
|
+
if (settings === null || typeof settings !== 'object') {
|
|
329
|
+
throw invalidCoercion('The options of register must be an object');
|
|
330
|
+
}
|
|
331
|
+
const hook = settings.onError;
|
|
332
|
+
if (hook !== undefined && typeof hook !== 'function') {
|
|
333
|
+
throw invalidCoercion('Option "onError" must be a function');
|
|
334
|
+
}
|
|
335
|
+
const names = Object.keys(custom);
|
|
336
|
+
for (const name of names) check(name, custom[name]);
|
|
337
|
+
for (const name of Object.keys(BUILT_IN)) COERCIONS[name] = BUILT_IN[name];
|
|
338
|
+
for (const name of names) COERCIONS[name] = custom[name];
|
|
339
|
+
if (hook !== undefined) onError = hook;
|
|
340
|
+
COERCION.resolve = resolve;
|
|
341
|
+
COERCION.installed = true;
|
|
342
|
+
COERCION.version += 1;
|
|
343
|
+
if (installed) return;
|
|
344
|
+
installed = true;
|
|
345
|
+
install(Schema.prototype, {
|
|
346
|
+
coerce(value, options) {
|
|
347
|
+
return coerce(this, value, options);
|
|
348
|
+
},
|
|
349
|
+
});
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
module.exports = { COERCIONS, coerce, register };
|
package/src/compile/code.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The builder of the generated source. Generated code holds identifiers,
|
|
2
2
|
// numbers, booleans and JSON strings only: a regular expression, a Set, a
|
|
3
3
|
// function, a nested check or a dictionary of known keys goes into the scope
|
|
4
|
-
// and is reached by name (the ajv and schemasafe rule
|
|
4
|
+
// and is reached by name (the ajv and schemasafe rule), so
|
|
5
5
|
// nothing taken from a schema is ever part of the source text.
|
|
6
6
|
const { IDENTIFIER } = require('../util.js');
|
|
7
7
|
|
package/src/compile/emit.js
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
// Generated code names three things: `v` the value, `c` the context and `k`
|
|
9
9
|
// the key the root was called with. Every other identifier is fresh.
|
|
10
10
|
const { ENUM_SET_SIZE } = require('../util.js');
|
|
11
|
-
const { issues, runValidate } = require('../issues.js');
|
|
12
|
-
const { codePoints, lengthOf, ruleNames } = require('../rules.js');
|
|
11
|
+
const { issues, runValidate, release } = require('../issues.js');
|
|
12
|
+
const { FORMATS, codePoints, lengthOf, ruleNames, patternLimit } = require('../rules.js');
|
|
13
13
|
const { STRUCT, isStruct } = require('../struct.js');
|
|
14
14
|
const scalars = require('../prototypes/scalars.js');
|
|
15
15
|
const collections = require('../prototypes/collections.js');
|
|
@@ -53,6 +53,14 @@ const typeIssue = (state, expected, x, key) =>
|
|
|
53
53
|
|
|
54
54
|
const notObject = (x) => `${x} === null || typeof ${x} !== "object" || Array.isArray(${x})`;
|
|
55
55
|
|
|
56
|
+
// A built-in by the name of its constructor and by its shape, as util.js
|
|
57
|
+
// tests it: the name alone is what a value parsed from JSON can carry.
|
|
58
|
+
const isDateCode = (x) =>
|
|
59
|
+
`${x}?.constructor?.name === "Date" && typeof ${x}.getTime === "function"`;
|
|
60
|
+
|
|
61
|
+
const isIterableCode = (x, name) =>
|
|
62
|
+
`${x}?.constructor?.name === ${quote(name)} && typeof ${x}[Symbol.iterator] === "function"`;
|
|
63
|
+
|
|
56
64
|
// The conditions of the bounds a field has.
|
|
57
65
|
const outside = (state, x, min, max) => {
|
|
58
66
|
const parts = [];
|
|
@@ -77,14 +85,30 @@ const emitLength = (type, x, key, state) => {
|
|
|
77
85
|
code.push('}');
|
|
78
86
|
};
|
|
79
87
|
|
|
88
|
+
// The condition that keeps a pattern or a format off a string past
|
|
89
|
+
// length.max, as the closures do.
|
|
90
|
+
const withinLength = (type, x, code) => {
|
|
91
|
+
const limit = patternLimit(type);
|
|
92
|
+
return limit === Infinity ? '' : `${x}.length <= ${code.value(limit)} && `;
|
|
93
|
+
};
|
|
94
|
+
|
|
80
95
|
const emitPattern = (type, x, key, state) => {
|
|
81
96
|
const { code } = state;
|
|
82
97
|
const { pattern } = type;
|
|
83
|
-
code.push(`if (!${code.ref(pattern)}.test(${x})) {`);
|
|
98
|
+
code.push(`if (${withinLength(type, x, code)}!${code.ref(pattern)}.test(${x})) {`);
|
|
84
99
|
record(state, issue(state, 'pattern', `${quote(pattern.source)}, ${keyOf(key)}`));
|
|
85
100
|
code.push('}');
|
|
86
101
|
};
|
|
87
102
|
|
|
103
|
+
const emitFormat = (type, x, key, state) => {
|
|
104
|
+
const { code } = state;
|
|
105
|
+
const { format } = type;
|
|
106
|
+
const { test } = FORMATS[format];
|
|
107
|
+
code.push(`if (${withinLength(type, x, code)}!${code.ref(test)}(${x})) {`);
|
|
108
|
+
record(state, issue(state, 'format', `${quote(format)}, ${keyOf(key)}`));
|
|
109
|
+
code.push('}');
|
|
110
|
+
};
|
|
111
|
+
|
|
88
112
|
const emitRange = (type, x, key, state) => {
|
|
89
113
|
const { code } = state;
|
|
90
114
|
const { min, max } = type;
|
|
@@ -97,6 +121,7 @@ const emitRange = (type, x, key, state) => {
|
|
|
97
121
|
const RULES = Object.assign(Object.create(null), {
|
|
98
122
|
length: emitLength,
|
|
99
123
|
pattern: emitPattern,
|
|
124
|
+
format: emitFormat,
|
|
100
125
|
range: emitRange,
|
|
101
126
|
});
|
|
102
127
|
|
|
@@ -155,7 +180,7 @@ const emitInteger = (type, x, key, state) =>
|
|
|
155
180
|
typed(type, x, key, state, `!Number.isInteger(${x})`, typeIssue(state, 'integer', x, key));
|
|
156
181
|
|
|
157
182
|
const emitDate = (type, x, key, state) => {
|
|
158
|
-
const fails = `!(${x}
|
|
183
|
+
const fails = `!(${isDateCode(x)} && !Number.isNaN(${x}.getTime()))`;
|
|
159
184
|
typed(type, x, key, state, fails, typeIssue(state, 'date', x, key));
|
|
160
185
|
};
|
|
161
186
|
|
|
@@ -228,7 +253,7 @@ const emitObject = (type, x, key, state) => {
|
|
|
228
253
|
const emitMap = (type, x, key, state) => {
|
|
229
254
|
const { code } = state;
|
|
230
255
|
const failure = typeIssue(state, type.type, x, key);
|
|
231
|
-
typed(type, x, key, state,
|
|
256
|
+
typed(type, x, key, state, `!(${isIterableCode(x, 'Map')})`, failure, () => {
|
|
232
257
|
if (type.required) {
|
|
233
258
|
code.push(`if (${x}.size === 0) {`);
|
|
234
259
|
record(state, issue(state, 'required', keyOf(key)));
|
|
@@ -258,7 +283,7 @@ const emitMap = (type, x, key, state) => {
|
|
|
258
283
|
const emitList = (type, x, key, state) => {
|
|
259
284
|
const { code } = state;
|
|
260
285
|
const set = type.isInstance === collections.set.isInstance;
|
|
261
|
-
const fails = set ?
|
|
286
|
+
const fails = set ? `!(${isIterableCode(x, 'Set')})` : `!Array.isArray(${x})`;
|
|
262
287
|
typed(type, x, key, state, fails, typeIssue(state, type.type, x, key), () => {
|
|
263
288
|
const children = inside(state, key);
|
|
264
289
|
const index = code.name('i');
|
|
@@ -413,7 +438,7 @@ const emitUnion = (type, x, key, state) => {
|
|
|
413
438
|
code.push('}');
|
|
414
439
|
code.push(`if (c.count === ${before}) break ${label};`);
|
|
415
440
|
code.push(`c.issues.length = ${before}; c.count = ${before};`);
|
|
416
|
-
code.push(`if (c.async !== null) c.async
|
|
441
|
+
code.push(`if (c.async !== null) ${code.ref(release)}(c.async, ${pending});`);
|
|
417
442
|
}
|
|
418
443
|
const names = [];
|
|
419
444
|
for (let index = 0; index < branches.length; index += 1) names.push(nameOf(branches[index]));
|
package/src/compile/index.d.ts
CHANGED
|
@@ -36,3 +36,9 @@ export function register(options?: CompileOptions): void;
|
|
|
36
36
|
|
|
37
37
|
// Whether this environment allows code generation from strings; probed once.
|
|
38
38
|
export function canEval(): boolean;
|
|
39
|
+
|
|
40
|
+
// Whether the check of a schema (of every entity of a model) runs generated
|
|
41
|
+
// code now: what `compile` reported, asked later. False for a schema built
|
|
42
|
+
// before `register()` and after `{ jit: false }`; a target that is neither
|
|
43
|
+
// a Schema nor a Model is a `TypeError`.
|
|
44
|
+
export function compiled(target: Schema | Model): boolean;
|
package/src/compile/index.js
CHANGED
|
@@ -153,6 +153,17 @@ const compile = (target, options = {}) => {
|
|
|
153
153
|
return error === undefined ? { accelerated: true } : { accelerated: false, error };
|
|
154
154
|
};
|
|
155
155
|
|
|
156
|
+
// Whether the check of a schema (of every entity of a model) runs the
|
|
157
|
+
// generated code now: what `compile` reported, asked later.
|
|
158
|
+
const compiled = (target) => {
|
|
159
|
+
const schemas = schemasOf(target);
|
|
160
|
+
for (let index = 0; index < schemas.length; index += 1) {
|
|
161
|
+
const schema = schemas[index];
|
|
162
|
+
if (!ORIGINAL.has(schema) || schema[RUN] === ORIGINAL.get(schema)) return false;
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
};
|
|
166
|
+
|
|
156
167
|
// Compiles every schema built from now on, with these options; a later call
|
|
157
168
|
// replaces them, and `{ jit: false }` stops it. A schema built before the
|
|
158
169
|
// call is not touched. In the default mode `onFallback` is told of every
|
|
@@ -173,4 +184,4 @@ const register = (options = {}) => {
|
|
|
173
184
|
};
|
|
174
185
|
};
|
|
175
186
|
|
|
176
|
-
module.exports = { compile, register, canEval };
|
|
187
|
+
module.exports = { compile, compiled, register, canEval };
|
package/src/context.js
CHANGED
|
@@ -5,17 +5,12 @@
|
|
|
5
5
|
const en = require('./locales/en.js');
|
|
6
6
|
|
|
7
7
|
const { NONE } = require('./issues.js');
|
|
8
|
+
const { invalidOption: invalid } = require('./errors.js');
|
|
8
9
|
|
|
9
10
|
// The limit when there is none: the largest small integer, so the comparison
|
|
10
11
|
// with the count on every field stays an integer comparison.
|
|
11
12
|
const UNLIMITED = 2 ** 30 - 1;
|
|
12
13
|
|
|
13
|
-
const shown = (value) =>
|
|
14
|
-
typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
|
|
15
|
-
|
|
16
|
-
const invalid = (name, expected, value) =>
|
|
17
|
-
new TypeError(`${name} must be ${expected}, got ${shown(value)}`);
|
|
18
|
-
|
|
19
14
|
// A whole number of issues, or no limit at all.
|
|
20
15
|
const maxErrorsOf = (maxErrors) => {
|
|
21
16
|
const valid = (Number.isInteger(maxErrors) || maxErrors === Infinity) && maxErrors >= 1;
|
|
@@ -97,6 +92,11 @@ const configure = (context, options, parsing) => {
|
|
|
97
92
|
if (options.unknown !== undefined) context.unknown = unknownOf(options.unknown, parsing);
|
|
98
93
|
if (options.references !== undefined) context.references = referencesOf(options.references);
|
|
99
94
|
if (options.root !== undefined) context.root = rootOf(options.root);
|
|
95
|
+
// Read by parse and parseAsync themselves, checked here with the rest.
|
|
96
|
+
const { coerce } = options;
|
|
97
|
+
if (parsing && coerce !== undefined && typeof coerce !== 'boolean') {
|
|
98
|
+
throw invalid('coerce', 'a boolean', coerce);
|
|
99
|
+
}
|
|
100
100
|
};
|
|
101
101
|
|
|
102
102
|
// One object shape for every context: the keys are always present, in this
|
|
@@ -126,9 +126,10 @@ const createContext = (options, name = '', unknown = 'reject', parsing = false)
|
|
|
126
126
|
references: 'kind',
|
|
127
127
|
root: name,
|
|
128
128
|
messages: en,
|
|
129
|
-
// The validators that returned a promise, in field order,
|
|
130
|
-
//
|
|
131
|
-
// where such a promise is an
|
|
129
|
+
// The validators that returned a promise, in field order, and the ones
|
|
130
|
+
// kept uncalled over them, settled after the walk by checkAsync and
|
|
131
|
+
// parseAsync; null in a synchronous check, where such a promise is an
|
|
132
|
+
// error.
|
|
132
133
|
async: null,
|
|
133
134
|
// The context parse tries the branches of a plain union in, made at the
|
|
134
135
|
// first such union of a pass and reused for the rest; null in a check.
|
|
@@ -141,4 +142,4 @@ const createContext = (options, name = '', unknown = 'reject', parsing = false)
|
|
|
141
142
|
return context;
|
|
142
143
|
};
|
|
143
144
|
|
|
144
|
-
module.exports = { createContext, UNLIMITED, MAX_DEPTH };
|
|
145
|
+
module.exports = { createContext, referencesOf, UNLIMITED, MAX_DEPTH };
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DeriveKeyOf,
|
|
3
|
+
DeriveOptions,
|
|
4
|
+
DerivedSchema,
|
|
5
|
+
ExtendDefinition,
|
|
6
|
+
ExtendedSchema,
|
|
7
|
+
KeyofDefinition,
|
|
8
|
+
OmitDefinition,
|
|
9
|
+
PartialDefinition,
|
|
10
|
+
PartialOptions,
|
|
11
|
+
PickDefinition,
|
|
12
|
+
RequiredDefinition,
|
|
13
|
+
RequiredOptions,
|
|
14
|
+
Schema,
|
|
15
|
+
StructGuardOf,
|
|
16
|
+
} from '../../index.js';
|
|
17
|
+
|
|
18
|
+
// Schemas made from a schema of a struct. Each builds a new Schema from the
|
|
19
|
+
// definition the source was built from: the source is never changed. A
|
|
20
|
+
// stored kind or a projection becomes a struct (without the id of the kind,
|
|
21
|
+
// unless the call names it), a memory kind keeps its metadata, the name is
|
|
22
|
+
// the source's unless `options.name`. A key the schema has no field of is
|
|
23
|
+
// `ERR_UNKNOWN_FIELD`, located in the schema; anything but a Schema of a
|
|
24
|
+
// struct is `ERR_INVALID_TARGET`.
|
|
25
|
+
|
|
26
|
+
// The fields named, in the order of the schema. The schema's own functions
|
|
27
|
+
// do not come along.
|
|
28
|
+
export function pick<
|
|
29
|
+
D extends string | object,
|
|
30
|
+
const K extends readonly DeriveKeyOf<D>[],
|
|
31
|
+
const O extends DeriveOptions = {},
|
|
32
|
+
>(
|
|
33
|
+
schema: Schema<D> & StructGuardOf<D>,
|
|
34
|
+
keys: K,
|
|
35
|
+
options?: O,
|
|
36
|
+
): DerivedSchema<D, PickDefinition<D, K[number], O>>;
|
|
37
|
+
|
|
38
|
+
// Every field but the ones named.
|
|
39
|
+
export function omit<
|
|
40
|
+
D extends string | object,
|
|
41
|
+
const K extends readonly DeriveKeyOf<D>[],
|
|
42
|
+
const O extends DeriveOptions = {},
|
|
43
|
+
>(
|
|
44
|
+
schema: Schema<D> & StructGuardOf<D>,
|
|
45
|
+
keys: K,
|
|
46
|
+
options?: O,
|
|
47
|
+
): DerivedSchema<D, OmitDefinition<D, K[number], O>>;
|
|
48
|
+
|
|
49
|
+
// Every field (or the ones in `options.keys`) optional, without its default
|
|
50
|
+
// unless `defaults: true`; `deep` goes into nested structs, not into
|
|
51
|
+
// collections, tuples, unions or references.
|
|
52
|
+
export function partial<
|
|
53
|
+
D extends string | object,
|
|
54
|
+
const O extends PartialOptions<DeriveKeyOf<D>> = {},
|
|
55
|
+
>(schema: Schema<D> & StructGuardOf<D>, options?: O): DerivedSchema<D, PartialDefinition<D, O>>;
|
|
56
|
+
|
|
57
|
+
// Every field (or the ones in `options.keys`) required; the defaults stay.
|
|
58
|
+
export function required<
|
|
59
|
+
D extends string | object,
|
|
60
|
+
const O extends RequiredOptions<DeriveKeyOf<D>> = {},
|
|
61
|
+
>(schema: Schema<D> & StructGuardOf<D>, options?: O): DerivedSchema<D, RequiredDefinition<D, O>>;
|
|
62
|
+
|
|
63
|
+
// The fields of the extension (an object of fields, or a Schema of a
|
|
64
|
+
// struct) over the schema's: one of the same name takes the place of the
|
|
65
|
+
// schema's, the others come after. `merge` of `./model` unifies instead. An
|
|
66
|
+
// extension whose definition is not known (an entity of a model) gives a
|
|
67
|
+
// `Schema` of an unknown one, as a source whose definition is not known does.
|
|
68
|
+
export function extend<
|
|
69
|
+
D extends string | object,
|
|
70
|
+
const X extends object,
|
|
71
|
+
const O extends DeriveOptions = {},
|
|
72
|
+
>(
|
|
73
|
+
schema: Schema<D> & StructGuardOf<D>,
|
|
74
|
+
extension: X,
|
|
75
|
+
options?: O,
|
|
76
|
+
): ExtendedSchema<D, X, ExtendDefinition<D, X, O>>;
|
|
77
|
+
|
|
78
|
+
// The names of the fields a value carries, as a schema of an enum.
|
|
79
|
+
export function keyof<D extends string | object>(
|
|
80
|
+
schema: Schema<D> & StructGuardOf<D>,
|
|
81
|
+
options?: DeriveOptions,
|
|
82
|
+
): DerivedSchema<D, KeyofDefinition<D>>;
|
|
83
|
+
|
|
84
|
+
// Adds the six as methods of Schema (`schema.omit(['id']).partial()`), not
|
|
85
|
+
// enumerable. Once per process; importing the subpath registers nothing.
|
|
86
|
+
export function register(): void;
|