@alexify/metaschema 1.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +551 -1
- package/README.md +235 -34
- package/SECURITY.md +32 -11
- package/index.d.ts +798 -23
- package/package.json +30 -6
- package/src/codec.js +490 -0
- package/src/compile/code.js +92 -0
- package/src/compile/emit.js +512 -0
- package/src/compile/index.d.ts +38 -0
- package/src/compile/index.js +176 -0
- package/src/context.js +141 -0
- package/src/errors.js +10 -1
- package/src/generators/index.d.ts +29 -0
- package/src/generators/index.js +90 -0
- package/src/generators/jsonschema.js +535 -0
- package/src/generators/typescript.js +237 -0
- package/src/index.js +1 -3
- package/src/issues.js +291 -0
- package/src/kinds.js +9 -12
- package/src/lint.js +98 -0
- package/src/locales/en.d.ts +5 -0
- package/src/locales/en.js +66 -0
- package/src/locales/uk.d.ts +5 -0
- package/src/locales/uk.js +62 -0
- package/src/metadata.js +65 -119
- package/src/metautil.js +8 -1
- package/src/model.js +31 -20
- package/src/preprocessor.js +45 -27
- package/src/prototypes/abstract.js +101 -51
- package/src/prototypes/collections.js +106 -41
- package/src/prototypes/json.js +9 -5
- package/src/prototypes/reference.js +91 -20
- package/src/prototypes/scalars.js +124 -16
- package/src/prototypes/schema.js +31 -6
- package/src/prototypes/tuple.js +57 -29
- package/src/prototypes/union.js +139 -0
- package/src/result.js +115 -0
- package/src/rules.js +185 -0
- package/src/runtime/browser.js +2 -2
- package/src/runtime/node.js +4 -2
- package/src/schema.js +181 -68
- package/src/struct.js +101 -33
- package/src/types.js +14 -14
- package/src/util.js +41 -50
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// The English messages. A locale is a table of renderers by issue code: each
|
|
2
|
+
// one turns the params of an issue into the text that follows the field in a
|
|
3
|
+
// message. `field` renders the location prefix of an error line.
|
|
4
|
+
const { shorten, safeString } = require('../util.js');
|
|
5
|
+
|
|
6
|
+
const field = (path) => `Field "${path}"`;
|
|
7
|
+
|
|
8
|
+
const required = () => 'is required';
|
|
9
|
+
|
|
10
|
+
const type = ({ expected, key }) =>
|
|
11
|
+
key === undefined ? `not of expected type: ${expected}` : `keys must be of type ${expected}`;
|
|
12
|
+
|
|
13
|
+
const list = (keys) => {
|
|
14
|
+
let text = shorten(keys[0]);
|
|
15
|
+
for (let index = 1; index < keys.length; index += 1) text += `, ${shorten(keys[index])}`;
|
|
16
|
+
return text;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const unexpected = ({ keys }) => `has unexpected keys: ${list(keys)}`;
|
|
20
|
+
|
|
21
|
+
const enumeration = ({ values }) => `value is not of enum: ${values.join(', ')}`;
|
|
22
|
+
|
|
23
|
+
const length = ({ min, actual }) =>
|
|
24
|
+
min !== undefined && actual < min ? 'value is too short' : 'exceeds the maximum length';
|
|
25
|
+
|
|
26
|
+
const range = ({ min, max, actual }) =>
|
|
27
|
+
min !== undefined && actual < min ? `is less than ${min}` : `is greater than ${max}`;
|
|
28
|
+
|
|
29
|
+
const pattern = ({ pattern: source }) => `does not match the pattern ${source}`;
|
|
30
|
+
|
|
31
|
+
const union = ({ expected, discriminator }) =>
|
|
32
|
+
discriminator === undefined
|
|
33
|
+
? `does not match any of: ${expected.join(', ')}`
|
|
34
|
+
: `is not one of: ${expected.join(', ')}`;
|
|
35
|
+
|
|
36
|
+
const reference = ({ entity }) => `Entity "${entity}" is not found`;
|
|
37
|
+
|
|
38
|
+
const circular = () => 'is a circular reference';
|
|
39
|
+
|
|
40
|
+
const depth = ({ max }) => `is nested deeper than ${max} references`;
|
|
41
|
+
|
|
42
|
+
const exception = ({ error }) => `validation failed ${safeString(error)}`;
|
|
43
|
+
|
|
44
|
+
const custom = () => 'validation error';
|
|
45
|
+
|
|
46
|
+
module.exports = {
|
|
47
|
+
field,
|
|
48
|
+
required,
|
|
49
|
+
type,
|
|
50
|
+
unexpected,
|
|
51
|
+
enum: enumeration,
|
|
52
|
+
length,
|
|
53
|
+
range,
|
|
54
|
+
pattern,
|
|
55
|
+
union,
|
|
56
|
+
reference,
|
|
57
|
+
circular,
|
|
58
|
+
depth,
|
|
59
|
+
exception,
|
|
60
|
+
custom,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// A table without a prototype: a code a validator makes up (`constructor`)
|
|
64
|
+
// finds no renderer here. Set after the literal, which cjs-module-lexer reads
|
|
65
|
+
// for the named exports of the ESM interop.
|
|
66
|
+
Object.setPrototypeOf(module.exports, null);
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Ukrainian messages, with the same table as ./en.js. Pass the table to a
|
|
2
|
+
// check as `messages`: `schema.check(value, { messages: uk })`.
|
|
3
|
+
const { shorten, safeString } = require('../util.js');
|
|
4
|
+
|
|
5
|
+
const field = (path) => `Поле "${path}"`;
|
|
6
|
+
|
|
7
|
+
const required = () => 'є обовʼязковим';
|
|
8
|
+
|
|
9
|
+
const type = ({ expected, key }) =>
|
|
10
|
+
key === undefined ? `не відповідає типу: ${expected}` : `ключі мають бути типу ${expected}`;
|
|
11
|
+
|
|
12
|
+
const list = (keys) => {
|
|
13
|
+
let text = shorten(keys[0]);
|
|
14
|
+
for (let index = 1; index < keys.length; index += 1) text += `, ${shorten(keys[index])}`;
|
|
15
|
+
return text;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const unexpected = ({ keys }) => `має неочікувані ключі: ${list(keys)}`;
|
|
19
|
+
|
|
20
|
+
const enumeration = ({ values }) => `значення не входить до переліку: ${values.join(', ')}`;
|
|
21
|
+
|
|
22
|
+
const length = ({ min, actual }) =>
|
|
23
|
+
min !== undefined && actual < min ? 'значення закоротке' : 'перевищує максимальну довжину';
|
|
24
|
+
|
|
25
|
+
const range = ({ min, max, actual }) =>
|
|
26
|
+
min !== undefined && actual < min ? `менше за ${min}` : `більше за ${max}`;
|
|
27
|
+
|
|
28
|
+
const pattern = ({ pattern: source }) => `не відповідає шаблону ${source}`;
|
|
29
|
+
|
|
30
|
+
const union = ({ expected, discriminator }) =>
|
|
31
|
+
discriminator === undefined
|
|
32
|
+
? `не відповідає жодному з: ${expected.join(', ')}`
|
|
33
|
+
: `не є одним із: ${expected.join(', ')}`;
|
|
34
|
+
|
|
35
|
+
const reference = ({ entity }) => `сутність "${entity}" не знайдено`;
|
|
36
|
+
|
|
37
|
+
const circular = () => 'є циклічним посиланням';
|
|
38
|
+
|
|
39
|
+
const depth = ({ max }) => `вкладене глибше ніж ${max} посилань`;
|
|
40
|
+
|
|
41
|
+
const exception = ({ error }) => `перевірка завершилась помилкою ${safeString(error)}`;
|
|
42
|
+
|
|
43
|
+
const custom = () => 'помилка перевірки';
|
|
44
|
+
|
|
45
|
+
module.exports = {
|
|
46
|
+
field,
|
|
47
|
+
required,
|
|
48
|
+
type,
|
|
49
|
+
unexpected,
|
|
50
|
+
enum: enumeration,
|
|
51
|
+
length,
|
|
52
|
+
range,
|
|
53
|
+
pattern,
|
|
54
|
+
union,
|
|
55
|
+
reference,
|
|
56
|
+
circular,
|
|
57
|
+
depth,
|
|
58
|
+
exception,
|
|
59
|
+
custom,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
Object.setPrototypeOf(module.exports, null);
|
package/src/metadata.js
CHANGED
|
@@ -1,108 +1,47 @@
|
|
|
1
1
|
const { getKindMetadata } = require('./kinds.js');
|
|
2
|
-
const {
|
|
3
|
-
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
constructor(path = '') {
|
|
20
|
-
this.#path = path;
|
|
21
|
-
this.errors = [];
|
|
22
|
-
this.issues = [];
|
|
23
|
-
this.valid = true;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// True once the maxErrors of the current check is reached; loops stop early.
|
|
27
|
-
get full() {
|
|
28
|
-
return this.errors.length >= limits.maxErrors;
|
|
2
|
+
const { ValidationResult } = require('./result.js');
|
|
3
|
+
const { SchemaDefinitionError, asyncReturn } = require('./errors.js');
|
|
4
|
+
const { isThenable } = require('./issues.js');
|
|
5
|
+
|
|
6
|
+
// The functions of a schema definition that are the schema's own: its
|
|
7
|
+
// validate, its decoder, its serializer and `format`.
|
|
8
|
+
const OPTIONS = new Set(['validate', 'parse', 'serialize', 'format']);
|
|
9
|
+
|
|
10
|
+
// The unknown-keys policy of a schema is the default of its `check`, so a
|
|
11
|
+
// value with keys the schema does not have is rejected or ignored without
|
|
12
|
+
// an option on every call; the option of a call still wins.
|
|
13
|
+
const unknownOf = (unknown) => {
|
|
14
|
+
if (unknown === undefined) return 'reject';
|
|
15
|
+
if (unknown !== 'reject' && unknown !== 'ignore') {
|
|
16
|
+
const reason = `Schema metadata "unknown" must be "reject" or "ignore", got ${JSON.stringify(unknown)}`;
|
|
17
|
+
throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
29
18
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return issues;
|
|
57
|
-
}
|
|
58
|
-
if (isIssue(error)) {
|
|
59
|
-
const found = { code: error.code || code, path: error.path || path };
|
|
60
|
-
return [{ ...found, message: prefixed(error.message, path) }];
|
|
61
|
-
}
|
|
62
|
-
return [{ code, path, message: prefixed(String(error), path) }];
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
static format(error, path = '') {
|
|
66
|
-
const issues = ValidationResult.issuesOf(error, path);
|
|
67
|
-
if (issues.length === 0) return null;
|
|
68
|
-
return issues.map((entry) => entry.message);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
static isInstance(error) {
|
|
72
|
-
return hasBrand(error, 'ValidationResult');
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
ValidationResult.prototype[BRAND] = 'ValidationResult';
|
|
77
|
-
|
|
78
|
-
class Options {
|
|
79
|
-
constructor() {
|
|
80
|
-
this.validate = null;
|
|
81
|
-
this.format = null;
|
|
82
|
-
this.parse = null;
|
|
83
|
-
this.serialize = null;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
extract(key, field) {
|
|
87
|
-
const isFn = typeof field === 'function';
|
|
88
|
-
const isOption = OPTIONS.includes(key) && isFn;
|
|
89
|
-
if (isOption) this[key] = field;
|
|
90
|
-
return isOption;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
class Indexes {
|
|
95
|
-
// Index definitions (`index`, `primary`, `unique` arrays) are taken out of the
|
|
96
|
-
// fields; a `many` relation is recorded here as well but stays a field, so
|
|
97
|
-
// the method reports only whether the entry was taken.
|
|
98
|
-
extract(key, field) {
|
|
99
|
-
if (field === null || typeof field !== 'object') return false;
|
|
100
|
-
const { index, primary, unique, many } = field;
|
|
101
|
-
const isIndex = Array.isArray(index || primary || unique);
|
|
102
|
-
if (isIndex || many) this[key] = field;
|
|
103
|
-
return isIndex;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
19
|
+
return unknown;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// `indexes` is a null-prototype dictionary keyed by definition keys, which may
|
|
23
|
+
// be called `extract` or `constructor`; `options` only ever holds the four
|
|
24
|
+
// keys below and stays a plain object with fast properties: the compiled
|
|
25
|
+
// check reads `options.validate` on every call, and V8 keeps an object made
|
|
26
|
+
// by `Object.create(null)` in dictionary mode.
|
|
27
|
+
const createOptions = () => ({ validate: null, format: null, parse: null, serialize: null });
|
|
28
|
+
|
|
29
|
+
const extractOption = (options, key, field) => {
|
|
30
|
+
const isOption = typeof field === 'function' && OPTIONS.has(key);
|
|
31
|
+
if (isOption) options[key] = field;
|
|
32
|
+
return isOption;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// Index definitions (`index`, `primary`, `unique` arrays) are taken out of the
|
|
36
|
+
// fields; a `many` relation is recorded as well but stays a field, so only
|
|
37
|
+
// whether the entry was taken is reported.
|
|
38
|
+
const extractIndex = (indexes, key, field) => {
|
|
39
|
+
if (field === null || typeof field !== 'object') return false;
|
|
40
|
+
const { index, primary, unique, many } = field;
|
|
41
|
+
const isIndex = Array.isArray(index || primary || unique);
|
|
42
|
+
if (isIndex || many) indexes[key] = field;
|
|
43
|
+
return isIndex;
|
|
44
|
+
};
|
|
106
45
|
|
|
107
46
|
class SchemaMetadata {
|
|
108
47
|
constructor() {
|
|
@@ -111,20 +50,22 @@ class SchemaMetadata {
|
|
|
111
50
|
this.store = 'memory';
|
|
112
51
|
this.allow = 'write';
|
|
113
52
|
this.parent = '';
|
|
114
|
-
this.
|
|
115
|
-
this.
|
|
53
|
+
this.unknown = 'reject';
|
|
54
|
+
this.indexes = Object.create(null);
|
|
55
|
+
this.options = createOptions();
|
|
116
56
|
this.custom = {};
|
|
117
57
|
this.references = new Set();
|
|
118
58
|
this.relations = new Set();
|
|
119
59
|
}
|
|
120
60
|
|
|
121
61
|
#setMany(values) {
|
|
122
|
-
const { kind, scope, store, allow, parent, ...custom } = values;
|
|
62
|
+
const { kind, scope, store, allow, parent, unknown, ...custom } = values;
|
|
123
63
|
this.kind = kind || this.kind;
|
|
124
64
|
this.scope = scope || this.scope;
|
|
125
65
|
this.store = store || this.store;
|
|
126
66
|
this.allow = allow || this.allow;
|
|
127
67
|
this.parent = parent || this.parent;
|
|
68
|
+
this.unknown = unknownOf(unknown);
|
|
128
69
|
this.custom = custom;
|
|
129
70
|
}
|
|
130
71
|
|
|
@@ -141,26 +82,31 @@ class SchemaMetadata {
|
|
|
141
82
|
|
|
142
83
|
extractMetadata(defs) {
|
|
143
84
|
const fields = Object.create(null);
|
|
144
|
-
for (const
|
|
145
|
-
const
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const taken = this[collection].extract(key, field);
|
|
150
|
-
if (taken) extracted = true;
|
|
151
|
-
}
|
|
152
|
-
if (!extracted) fields[key] = field;
|
|
85
|
+
for (const key of Object.keys(defs)) {
|
|
86
|
+
const field = defs[key];
|
|
87
|
+
const option = extractOption(this.options, key, field);
|
|
88
|
+
const index = extractIndex(this.indexes, key, field);
|
|
89
|
+
if (!option && !index) fields[key] = field;
|
|
153
90
|
}
|
|
154
91
|
return fields;
|
|
155
92
|
}
|
|
156
93
|
|
|
157
|
-
validate
|
|
94
|
+
// Runs only the schema-level validate function, as a result of its own; a
|
|
95
|
+
// function that returns a promise is an error here, as in check.
|
|
96
|
+
validate(value, path = '') {
|
|
158
97
|
if (!this.options.validate) return null;
|
|
159
|
-
const result = new ValidationResult(
|
|
98
|
+
const result = new ValidationResult();
|
|
160
99
|
try {
|
|
161
|
-
|
|
100
|
+
const output = this.options.validate.call(this, value, path);
|
|
101
|
+
if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
|
|
102
|
+
return result.add(output);
|
|
162
103
|
} catch (error) {
|
|
163
|
-
|
|
104
|
+
if (error.code === 'ERR_ASYNC_VALIDATOR') throw error;
|
|
105
|
+
return result.add({
|
|
106
|
+
code: 'exception',
|
|
107
|
+
message: `validation failed ${error}`,
|
|
108
|
+
params: { error },
|
|
109
|
+
});
|
|
164
110
|
}
|
|
165
111
|
}
|
|
166
112
|
}
|
package/src/metautil.js
CHANGED
|
@@ -11,7 +11,14 @@ const isFirstLetter = (s) => isFirstUpper(s) || isFirstLower(s);
|
|
|
11
11
|
|
|
12
12
|
const toLowerCamel = (s) => s.charAt(0).toLowerCase() + s.slice(1);
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
// The first own key that starts with a letter, without a list of the keys:
|
|
15
|
+
// this runs once for every object of a definition.
|
|
16
|
+
const firstKey = (obj) => {
|
|
17
|
+
for (const key in obj) {
|
|
18
|
+
if (Object.hasOwn(obj, key) && isFirstLetter(key)) return key;
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
};
|
|
15
22
|
|
|
16
23
|
module.exports = {
|
|
17
24
|
inRange,
|
package/src/model.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
const { firstKey } = require('./metautil.js');
|
|
2
2
|
|
|
3
|
+
const { BRAND } = require('./util.js');
|
|
3
4
|
const { Schema } = require('./schema.js');
|
|
4
5
|
const { TYPES, createRegistry, typeFactory } = require('./types.js');
|
|
5
6
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
6
|
-
|
|
7
|
-
const REGISTRIES = ['shared', 'isolated'];
|
|
7
|
+
const { warning } = require('./lint.js');
|
|
8
8
|
|
|
9
9
|
const registryFor = (options) => {
|
|
10
10
|
const { registry = 'shared' } = options;
|
|
11
|
-
if (
|
|
11
|
+
if (registry !== 'shared' && registry !== 'isolated') {
|
|
12
12
|
const reason = `Model option "registry" must be "shared" or "isolated", got ${JSON.stringify(registry)}`;
|
|
13
13
|
throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
14
14
|
}
|
|
@@ -16,12 +16,16 @@ const registryFor = (options) => {
|
|
|
16
16
|
};
|
|
17
17
|
|
|
18
18
|
class Model {
|
|
19
|
+
// The model's own warnings (the cycles met while ordering), found while
|
|
20
|
+
// building; the rest comes from the entities on first use.
|
|
21
|
+
#cycles = [];
|
|
22
|
+
#warnings = null;
|
|
23
|
+
|
|
19
24
|
constructor(types, entities, database = null, options = {}) {
|
|
20
25
|
this.types = typeFactory(types, registryFor(options));
|
|
21
26
|
this.entities = new Map();
|
|
22
27
|
this.database = database;
|
|
23
28
|
this.order = new Set();
|
|
24
|
-
this.warnings = [];
|
|
25
29
|
const projections = [];
|
|
26
30
|
for (const pair of entities) {
|
|
27
31
|
const name = pair[0];
|
|
@@ -43,15 +47,28 @@ class Model {
|
|
|
43
47
|
this.#preprocess();
|
|
44
48
|
}
|
|
45
49
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
// The lint warnings of every entity, the references and types they cannot
|
|
51
|
+
// resolve, and the recursive dependencies, as `Warning [code]: text`.
|
|
52
|
+
get warnings() {
|
|
53
|
+
if (this.#warnings !== null) return this.#warnings;
|
|
54
|
+
const warnings = [];
|
|
55
|
+
const add = (list) => {
|
|
56
|
+
for (let index = 0; index < list.length; index += 1) warnings.push(list[index]);
|
|
57
|
+
};
|
|
58
|
+
for (const pair of this.entities) {
|
|
49
59
|
const name = pair[0];
|
|
50
60
|
const entity = pair[1];
|
|
51
61
|
if (name.startsWith('.')) continue;
|
|
52
|
-
|
|
53
|
-
|
|
62
|
+
add(entity.warnings);
|
|
63
|
+
add(entity.checkConsistency());
|
|
54
64
|
}
|
|
65
|
+
add(this.#cycles);
|
|
66
|
+
this.#warnings = warnings;
|
|
67
|
+
return warnings;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
#preprocess() {
|
|
71
|
+
const { entities, order } = this;
|
|
55
72
|
if (entities.has('Identifier')) order.add('Identifier');
|
|
56
73
|
for (const name of entities.keys()) {
|
|
57
74
|
const isMeta = name.startsWith('.');
|
|
@@ -69,7 +86,9 @@ class Model {
|
|
|
69
86
|
for (const ref of entity.references) {
|
|
70
87
|
if (ref === name) continue;
|
|
71
88
|
if (visiting.has(ref)) {
|
|
72
|
-
this.
|
|
89
|
+
this.#cycles.push(
|
|
90
|
+
warning('recursive-reference', `"${name}" depends on "${ref}" recursively`),
|
|
91
|
+
);
|
|
73
92
|
continue;
|
|
74
93
|
}
|
|
75
94
|
this.#reorderEntity(ref, visiting);
|
|
@@ -77,16 +96,8 @@ class Model {
|
|
|
77
96
|
visiting.delete(name);
|
|
78
97
|
this.order.add(name);
|
|
79
98
|
}
|
|
80
|
-
|
|
81
|
-
get dts() {
|
|
82
|
-
const { entities, order } = this;
|
|
83
|
-
const dts = [];
|
|
84
|
-
for (const name of order) {
|
|
85
|
-
const schema = entities.get(name);
|
|
86
|
-
dts.push(schema.toInterface());
|
|
87
|
-
}
|
|
88
|
-
return `${dts.join('\n\n')}\n`;
|
|
89
|
-
}
|
|
90
99
|
}
|
|
91
100
|
|
|
101
|
+
Model.prototype[BRAND] = 'Model';
|
|
102
|
+
|
|
92
103
|
module.exports = { Model };
|
package/src/preprocessor.js
CHANGED
|
@@ -1,20 +1,31 @@
|
|
|
1
1
|
const { isFirstUpper, toLowerCamel, firstKey } = require('./metautil.js');
|
|
2
2
|
|
|
3
|
-
const { formatters } = require('./util.js');
|
|
3
|
+
const { hasBrand, formatters } = require('./util.js');
|
|
4
4
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
5
|
+
const { typeOf } = require('./issues.js');
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
// The first key of an object decides what it is: a Schema or a built field is
|
|
8
|
+
// used as it is, a capitalized key is a kind, `type` is the long form, a type
|
|
9
|
+
// name is that type's shorthand, and anything else is a nested struct.
|
|
10
|
+
const PARSERS = Object.assign(Object.create(null), {
|
|
7
11
|
string: ['stringShorthand'],
|
|
8
|
-
object: [
|
|
12
|
+
object: [
|
|
13
|
+
'schemaInstance',
|
|
14
|
+
'typeInstance',
|
|
15
|
+
'schemaWithKind',
|
|
16
|
+
'typeLongForm',
|
|
17
|
+
'typeShorthand',
|
|
18
|
+
'kindlessSchema',
|
|
19
|
+
],
|
|
9
20
|
function: ['functionField'],
|
|
10
21
|
array: ['tupleShorthand'],
|
|
11
|
-
};
|
|
22
|
+
});
|
|
12
23
|
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
24
|
+
const invalid = (source, srcType = typeOf(source)) =>
|
|
25
|
+
new SchemaDefinitionError(
|
|
26
|
+
'ERR_INVALID_DEFINITION',
|
|
27
|
+
`Invalid definition: "${source}" of type ${srcType}`,
|
|
28
|
+
);
|
|
18
29
|
|
|
19
30
|
class Preprocessor {
|
|
20
31
|
constructor(root) {
|
|
@@ -23,35 +34,44 @@ class Preprocessor {
|
|
|
23
34
|
this.types = root.types;
|
|
24
35
|
}
|
|
25
36
|
|
|
37
|
+
// The first key of an object is read once here and handed to the parsers
|
|
38
|
+
// that look at it.
|
|
26
39
|
parse(source) {
|
|
27
|
-
const srcType =
|
|
40
|
+
const srcType = typeOf(source);
|
|
28
41
|
const parsers = PARSERS[srcType];
|
|
29
42
|
if (parsers) {
|
|
43
|
+
const first = srcType === 'object' ? firstKey(source) : undefined;
|
|
30
44
|
for (const name of parsers) {
|
|
31
|
-
const result = this[name](source);
|
|
45
|
+
const result = this[name](source, first);
|
|
32
46
|
if (result) return result;
|
|
33
47
|
}
|
|
34
48
|
}
|
|
35
|
-
|
|
36
|
-
throw new SchemaDefinitionError('ERR_INVALID_DEFINITION', msg);
|
|
49
|
+
throw invalid(source, srcType);
|
|
37
50
|
}
|
|
38
51
|
|
|
52
|
+
// A Schema instance as a field: `{ schema: instance }` and the long form go
|
|
53
|
+
// through the type parsers, and the schema type accepts the instance there.
|
|
39
54
|
schemaInstance(source) {
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
55
|
+
if (!hasBrand(source, 'Schema')) return null;
|
|
56
|
+
const defs = { schema: source };
|
|
57
|
+
return { Type: this.types.schema, defs };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// A field already built (a projection copies the fields of its parent) is
|
|
61
|
+
// parsed again from its own definition, so the copy belongs to the schema
|
|
62
|
+
// that holds it.
|
|
63
|
+
typeInstance(source) {
|
|
64
|
+
if (!hasBrand(source, 'Type')) return null;
|
|
65
|
+
return this.typeLongForm({ type: source.type, ...source.toJSON() }, 'type');
|
|
47
66
|
}
|
|
48
67
|
|
|
49
68
|
stringShorthand(source) {
|
|
50
|
-
return this.typeLongForm({ type: source });
|
|
69
|
+
return this.typeLongForm({ type: source }, 'type');
|
|
51
70
|
}
|
|
52
71
|
|
|
53
|
-
typeLongForm(source) {
|
|
54
|
-
if (
|
|
72
|
+
typeLongForm(source, first) {
|
|
73
|
+
if (first !== 'type') return null;
|
|
74
|
+
if (typeof source.type !== 'string') throw invalid(source.type);
|
|
55
75
|
const { types } = this;
|
|
56
76
|
const parsed = formatters.type(source.type, source.required);
|
|
57
77
|
const { type, required } = parsed;
|
|
@@ -66,9 +86,8 @@ class Preprocessor {
|
|
|
66
86
|
return { Type: types[type], defs };
|
|
67
87
|
}
|
|
68
88
|
|
|
69
|
-
typeShorthand(source) {
|
|
89
|
+
typeShorthand(source, first) {
|
|
70
90
|
const { types } = this;
|
|
71
|
-
const first = firstKey(source);
|
|
72
91
|
const parsed = formatters.key(first, source.required);
|
|
73
92
|
const type = parsed.field;
|
|
74
93
|
const required = parsed.required;
|
|
@@ -78,9 +97,8 @@ class Preprocessor {
|
|
|
78
97
|
return { Type: types[type], defs };
|
|
79
98
|
}
|
|
80
99
|
|
|
81
|
-
schemaWithKind(source) {
|
|
100
|
+
schemaWithKind(source, first) {
|
|
82
101
|
const { types, root } = this;
|
|
83
|
-
const first = firstKey(source);
|
|
84
102
|
if (!isFirstUpper(first)) return null;
|
|
85
103
|
const { [first]: meta, ...fields } = source;
|
|
86
104
|
const kind = toLowerCamel(first);
|