@alexify/metaschema 3.4.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +162 -1
- package/README.md +22 -7
- package/SECURITY.md +5 -4
- package/index.d.ts +856 -460
- package/package.json +8 -6
- package/src/checks.js +72 -107
- package/src/codec.js +67 -58
- package/src/coerce/index.d.ts +31 -21
- package/src/coerce/index.js +64 -47
- package/src/compile/code.js +2 -2
- package/src/compile/emit.js +20 -31
- package/src/compile/index.d.ts +41 -25
- package/src/compile/index.js +45 -32
- package/src/context.js +10 -10
- package/src/definition/index.d.ts +10 -7
- package/src/definition/index.js +2 -1
- package/src/derive/index.d.ts +25 -17
- package/src/derive/index.js +14 -11
- package/src/errors.js +84 -59
- package/src/formats/index.d.ts +27 -21
- package/src/formats/index.js +15 -13
- package/src/generators/{fromjsonschema.js → from-json-schema.js} +170 -127
- package/src/generators/index.d.ts +23 -15
- package/src/generators/index.js +2 -2
- package/src/generators/{jsonschema.js → json-schema.js} +37 -43
- package/src/generators/typescript.js +9 -6
- package/src/index.js +2 -1
- package/src/issues.js +41 -42
- package/src/kinds.js +18 -16
- package/src/lint.js +15 -18
- package/src/locales/en.js +7 -7
- package/src/locales/uk.js +6 -6
- package/src/metadata.js +2 -2
- package/src/model/data.js +17 -20
- package/src/model/diff.js +29 -24
- package/src/model/index.d.ts +51 -35
- package/src/model/infer.js +69 -60
- package/src/model/merge.js +29 -18
- package/src/model/pattern.js +105 -102
- package/src/model/restore.js +24 -19
- package/src/model/sample.js +90 -100
- package/src/model.js +4 -2
- package/src/mongodb/bson.js +12 -12
- package/src/mongodb/document.js +7 -6
- package/src/mongodb/index.d.ts +54 -31
- package/src/mongodb/update.js +12 -9
- package/src/preprocessor.js +13 -13
- package/src/prototypes/abstract.js +8 -8
- package/src/prototypes/collections.js +7 -7
- package/src/prototypes/flags.js +1 -1
- package/src/prototypes/reference.js +3 -4
- package/src/prototypes/scalars.js +1 -1
- package/src/prototypes/schema.js +5 -6
- package/src/prototypes/tuple.js +6 -5
- package/src/prototypes/union.js +5 -4
- package/src/rules.js +23 -20
- package/src/runtime/browser.js +6 -1
- package/src/runtime/node.js +19 -2
- package/src/schema.js +15 -13
- package/src/snapshot.js +14 -12
- package/src/stream/index.d.ts +33 -21
- package/src/stream/index.js +37 -20
- package/src/struct.js +6 -6
- package/src/types.js +28 -22
- package/src/util.js +65 -64
- package/src/validation.js +10 -13
package/src/preprocessor.js
CHANGED
|
@@ -4,12 +4,15 @@ const { hasBrand, formatters, typeOf } = require('./util.js');
|
|
|
4
4
|
const { constants, isKindKey } = require('./kinds.js');
|
|
5
5
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
6
6
|
|
|
7
|
+
const BUILT_IN_KINDS = new Set(constants.KIND);
|
|
8
|
+
|
|
7
9
|
// The first key of an object decides what it is: a Schema or a built field is
|
|
8
10
|
// used as it is, a kind key (`isKindKey` of kinds.js: a name like `Entity`
|
|
9
11
|
// holding the metadata object) is a kind, `type` is the long form, a type
|
|
10
12
|
// name is that type's shorthand, and anything else is a nested struct, a
|
|
11
13
|
// capitalized key that is no kind (`PORT`, `Name: 'string'`) included.
|
|
12
|
-
const PARSERS =
|
|
14
|
+
const PARSERS = {
|
|
15
|
+
__proto__: null,
|
|
13
16
|
string: ['stringShorthand'],
|
|
14
17
|
object: [
|
|
15
18
|
'schemaInstance',
|
|
@@ -21,13 +24,10 @@ const PARSERS = Object.assign(Object.create(null), {
|
|
|
21
24
|
],
|
|
22
25
|
function: ['functionField'],
|
|
23
26
|
array: ['tupleShorthand'],
|
|
24
|
-
}
|
|
27
|
+
};
|
|
25
28
|
|
|
26
|
-
const invalid = (source,
|
|
27
|
-
new SchemaDefinitionError(
|
|
28
|
-
'ERR_INVALID_DEFINITION',
|
|
29
|
-
`Invalid definition: "${source}" of type ${srcType}`,
|
|
30
|
-
);
|
|
29
|
+
const invalid = (source, sourceType = typeOf(source)) =>
|
|
30
|
+
new SchemaDefinitionError(`Invalid definition: "${source}" of type ${sourceType}`);
|
|
31
31
|
|
|
32
32
|
class Preprocessor {
|
|
33
33
|
constructor(root) {
|
|
@@ -40,16 +40,16 @@ class Preprocessor {
|
|
|
40
40
|
// The first key of an object is read once here and handed to the parsers
|
|
41
41
|
// that look at it.
|
|
42
42
|
parse(source) {
|
|
43
|
-
const
|
|
44
|
-
const parsers = PARSERS[
|
|
43
|
+
const sourceType = typeOf(source);
|
|
44
|
+
const parsers = PARSERS[sourceType];
|
|
45
45
|
if (parsers) {
|
|
46
|
-
const first =
|
|
46
|
+
const first = sourceType === 'object' ? firstKey(source) : undefined;
|
|
47
47
|
for (const name of parsers) {
|
|
48
48
|
const result = this[name](source, first);
|
|
49
49
|
if (result) return result;
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
|
-
throw invalid(source,
|
|
52
|
+
throw invalid(source, sourceType);
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
// A Schema instance as a field: `{ schema: instance }` and the long form go
|
|
@@ -86,7 +86,7 @@ class Preprocessor {
|
|
|
86
86
|
return { Type: types.reference, defs };
|
|
87
87
|
}
|
|
88
88
|
if (!types[type]) {
|
|
89
|
-
throw new SchemaDefinitionError(
|
|
89
|
+
throw new SchemaDefinitionError(`Unknown type "${type}"`, { code: 'ALX_ERR_UNKNOWN_TYPE' });
|
|
90
90
|
}
|
|
91
91
|
const defs = { required, ...source };
|
|
92
92
|
return { Type: types[type], defs };
|
|
@@ -111,7 +111,7 @@ class Preprocessor {
|
|
|
111
111
|
const kind = toLowerCamel(first);
|
|
112
112
|
// A kind of the program's own is kept for the lint: metadata that reads
|
|
113
113
|
// as field definitions is most likely a field that was read as a kind.
|
|
114
|
-
if (!
|
|
114
|
+
if (!BUILT_IN_KINDS.has(kind)) {
|
|
115
115
|
if (this.kinds === null) this.kinds = [];
|
|
116
116
|
this.kinds.push([first, meta]);
|
|
117
117
|
}
|
|
@@ -16,18 +16,18 @@ const RESERVED = new Set([
|
|
|
16
16
|
'root',
|
|
17
17
|
]);
|
|
18
18
|
|
|
19
|
-
const reservedKey = (key) =>
|
|
20
|
-
new SchemaDefinitionError('ERR_RESERVED_KEY', `Key "${key}" is reserved in a field definition`);
|
|
21
|
-
|
|
22
19
|
// The options of a field that are flags: `nullable` (null in place of a
|
|
23
20
|
// value) and `coerce` (whether parse converts the input of its subtree).
|
|
24
21
|
const FLAGS = ['nullable', 'coerce'];
|
|
25
22
|
|
|
26
|
-
const
|
|
27
|
-
new SchemaDefinitionError(
|
|
23
|
+
const reservedKey = (key) =>
|
|
24
|
+
new SchemaDefinitionError(`Key "${key}" is reserved in a field definition`, {
|
|
25
|
+
code: 'ALX_ERR_RESERVED_KEY',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const invalidFlag = (key) => new SchemaDefinitionError(`Option "${key}" needs a boolean`);
|
|
28
29
|
|
|
29
|
-
const invalidCodec = (key) =>
|
|
30
|
-
new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a function`);
|
|
30
|
+
const invalidCodec = (key) => new SchemaDefinitionError(`Option "${key}" needs a function`);
|
|
31
31
|
|
|
32
32
|
// `parse` (the decoder) and `serialize` are read by parse and serialize, on
|
|
33
33
|
// any type; a definition that gave them anything else can never work.
|
|
@@ -105,4 +105,4 @@ class AbstractType {
|
|
|
105
105
|
|
|
106
106
|
AbstractType.prototype[BRAND] = 'Type';
|
|
107
107
|
|
|
108
|
-
module.exports = {
|
|
108
|
+
module.exports = { BUILD, AbstractType };
|
|
@@ -5,7 +5,7 @@ const { isMap, isSet } = require('../util.js');
|
|
|
5
5
|
// never match a key, and the JIT quotes the key type into its source.
|
|
6
6
|
const invalidKey = (type) => {
|
|
7
7
|
const reason = `Type "${type}" needs a key type of "string" or "number"`;
|
|
8
|
-
return new SchemaDefinitionError(
|
|
8
|
+
return new SchemaDefinitionError(reason);
|
|
9
9
|
};
|
|
10
10
|
|
|
11
11
|
// The collections: a dictionary (`object`, `map`) of a key type and a value
|
|
@@ -16,7 +16,7 @@ const object = {
|
|
|
16
16
|
options: ['key', 'value', 'length'],
|
|
17
17
|
kind: 'struct',
|
|
18
18
|
|
|
19
|
-
construct(def,
|
|
19
|
+
construct(def, preprocessor) {
|
|
20
20
|
const { type } = this;
|
|
21
21
|
const { [type]: short, key, value } = def;
|
|
22
22
|
let keyType = key;
|
|
@@ -32,8 +32,8 @@ const object = {
|
|
|
32
32
|
}
|
|
33
33
|
if (keyType !== 'string' && keyType !== 'number') throw invalidKey(type);
|
|
34
34
|
this.key = keyType;
|
|
35
|
-
const { Type, defs } =
|
|
36
|
-
this.value = new Type(defs,
|
|
35
|
+
const { Type, defs } = preprocessor.parse(valueDef);
|
|
36
|
+
this.value = new Type(defs, preprocessor);
|
|
37
37
|
},
|
|
38
38
|
|
|
39
39
|
isInstance(value) {
|
|
@@ -54,11 +54,11 @@ const array = {
|
|
|
54
54
|
rules: ['length'],
|
|
55
55
|
options: ['value', 'length'],
|
|
56
56
|
|
|
57
|
-
construct(def,
|
|
57
|
+
construct(def, preprocessor) {
|
|
58
58
|
const { type } = this;
|
|
59
59
|
const source = def[type] || def.value;
|
|
60
|
-
const { Type, defs } =
|
|
61
|
-
this.value = new Type(defs,
|
|
60
|
+
const { Type, defs } = preprocessor.parse(source);
|
|
61
|
+
this.value = new Type(defs, preprocessor);
|
|
62
62
|
},
|
|
63
63
|
|
|
64
64
|
isInstance(value) {
|
package/src/prototypes/flags.js
CHANGED
|
@@ -2,7 +2,7 @@ const { SchemaDefinitionError } = require('../errors.js');
|
|
|
2
2
|
|
|
3
3
|
const invalidFlags = (type) => {
|
|
4
4
|
const hint = `Type "${type}" needs a list of distinct names: { ${type}: ['read', 'write'] }`;
|
|
5
|
-
return new SchemaDefinitionError(
|
|
5
|
+
return new SchemaDefinitionError(hint);
|
|
6
6
|
};
|
|
7
7
|
|
|
8
8
|
// A set of named switches: an object whose keys are names of the list, each
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
2
2
|
|
|
3
|
-
const invalidEmbed = () =>
|
|
4
|
-
new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "embed" needs a boolean');
|
|
3
|
+
const invalidEmbed = () => new SchemaDefinitionError('Option "embed" needs a boolean');
|
|
5
4
|
|
|
6
5
|
// Whether a referenced value is the record itself (the graph view) or its
|
|
7
6
|
// id (the storage view): the mode of the check when it says so, otherwise
|
|
@@ -22,7 +21,7 @@ const reference = {
|
|
|
22
21
|
const target = def[key];
|
|
23
22
|
if (typeof target !== 'string' || target === '') {
|
|
24
23
|
const reason = `Reference "${key}" needs an entity name, got ${JSON.stringify(target)}`;
|
|
25
|
-
throw new SchemaDefinitionError('
|
|
24
|
+
throw new SchemaDefinitionError(reason, { code: 'ALX_ERR_INVALID_REFERENCE' });
|
|
26
25
|
}
|
|
27
26
|
if (this.embed !== undefined && typeof this.embed !== 'boolean') throw invalidEmbed();
|
|
28
27
|
// Read from the referencing side: a `many` field holds the many end of
|
|
@@ -34,4 +33,4 @@ const reference = {
|
|
|
34
33
|
},
|
|
35
34
|
};
|
|
36
35
|
|
|
37
|
-
module.exports = {
|
|
36
|
+
module.exports = { embeds, reference };
|
|
@@ -2,7 +2,7 @@ const { SchemaDefinitionError } = require('../errors.js');
|
|
|
2
2
|
|
|
3
3
|
const missingEnum = (type) => {
|
|
4
4
|
const hint = `Type "${type}" needs a list of values: { type: '${type}', enum: [...] }`;
|
|
5
|
-
return new SchemaDefinitionError('
|
|
5
|
+
return new SchemaDefinitionError(hint, { code: 'ALX_ERR_INVALID_ENUM' });
|
|
6
6
|
};
|
|
7
7
|
|
|
8
8
|
// The scalar types: what a field of each holds (its check is `COMPILE` of
|
package/src/prototypes/schema.js
CHANGED
|
@@ -4,7 +4,7 @@ const { SchemaDefinitionError } = require('../errors.js');
|
|
|
4
4
|
|
|
5
5
|
const missingSchema = (type) => {
|
|
6
6
|
const hint = `Type "${type}" needs a schema definition: { type: '${type}', schema: { ... } }`;
|
|
7
|
-
return new SchemaDefinitionError('
|
|
7
|
+
return new SchemaDefinitionError(hint, { code: 'ALX_ERR_MISSING_SCHEMA' });
|
|
8
8
|
};
|
|
9
9
|
|
|
10
10
|
const isDefinition = (value) =>
|
|
@@ -29,18 +29,17 @@ const schema = {
|
|
|
29
29
|
kind: 'struct',
|
|
30
30
|
options: ['schema'],
|
|
31
31
|
|
|
32
|
-
construct(defs,
|
|
32
|
+
construct(defs, preprocessor) {
|
|
33
33
|
const { schema: definition, required } = defs;
|
|
34
34
|
if (!isDefinition(definition)) throw missingSchema(this.type);
|
|
35
35
|
this.required = required ?? true;
|
|
36
36
|
if (hasBrand(definition, 'Schema')) {
|
|
37
|
-
|
|
37
|
+
preprocessor.root.updateFromSchema(definition);
|
|
38
38
|
this.schema = definition.fields;
|
|
39
|
-
adopt(this, definition.options);
|
|
40
|
-
return;
|
|
39
|
+
return void adopt(this, definition.options);
|
|
41
40
|
}
|
|
42
41
|
if (isStruct(definition)) this.schema = definition;
|
|
43
|
-
else this.schema = createStruct(definition,
|
|
42
|
+
else this.schema = createStruct(definition, preprocessor);
|
|
44
43
|
adopt(this, definition);
|
|
45
44
|
},
|
|
46
45
|
};
|
package/src/prototypes/tuple.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
const { formatters } = require('../util.js');
|
|
2
2
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
3
3
|
|
|
4
|
-
const invalidTuple = (reason) =>
|
|
4
|
+
const invalidTuple = (reason) =>
|
|
5
|
+
new SchemaDefinitionError(`Tuple ${reason}`, { code: 'ALX_ERR_INVALID_TUPLE' });
|
|
5
6
|
|
|
6
7
|
// A named element is `{ name: 'type' }`: one key that is not `type` or a type
|
|
7
8
|
// name, holding a type name (a string is no metadata of a kind, so `{ X:
|
|
@@ -20,15 +21,15 @@ const tuple = {
|
|
|
20
21
|
kind: 'struct',
|
|
21
22
|
options: ['value', 'tuple'],
|
|
22
23
|
|
|
23
|
-
construct(def,
|
|
24
|
+
construct(def, preprocessor) {
|
|
24
25
|
const elements = def.value || def.tuple;
|
|
25
26
|
if (!Array.isArray(elements)) throw invalidTuple('needs a list of element definitions');
|
|
26
27
|
const built = [];
|
|
27
28
|
for (let index = 0; index < elements.length; index += 1) {
|
|
28
29
|
const element = elements[index];
|
|
29
|
-
const key = nameOf(element,
|
|
30
|
+
const key = nameOf(element, preprocessor.types);
|
|
30
31
|
const source = key === null ? element : element[key];
|
|
31
|
-
const { Type, defs } =
|
|
32
|
+
const { Type, defs } = preprocessor.parse(source);
|
|
32
33
|
if (!Type) throw invalidTuple(`element ${index} cannot be a function`);
|
|
33
34
|
let name = null;
|
|
34
35
|
if (key !== null) {
|
|
@@ -36,7 +37,7 @@ const tuple = {
|
|
|
36
37
|
defs.required = (defs.required ?? true) && parsed.required;
|
|
37
38
|
name = parsed.field;
|
|
38
39
|
}
|
|
39
|
-
const type = new Type(defs,
|
|
40
|
+
const type = new Type(defs, preprocessor);
|
|
40
41
|
if (name !== null) type.name = name;
|
|
41
42
|
built.push(type);
|
|
42
43
|
}
|
package/src/prototypes/union.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
2
2
|
|
|
3
|
-
const invalidUnion = (reason) =>
|
|
3
|
+
const invalidUnion = (reason) =>
|
|
4
|
+
new SchemaDefinitionError(`Union ${reason}`, { code: 'ALX_ERR_INVALID_UNION' });
|
|
4
5
|
|
|
5
6
|
// The values of the discriminator field of a branch: the branch must be a
|
|
6
7
|
// struct whose field of that name is an enum, so the branch is known from
|
|
@@ -20,16 +21,16 @@ const union = {
|
|
|
20
21
|
kind: 'struct',
|
|
21
22
|
options: ['union', 'discriminator'],
|
|
22
23
|
|
|
23
|
-
construct(def,
|
|
24
|
+
construct(def, preprocessor) {
|
|
24
25
|
const branches = def.union;
|
|
25
26
|
if (!Array.isArray(branches) || branches.length === 0) {
|
|
26
27
|
throw invalidUnion('needs a list of branches: { union: [...] }');
|
|
27
28
|
}
|
|
28
29
|
const built = [];
|
|
29
30
|
for (let index = 0; index < branches.length; index += 1) {
|
|
30
|
-
const { Type, defs } =
|
|
31
|
+
const { Type, defs } = preprocessor.parse(branches[index]);
|
|
31
32
|
if (!Type) throw invalidUnion(`branch ${index} cannot be a function`);
|
|
32
|
-
built.push(new Type(defs,
|
|
33
|
+
built.push(new Type(defs, preprocessor));
|
|
33
34
|
}
|
|
34
35
|
this.union = built;
|
|
35
36
|
const { discriminator } = this;
|
package/src/rules.js
CHANGED
|
@@ -7,10 +7,25 @@
|
|
|
7
7
|
// check.
|
|
8
8
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
// The formatter of each rule, by name; the names are the rules that exist. A
|
|
11
|
+
// null-prototype dictionary: a definition key may be called `constructor`.
|
|
12
|
+
// The formats a string may name (`format: 'email'`): a null-prototype table
|
|
13
|
+
// of `{ test, examples }` entries, empty until `register()` of the formats
|
|
14
|
+
// subpath fills it (the core knows the rule, the subpath the formats), read
|
|
15
|
+
// when the field is built. A name the table lacks is a definition error with
|
|
16
|
+
// the hint, never a check that passes everything.
|
|
17
|
+
const FORMATS = Object.create(null);
|
|
18
|
+
|
|
19
|
+
// The entry a field's format named when the field was built: a format the
|
|
20
|
+
// program registers later under that name does not change the field, whose
|
|
21
|
+
// check is compiled on its first use.
|
|
22
|
+
const NAMED = new WeakMap();
|
|
23
|
+
|
|
24
|
+
const invalidRule = (reason, options) =>
|
|
25
|
+
new SchemaDefinitionError(reason, { ...options, code: 'ALX_ERR_INVALID_RULE' });
|
|
11
26
|
|
|
12
27
|
const invalidLength = (reason = 'needs a number, [min, max] or { min, max }') =>
|
|
13
|
-
new SchemaDefinitionError(
|
|
28
|
+
new SchemaDefinitionError(`Rule "length" ${reason}`, { code: 'ALX_ERR_INVALID_LENGTH' });
|
|
14
29
|
|
|
15
30
|
const isBound = (value) => value === undefined || typeof value === 'number';
|
|
16
31
|
|
|
@@ -46,24 +61,11 @@ const formatPattern = (value) => {
|
|
|
46
61
|
try {
|
|
47
62
|
return new RegExp(source, `${given}u`);
|
|
48
63
|
} catch (error) {
|
|
49
|
-
|
|
64
|
+
const reason = `Rule "pattern" is not a valid regular expression: ${error.message}`;
|
|
65
|
+
throw invalidRule(reason, { cause: error });
|
|
50
66
|
}
|
|
51
67
|
};
|
|
52
68
|
|
|
53
|
-
// The formatter of each rule, by name; the names are the rules that exist. A
|
|
54
|
-
// null-prototype dictionary: a definition key may be called `constructor`.
|
|
55
|
-
// The formats a string may name (`format: 'email'`): a null-prototype table
|
|
56
|
-
// of `{ test, examples }` entries, empty until `register()` of the formats
|
|
57
|
-
// subpath fills it (the core knows the rule, the subpath the formats), read
|
|
58
|
-
// when the field is built. A name the table lacks is a definition error with
|
|
59
|
-
// the hint, never a check that passes everything.
|
|
60
|
-
const FORMATS = Object.create(null);
|
|
61
|
-
|
|
62
|
-
// The entry a field's format named when the field was built: a format the
|
|
63
|
-
// program registers later under that name does not change the field, whose
|
|
64
|
-
// check is compiled on its first use.
|
|
65
|
-
const NAMED = new WeakMap();
|
|
66
|
-
|
|
67
69
|
const formatName = (value, type) => {
|
|
68
70
|
if (typeof value !== 'string') throw invalidRule('Rule "format" needs the name of a format');
|
|
69
71
|
if (FORMATS[value] === undefined) {
|
|
@@ -84,14 +86,15 @@ const formatDecimals = (value) => {
|
|
|
84
86
|
return value;
|
|
85
87
|
};
|
|
86
88
|
|
|
87
|
-
const FORMAT =
|
|
89
|
+
const FORMAT = {
|
|
90
|
+
__proto__: null,
|
|
88
91
|
length: formatLength,
|
|
89
92
|
min: formatLimit('min'),
|
|
90
93
|
max: formatLimit('max'),
|
|
91
94
|
pattern: formatPattern,
|
|
92
95
|
format: formatName,
|
|
93
96
|
decimals: formatDecimals,
|
|
94
|
-
}
|
|
97
|
+
};
|
|
95
98
|
|
|
96
99
|
// The bounds of a field leave room for a value: the definition is checked
|
|
97
100
|
// when the field is built, its check compiled later.
|
|
@@ -107,4 +110,4 @@ const notApplicable = (rule, type, rules) => {
|
|
|
107
110
|
return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
|
|
108
111
|
};
|
|
109
112
|
|
|
110
|
-
module.exports = {
|
|
113
|
+
module.exports = { FORMATS, formatOf, FORMAT, checkBounds, notApplicable };
|
package/src/runtime/browser.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
// Browser twin of ./node.js: the same interface, mapped in by the package.json
|
|
2
2
|
// `browser` field. There is no file system to write to, so it rejects.
|
|
3
3
|
|
|
4
|
-
const
|
|
4
|
+
const { SchemaUsageError } = require('../errors.js');
|
|
5
|
+
|
|
6
|
+
const writeFile = () => {
|
|
7
|
+
const message = 'saveTypes is not available in the browser';
|
|
8
|
+
return Promise.reject(new SchemaUsageError(message, { code: 'ALX_ERR_UNSUPPORTED_RUNTIME' }));
|
|
9
|
+
};
|
|
5
10
|
|
|
6
11
|
module.exports = { writeFile };
|
package/src/runtime/node.js
CHANGED
|
@@ -1,7 +1,24 @@
|
|
|
1
1
|
const fsp = require('node:fs').promises;
|
|
2
2
|
|
|
3
3
|
// The one file-system call of the package, behind `saveTypes` of the
|
|
4
|
-
// `./generators` subpath.
|
|
5
|
-
|
|
4
|
+
// `./generators` subpath. The text goes to a file of its own beside the
|
|
5
|
+
// target, then takes the target's place by a rename, which is atomic within
|
|
6
|
+
// a directory: a reader (`tsc --watch`, an editor) never sees half a
|
|
7
|
+
// declaration file, and a write that fails leaves the old file as it was.
|
|
8
|
+
// `wx` refuses a temporary name that exists; the counter keeps the names of
|
|
9
|
+
// two writes of one process apart.
|
|
10
|
+
let written = 0;
|
|
11
|
+
|
|
12
|
+
const writeFile = async (outputFile, text) => {
|
|
13
|
+
written += 1;
|
|
14
|
+
const temporary = `${outputFile}.${process.pid}.${written}.tmp`;
|
|
15
|
+
try {
|
|
16
|
+
await fsp.writeFile(temporary, text, { flag: 'wx' });
|
|
17
|
+
await fsp.rename(temporary, outputFile);
|
|
18
|
+
} catch (error) {
|
|
19
|
+
await fsp.rm(temporary, { force: true });
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
6
23
|
|
|
7
24
|
module.exports = { writeFile };
|
package/src/schema.js
CHANGED
|
@@ -32,6 +32,14 @@ const lazyRun = (schema) => {
|
|
|
32
32
|
return run;
|
|
33
33
|
};
|
|
34
34
|
|
|
35
|
+
// A stub of a validation method: the method installed since, when the
|
|
36
|
+
// validation half has been, else the error that it is not.
|
|
37
|
+
const late = (schema, name, args) => {
|
|
38
|
+
const method = Schema.prototype[name];
|
|
39
|
+
if (method === STUBS[name]) throw noValidation(name);
|
|
40
|
+
return method.apply(schema, args);
|
|
41
|
+
};
|
|
42
|
+
|
|
35
43
|
// The half of the core that builds a schema and reads it: its fields and
|
|
36
44
|
// metadata, its JSON and its snapshot. The validation half (`validation.js`,
|
|
37
45
|
// which the core entry loads) installs `check`, `parse`, `serialize` and
|
|
@@ -59,9 +67,9 @@ class Schema extends SchemaMetadata {
|
|
|
59
67
|
if (hasBrand(raw, 'Schema')) {
|
|
60
68
|
if (name && raw.name && raw.name !== name) {
|
|
61
69
|
const reason = `Schema "${raw.name}" cannot be used as "${name}"`;
|
|
62
|
-
throw new SchemaDefinitionError(
|
|
70
|
+
throw new SchemaDefinitionError(reason);
|
|
63
71
|
}
|
|
64
|
-
raw.attach(
|
|
72
|
+
for (const namespace of namespaces) raw.attach(namespace);
|
|
65
73
|
return raw;
|
|
66
74
|
}
|
|
67
75
|
super();
|
|
@@ -100,7 +108,7 @@ class Schema extends SchemaMetadata {
|
|
|
100
108
|
if (this.namespaces.size === 0) return TYPES;
|
|
101
109
|
if (this.#types === null) {
|
|
102
110
|
const types = Object.create(null);
|
|
103
|
-
for (const
|
|
111
|
+
for (const namespace of this.namespaces) Object.assign(types, namespace.types);
|
|
104
112
|
this.#types = types;
|
|
105
113
|
}
|
|
106
114
|
return this.#types;
|
|
@@ -111,8 +119,8 @@ class Schema extends SchemaMetadata {
|
|
|
111
119
|
// first, so a schema with the name of one of their entities (a schema
|
|
112
120
|
// derived from it keeps the name) still reaches that entity.
|
|
113
121
|
findReference(name) {
|
|
114
|
-
for (const
|
|
115
|
-
const entity =
|
|
122
|
+
for (const namespace of this.namespaces) {
|
|
123
|
+
const entity = namespace.entities.get(name);
|
|
116
124
|
if (entity) return entity;
|
|
117
125
|
}
|
|
118
126
|
return name === this.name && name !== '' ? this : null;
|
|
@@ -122,13 +130,13 @@ class Schema extends SchemaMetadata {
|
|
|
122
130
|
// latter through the entities an async validator may be in), so both are
|
|
123
131
|
// rebuilt on the next use.
|
|
124
132
|
attach(...namespaces) {
|
|
125
|
-
for (const
|
|
133
|
+
for (const namespace of namespaces) this.namespaces.add(namespace);
|
|
126
134
|
this.#types = null;
|
|
127
135
|
this[STANDARD] = null;
|
|
128
136
|
}
|
|
129
137
|
|
|
130
138
|
detach(...namespaces) {
|
|
131
|
-
for (const
|
|
139
|
+
for (const namespace of namespaces) this.namespaces.delete(namespace);
|
|
132
140
|
this.#types = null;
|
|
133
141
|
this[STANDARD] = null;
|
|
134
142
|
}
|
|
@@ -184,12 +192,6 @@ const STUBS = {
|
|
|
184
192
|
},
|
|
185
193
|
};
|
|
186
194
|
|
|
187
|
-
const late = (schema, name, args) => {
|
|
188
|
-
const method = Schema.prototype[name];
|
|
189
|
-
if (method === STUBS[name]) throw noValidation(name);
|
|
190
|
-
return method.apply(schema, args);
|
|
191
|
-
};
|
|
192
|
-
|
|
193
195
|
for (const name of Object.keys(STUBS)) {
|
|
194
196
|
Object.defineProperty(Schema.prototype, name, {
|
|
195
197
|
value: STUBS[name],
|
package/src/snapshot.js
CHANGED
|
@@ -49,7 +49,7 @@ const base64Of = (bytes) => {
|
|
|
49
49
|
const valueOf = (value) => {
|
|
50
50
|
const type = typeof value;
|
|
51
51
|
if (type === 'function') return { $function: true };
|
|
52
|
-
if (type === 'bigint') return { $bigint:
|
|
52
|
+
if (type === 'bigint') return { $bigint: `${value}` };
|
|
53
53
|
if (type !== 'object' || value === null) return value;
|
|
54
54
|
if (hasBrand(value, 'Type')) return fieldOf(value);
|
|
55
55
|
if (Array.isArray(value)) return listOf(value);
|
|
@@ -67,7 +67,9 @@ const valueOf = (value) => {
|
|
|
67
67
|
// sorted, so the text does not depend on how the definition was written.
|
|
68
68
|
const fieldOf = (field) => {
|
|
69
69
|
const out = { type: field.type, required: field.required };
|
|
70
|
-
|
|
70
|
+
const keys = Object.keys(field);
|
|
71
|
+
keys.sort();
|
|
72
|
+
for (const key of keys) {
|
|
71
73
|
const item = field[key];
|
|
72
74
|
if (key !== 'root' && item !== undefined) out[key] = valueOf(item);
|
|
73
75
|
}
|
|
@@ -137,10 +139,9 @@ const typeOf = (Type) => {
|
|
|
137
139
|
};
|
|
138
140
|
|
|
139
141
|
const typeClash = (name) =>
|
|
140
|
-
new SchemaDefinitionError(
|
|
141
|
-
'
|
|
142
|
-
|
|
143
|
-
);
|
|
142
|
+
new SchemaDefinitionError(`Two types named "${name}" cannot be represented in one snapshot`, {
|
|
143
|
+
code: 'ALX_ERR_UNREPRESENTABLE',
|
|
144
|
+
});
|
|
144
145
|
|
|
145
146
|
// The types the entities use, by name, and the custom types their aliases
|
|
146
147
|
// name down the chain (a model is restored from them): each from the table
|
|
@@ -172,7 +173,9 @@ const typesOf = (entities, tableOf) => {
|
|
|
172
173
|
}
|
|
173
174
|
}
|
|
174
175
|
const out = {};
|
|
175
|
-
|
|
176
|
+
const names = Array.from(found.keys());
|
|
177
|
+
names.sort();
|
|
178
|
+
for (const name of names) {
|
|
176
179
|
const entry = typeOf(found.get(name));
|
|
177
180
|
if (entry !== null) out[name] = entry;
|
|
178
181
|
}
|
|
@@ -200,10 +203,9 @@ const snapshotOf = (model) => {
|
|
|
200
203
|
};
|
|
201
204
|
|
|
202
205
|
const clash = (name) =>
|
|
203
|
-
new SchemaDefinitionError(
|
|
204
|
-
'
|
|
205
|
-
|
|
206
|
-
);
|
|
206
|
+
new SchemaDefinitionError(`Two schemas named "${name}" cannot be represented in one snapshot`, {
|
|
207
|
+
code: 'ALX_ERR_UNREPRESENTABLE',
|
|
208
|
+
});
|
|
207
209
|
|
|
208
210
|
// The order of the entities of a model and of a snapshot: depth first from
|
|
209
211
|
// each start in turn, every entity after the ones its edges reach
|
|
@@ -283,4 +285,4 @@ const schemaSnapshotOf = (schema) => {
|
|
|
283
285
|
};
|
|
284
286
|
};
|
|
285
287
|
|
|
286
|
-
module.exports = { FORMAT,
|
|
288
|
+
module.exports = { FORMAT, usesOf, snapshotOf, orderOf, schemaSnapshotOf };
|
package/src/stream/index.d.ts
CHANGED
|
@@ -11,48 +11,58 @@ import type {
|
|
|
11
11
|
ValidationResult,
|
|
12
12
|
} from '../../index.js';
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
/**
|
|
15
|
+
* `check` on every record of an iterable, as a generator of
|
|
16
|
+
* `{ index, record, result }` in the order of the records; the options are
|
|
17
|
+
* those of `check`, plus `maxInvalid`, the number of invalid records after
|
|
18
|
+
* which the iteration ends. A target that is not a Schema, or a source that
|
|
19
|
+
* is not iterable, is a `SchemaUsageError` with the code `ALX_ERR_INVALID_TARGET`.
|
|
20
|
+
*/
|
|
19
21
|
export function checkEach<T>(
|
|
20
22
|
schema: Schema,
|
|
21
23
|
records: Iterable<T>,
|
|
22
24
|
options?: EachOptions,
|
|
23
25
|
): Generator<RecordEntry<T, ValidationResult>, void, undefined>;
|
|
24
26
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
+
/**
|
|
28
|
+
* `parse` on every record of an iterable: the same, with the result of
|
|
29
|
+
* `parse` in each entry.
|
|
30
|
+
*/
|
|
27
31
|
export function parseEach<T, D extends string | object>(
|
|
28
32
|
schema: Schema<D>,
|
|
29
33
|
records: Iterable<T>,
|
|
30
34
|
options?: ParseEachOptions,
|
|
31
35
|
): Generator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
|
|
32
36
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
37
|
+
/**
|
|
38
|
+
* `checkAsync` on every record of a sync or async iterable, as an async
|
|
39
|
+
* generator in the order of the records, with up to `concurrency` records
|
|
40
|
+
* in flight (one by default).
|
|
41
|
+
*/
|
|
36
42
|
export function checkEachAsync<T>(
|
|
37
43
|
schema: Schema,
|
|
38
44
|
records: Iterable<T> | AsyncIterable<T>,
|
|
39
45
|
options?: EachOptions & EachAsyncOptions,
|
|
40
46
|
): AsyncGenerator<RecordEntry<T, ValidationResult>, void, undefined>;
|
|
41
47
|
|
|
42
|
-
|
|
43
|
-
|
|
48
|
+
/**
|
|
49
|
+
* `parseAsync` on every record of a sync or async iterable: the same, with
|
|
50
|
+
* the result of `parseAsync` in each entry.
|
|
51
|
+
*/
|
|
44
52
|
export function parseEachAsync<T, D extends string | object>(
|
|
45
53
|
schema: Schema<D>,
|
|
46
54
|
records: Iterable<T> | AsyncIterable<T>,
|
|
47
55
|
options?: ParseEachOptions & EachAsyncOptions,
|
|
48
56
|
): AsyncGenerator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
|
|
49
57
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
58
|
+
/**
|
|
59
|
+
* A TransformStream over the records of a stream: a valid record goes on as
|
|
60
|
+
* its parsed value (`mode: 'parse'`, the default) or as it is
|
|
61
|
+
* (`mode: 'check'`); an invalid one is handed to `onInvalid` and dropped, or
|
|
62
|
+
* ends the stream with a `SchemaUsageError` of the code `ALX_ERR_INVALID_RECORD` (with
|
|
63
|
+
* `index`, `record` and `result` on it) when there is no `onInvalid` or
|
|
64
|
+
* `maxInvalid` is reached. `async: true` runs the async methods.
|
|
65
|
+
*/
|
|
56
66
|
export function transform<D extends string | object>(
|
|
57
67
|
schema: Schema<D>,
|
|
58
68
|
options: TransformOptions & { mode: 'check' },
|
|
@@ -62,7 +72,9 @@ export function transform<D extends string | object>(
|
|
|
62
72
|
options?: TransformOptions,
|
|
63
73
|
): TransformStream<unknown, InferOutput<D>>;
|
|
64
74
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
75
|
+
/**
|
|
76
|
+
* Installs `schema.checkEach`, `schema.parseEach`, `schema.checkEachAsync`,
|
|
77
|
+
* `schema.parseEachAsync` and `schema.transform`. Once per process; later
|
|
78
|
+
* calls do nothing.
|
|
79
|
+
*/
|
|
68
80
|
export function register(): void;
|