@alexify/metaschema 1.0.0 → 2.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 +228 -1
- package/README.md +124 -28
- package/SECURITY.md +6 -4
- package/index.d.ts +558 -19
- package/package.json +11 -2
- package/src/context.js +95 -0
- package/src/index.js +1 -1
- package/src/issues.js +196 -0
- package/src/lint.js +90 -0
- package/src/locales/en.d.ts +5 -0
- package/src/locales/en.js +58 -0
- package/src/locales/uk.d.ts +5 -0
- package/src/locales/uk.js +57 -0
- package/src/metadata.js +25 -76
- package/src/model.js +23 -7
- package/src/preprocessor.js +42 -19
- package/src/prototypes/abstract.js +86 -49
- package/src/prototypes/collections.js +86 -38
- package/src/prototypes/json.js +9 -5
- package/src/prototypes/reference.js +77 -20
- package/src/prototypes/scalars.js +126 -16
- package/src/prototypes/schema.js +19 -6
- package/src/prototypes/tuple.js +52 -29
- package/src/prototypes/union.js +100 -0
- package/src/result.js +124 -0
- package/src/rules.js +156 -0
- package/src/schema.js +133 -39
- package/src/struct.js +89 -32
- package/src/types.js +9 -3
- package/src/util.js +5 -53
package/src/rules.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// The rule checks a field may carry besides its type. A type lists the rules
|
|
2
|
+
// it accepts (`rules: ['length']` on a prototype); a rule in a definition of a
|
|
3
|
+
// type that does not accept it is a definition error, not a silent no-op. A
|
|
4
|
+
// rule's value is checked and normalized when the field is built (`format`),
|
|
5
|
+
// and its check is compiled into a closure over the field's bounds, run after
|
|
6
|
+
// the type check.
|
|
7
|
+
const { issues } = require('./issues.js');
|
|
8
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
9
|
+
|
|
10
|
+
const invalidRule = (reason) => new SchemaDefinitionError('ERR_INVALID_RULE', reason);
|
|
11
|
+
|
|
12
|
+
const invalidLength = (reason = 'needs a number, [min, max] or { min, max }') =>
|
|
13
|
+
new SchemaDefinitionError('ERR_INVALID_LENGTH', `Rule "length" ${reason}`);
|
|
14
|
+
|
|
15
|
+
const isBound = (value) => value === undefined || typeof value === 'number';
|
|
16
|
+
|
|
17
|
+
const isLimit = (value) => typeof value === 'number' || typeof value === 'bigint';
|
|
18
|
+
|
|
19
|
+
const formatLength = (length) => {
|
|
20
|
+
if (typeof length === 'number') return { max: length };
|
|
21
|
+
if (length === null || typeof length !== 'object') throw invalidLength();
|
|
22
|
+
const min = Array.isArray(length) ? length[0] : length.min;
|
|
23
|
+
const max = Array.isArray(length) ? length[1] : length.max;
|
|
24
|
+
if (!isBound(min) || !isBound(max)) throw invalidLength();
|
|
25
|
+
if (min !== undefined && max !== undefined && min > max) throw invalidLength('has min above max');
|
|
26
|
+
return { min, max };
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// A number or a bigint, kept as it is: a bigint bound compared with a number
|
|
30
|
+
// value (and the other way round) is exact in JavaScript, Number(bigint) is not.
|
|
31
|
+
const formatLimit = (name) => (value) => {
|
|
32
|
+
if (!isLimit(value)) throw invalidRule(`Rule "${name}" needs a number or a bigint`);
|
|
33
|
+
return value;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// A pattern is compiled once, here, with the `u` flag (so `\p{L}` and
|
|
37
|
+
// astral characters mean what they say), and without `g` and `y`, whose
|
|
38
|
+
// lastIndex would make the same test give different answers in a row.
|
|
39
|
+
const formatPattern = (value) => {
|
|
40
|
+
const isRegExp = value instanceof RegExp;
|
|
41
|
+
if (!isRegExp && typeof value !== 'string') {
|
|
42
|
+
throw invalidRule('Rule "pattern" needs a string or a RegExp');
|
|
43
|
+
}
|
|
44
|
+
const source = isRegExp ? value.source : value;
|
|
45
|
+
const given = isRegExp ? value.flags.replace(/[guy]/g, '') : '';
|
|
46
|
+
try {
|
|
47
|
+
return new RegExp(source, `${given}u`);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
throw invalidRule(`Rule "pattern" is not a valid regular expression: ${error.message}`);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// The formatter of each rule, by name; the names are the rules that exist.
|
|
54
|
+
const FORMAT = {
|
|
55
|
+
length: formatLength,
|
|
56
|
+
min: formatLimit('min'),
|
|
57
|
+
max: formatLimit('max'),
|
|
58
|
+
pattern: formatPattern,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const notApplicable = (rule, type, rules) => {
|
|
62
|
+
const hint = rule === 'length' && rules.has('min') ? '; use min and max' : '';
|
|
63
|
+
return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Code points of a string: a surrogate pair counts once, a lone surrogate
|
|
67
|
+
// once too.
|
|
68
|
+
const codePoints = (text) => {
|
|
69
|
+
const { length } = text;
|
|
70
|
+
let count = 0;
|
|
71
|
+
for (let index = 0; index < length; index += 1) {
|
|
72
|
+
const unit = text.charCodeAt(index);
|
|
73
|
+
if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < length) {
|
|
74
|
+
const next = text.charCodeAt(index + 1);
|
|
75
|
+
if (next >= 0xdc00 && next <= 0xdfff) index += 1;
|
|
76
|
+
}
|
|
77
|
+
count += 1;
|
|
78
|
+
}
|
|
79
|
+
return count;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// The length of a value: the size of a Map or Set, the length of a string or
|
|
83
|
+
// an array, the number of keys of an object. A string is UTF-16 units unless
|
|
84
|
+
// the field asks for code points.
|
|
85
|
+
const lengthOf = (value) => {
|
|
86
|
+
if (typeof value === 'string') return value.length;
|
|
87
|
+
const { size, length } = value;
|
|
88
|
+
if (typeof size === 'number') return size;
|
|
89
|
+
if (typeof length === 'number') return length;
|
|
90
|
+
return Object.keys(value).length;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const lengthOfUnicode = (value) =>
|
|
94
|
+
typeof value === 'string' ? codePoints(value) : lengthOf(value);
|
|
95
|
+
|
|
96
|
+
const compileLength = (type) => {
|
|
97
|
+
const { min, max } = type.length;
|
|
98
|
+
if (type.unicode === true) {
|
|
99
|
+
return (value, context, key) => {
|
|
100
|
+
const actual = lengthOfUnicode(value);
|
|
101
|
+
const short = min !== undefined && actual < min;
|
|
102
|
+
const long = max !== undefined && actual > max;
|
|
103
|
+
if (short || long) issues.length(context, min, max, actual, key);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return (value, context, key) => {
|
|
107
|
+
const actual = lengthOf(value);
|
|
108
|
+
const short = min !== undefined && actual < min;
|
|
109
|
+
const long = max !== undefined && actual > max;
|
|
110
|
+
if (short || long) issues.length(context, min, max, actual, key);
|
|
111
|
+
};
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// One closure for both bounds when a field has both.
|
|
115
|
+
const compileRange = (type) => {
|
|
116
|
+
const { min, max } = type;
|
|
117
|
+
if (min === undefined) {
|
|
118
|
+
return (value, context, key) => {
|
|
119
|
+
if (value > max) issues.range(context, min, max, value, key);
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
if (max === undefined) {
|
|
123
|
+
return (value, context, key) => {
|
|
124
|
+
if (value < min) issues.range(context, min, max, value, key);
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
if (min > max) throw invalidRule('Rule "max" is below "min"');
|
|
128
|
+
return (value, context, key) => {
|
|
129
|
+
if (value < min || value > max) issues.range(context, min, max, value, key);
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const compilePattern = (type) => {
|
|
134
|
+
const { pattern } = type;
|
|
135
|
+
const { source } = pattern;
|
|
136
|
+
return (value, context, key) => {
|
|
137
|
+
if (!pattern.test(value)) issues.pattern(context, source, key);
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
// The checks of the rules a field carries, in the order the type lists them.
|
|
142
|
+
const compileRules = (type, rules) => {
|
|
143
|
+
const checks = [];
|
|
144
|
+
if (rules.size === 0) return checks;
|
|
145
|
+
let range = false;
|
|
146
|
+
for (const name of rules) {
|
|
147
|
+
if (type[name] === undefined) continue;
|
|
148
|
+
if (name === 'length') checks.push(compileLength(type));
|
|
149
|
+
else if (name === 'pattern') checks.push(compilePattern(type));
|
|
150
|
+
else if (name === 'min' || name === 'max') range = true;
|
|
151
|
+
}
|
|
152
|
+
if (range) checks.push(compileRange(type));
|
|
153
|
+
return checks;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
module.exports = { FORMAT, notApplicable, compileRules, codePoints };
|
package/src/schema.js
CHANGED
|
@@ -1,40 +1,103 @@
|
|
|
1
1
|
const { isFirstUpper } = require('./metautil.js');
|
|
2
2
|
|
|
3
|
-
const { BRAND, INSPECT,
|
|
3
|
+
const { BRAND, INSPECT, RUN, hasBrand } = require('./util.js');
|
|
4
|
+
const { createContext } = require('./context.js');
|
|
4
5
|
const { TYPES } = require('./types.js');
|
|
5
6
|
const { Preprocessor } = require('./preprocessor.js');
|
|
6
|
-
const { SchemaMetadata
|
|
7
|
+
const { SchemaMetadata } = require('./metadata.js');
|
|
8
|
+
const { ValidationResult } = require('./result.js');
|
|
9
|
+
const { finalize, runValidate } = require('./issues.js');
|
|
7
10
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
8
|
-
const { createStruct,
|
|
11
|
+
const { createStruct, isStruct, checkOf } = require('./struct.js');
|
|
12
|
+
const { embeds } = require('./prototypes/reference.js');
|
|
13
|
+
const { warning, lintSchema } = require('./lint.js');
|
|
9
14
|
|
|
10
|
-
const TS_SCALARS = {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
15
|
+
const TS_SCALARS = {
|
|
16
|
+
string: 'string',
|
|
17
|
+
number: 'number',
|
|
18
|
+
boolean: 'boolean',
|
|
19
|
+
bigint: 'bigint',
|
|
20
|
+
date: 'Date',
|
|
21
|
+
null: 'null',
|
|
22
|
+
any: 'any',
|
|
23
|
+
unknown: 'unknown',
|
|
16
24
|
};
|
|
17
25
|
|
|
18
26
|
const listOf = (element) => (element.includes(' | ') ? `(${element})[]` : `${element}[]`);
|
|
19
27
|
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
28
|
+
// Whether a reference field renders as its id (`companyId: string`) or as
|
|
29
|
+
// the referenced type (`company: Company`): the same rule as `check`, with
|
|
30
|
+
// a target that cannot be resolved taken as stored.
|
|
31
|
+
const asId = (def) => {
|
|
32
|
+
const target = def.root.findReference(def.type);
|
|
33
|
+
if (target === null) return def.embed !== true;
|
|
34
|
+
return !embeds(target, def.embed, 'kind');
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const tsStruct = (fields) => `{ ${tsFields(fields).join('; ')} }`;
|
|
38
|
+
|
|
39
|
+
// The referenced type: its interface by name, inline when it has none, the
|
|
40
|
+
// name of the reference when it cannot be resolved.
|
|
41
|
+
const tsReference = (def) => {
|
|
42
|
+
const target = def.root.findReference(def.type);
|
|
43
|
+
if (target === null || target.name) return def.type;
|
|
44
|
+
const { fields } = target;
|
|
45
|
+
return hasBrand(fields, 'Struct') ? tsStruct(fields) : tsType(fields);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// The TypeScript type of a field. A reference to a stored kind is held as
|
|
49
|
+
// an id, so it renders as a string (an array of them for `many`), a
|
|
50
|
+
// reference to a memory kind as the type itself; a custom scalar with its
|
|
51
|
+
// own check has no known shape and renders as a string.
|
|
23
52
|
const tsType = (def) => {
|
|
24
|
-
|
|
53
|
+
const type = tsBase(def);
|
|
54
|
+
return def.nullable === true ? `${type} | null` : type;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const tsBase = (def) => {
|
|
58
|
+
if (isFirstUpper(def.type)) {
|
|
59
|
+
const element = asId(def) ? 'string' : tsReference(def);
|
|
60
|
+
return def.many ? listOf(element) : element;
|
|
61
|
+
}
|
|
25
62
|
if (def.enum) return def.enum.map((value) => JSON.stringify(value)).join(' | ');
|
|
63
|
+
if (def.union) return def.union.map(tsType).join(' | ');
|
|
26
64
|
if (def.scalar) return TS_SCALARS[def.scalar] || 'string';
|
|
27
|
-
if (def.schema) return
|
|
65
|
+
if (def.schema) return tsStruct(def.schema);
|
|
28
66
|
if (Array.isArray(def.value)) return `[${def.value.map(tsType).join(', ')}]`;
|
|
29
67
|
if (def.key !== undefined && def.value) {
|
|
30
68
|
const entries = `${def.key}, ${tsType(def.value)}`;
|
|
31
69
|
return def.isInstance({}) ? `Record<${entries}>` : `Map<${entries}>`;
|
|
32
70
|
}
|
|
33
|
-
if (def.value)
|
|
71
|
+
if (def.value) {
|
|
72
|
+
const element = tsType(def.value);
|
|
73
|
+
return def.isInstance([]) ? listOf(element) : `Set<${element}>`;
|
|
74
|
+
}
|
|
34
75
|
if (def.kind === 'struct') return 'unknown';
|
|
35
76
|
return 'string';
|
|
36
77
|
};
|
|
37
78
|
|
|
79
|
+
// The validation of a schema inside an existing context: `check` starts one,
|
|
80
|
+
// and a reference field checks its target entity within the context of the
|
|
81
|
+
// outer check, so the error limit and the cycle detection span the whole
|
|
82
|
+
// value. The schema-level validate runs last, and only on a value whose
|
|
83
|
+
// fields all passed, so it can rely on their shape. Built once per schema,
|
|
84
|
+
// as Schema[RUN].
|
|
85
|
+
const compileSchema = (schema) => {
|
|
86
|
+
const { fields, options } = schema;
|
|
87
|
+
const run = isStruct(fields) ? checkOf(fields) : fields.check;
|
|
88
|
+
return (value, context, key) => {
|
|
89
|
+
const before = context.count;
|
|
90
|
+
run(value, context, key);
|
|
91
|
+
const { validate } = options;
|
|
92
|
+
if (validate && context.count === before) {
|
|
93
|
+
const nested = key !== undefined;
|
|
94
|
+
if (nested) context.path.push(key);
|
|
95
|
+
runValidate(schema, validate, value, context);
|
|
96
|
+
if (nested) context.path.pop();
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
|
|
38
101
|
const tsFields = (fields) => {
|
|
39
102
|
const lines = [];
|
|
40
103
|
for (const pair of Object.entries(fields)) {
|
|
@@ -42,7 +105,7 @@ const tsFields = (fields) => {
|
|
|
42
105
|
const def = pair[1];
|
|
43
106
|
if (!hasBrand(def, 'Type')) continue;
|
|
44
107
|
const optional = def.required ? '' : '?';
|
|
45
|
-
const name = isFirstUpper(def.type) ? `${key}Id` : key;
|
|
108
|
+
const name = isFirstUpper(def.type) && asId(def) ? `${key}Id` : key;
|
|
46
109
|
lines.push(`${name}${optional}: ${tsType(def)}`);
|
|
47
110
|
}
|
|
48
111
|
return lines;
|
|
@@ -53,6 +116,17 @@ class Schema extends SchemaMetadata {
|
|
|
53
116
|
// change.
|
|
54
117
|
#types = null;
|
|
55
118
|
|
|
119
|
+
// Whether the root value joins the cycle detection: only a struct with
|
|
120
|
+
// references can reach it again.
|
|
121
|
+
#tracked = false;
|
|
122
|
+
|
|
123
|
+
// The lint of the definition, run on first use: a schema built in a hot
|
|
124
|
+
// path never pays for it.
|
|
125
|
+
#warnings = null;
|
|
126
|
+
|
|
127
|
+
// The Standard Schema props, built on first use.
|
|
128
|
+
#standard = null;
|
|
129
|
+
|
|
56
130
|
static from(source, namespaces) {
|
|
57
131
|
return new Schema('', source, namespaces);
|
|
58
132
|
}
|
|
@@ -91,6 +165,33 @@ class Schema extends SchemaMetadata {
|
|
|
91
165
|
const combined = { ...fields, ...extras };
|
|
92
166
|
this.fields = createStruct(combined, preprocessor);
|
|
93
167
|
}
|
|
168
|
+
this.#tracked = isSchemaType && this.relations.size > 0;
|
|
169
|
+
this[RUN] = compileSchema(this);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// What is not wrong enough to throw: `Warning [code]: text` strings.
|
|
173
|
+
get warnings() {
|
|
174
|
+
if (this.#warnings === null) this.#warnings = lintSchema(this);
|
|
175
|
+
return this.#warnings;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Standard Schema v1 (https://standardschema.dev): the interface tRPC,
|
|
179
|
+
// TanStack Form, Hono and the other consumers of the specification validate
|
|
180
|
+
// through. A verdict only: a valid value comes back as it is, and the
|
|
181
|
+
// issues of an invalid one are the result's own (a message and a path of
|
|
182
|
+
// keys each). The vendor-specific `libraryOptions` of a call are the
|
|
183
|
+
// options of `check`. An accessor of the prototype stays out of toJSON,
|
|
184
|
+
// inspect and Object.keys, and `validate` closes over the schema because a
|
|
185
|
+
// consumer calls it unbound.
|
|
186
|
+
get '~standard'() {
|
|
187
|
+
if (this.#standard === null) {
|
|
188
|
+
const validate = (value, options) => {
|
|
189
|
+
const result = this.check(value, options == null ? undefined : options.libraryOptions);
|
|
190
|
+
return result.valid ? { value } : { issues: result.issues };
|
|
191
|
+
};
|
|
192
|
+
this.#standard = { version: 1, vendor: 'alexify.metaschema', validate };
|
|
193
|
+
}
|
|
194
|
+
return this.#standard;
|
|
94
195
|
}
|
|
95
196
|
|
|
96
197
|
get types() {
|
|
@@ -102,6 +203,8 @@ class Schema extends SchemaMetadata {
|
|
|
102
203
|
return this.#types;
|
|
103
204
|
}
|
|
104
205
|
|
|
206
|
+
// The warnings that need the namespaces: references and types that do
|
|
207
|
+
// not resolve.
|
|
105
208
|
checkConsistency() {
|
|
106
209
|
const warn = [];
|
|
107
210
|
const { name, references } = this;
|
|
@@ -109,10 +212,10 @@ class Schema extends SchemaMetadata {
|
|
|
109
212
|
if (isFirstUpper(ref)) {
|
|
110
213
|
const entity = this.findReference(ref);
|
|
111
214
|
if (!entity) {
|
|
112
|
-
warn.push(`
|
|
215
|
+
warn.push(warning('missing-reference', `"${ref}" referenced by "${name}" is not found`));
|
|
113
216
|
}
|
|
114
217
|
} else if (!this.types[ref]) {
|
|
115
|
-
warn.push(`
|
|
218
|
+
warn.push(warning('missing-type', `type "${ref}" is not found in "${name}"`));
|
|
116
219
|
}
|
|
117
220
|
}
|
|
118
221
|
return warn;
|
|
@@ -126,28 +229,19 @@ class Schema extends SchemaMetadata {
|
|
|
126
229
|
return null;
|
|
127
230
|
}
|
|
128
231
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
if (track) ancestors.add(source);
|
|
139
|
-
const previous = limits.maxErrors;
|
|
140
|
-
if (options.maxErrors !== undefined) limits.maxErrors = maxErrorsOf(options);
|
|
141
|
-
try {
|
|
142
|
-
const custom = this.validate(source, path);
|
|
143
|
-
result.add(custom);
|
|
144
|
-
if (result.full) return result;
|
|
145
|
-
const nested = isStruct ? checkStruct(fields, source, path) : fields.check(source, path);
|
|
146
|
-
return result.add(nested);
|
|
147
|
-
} finally {
|
|
148
|
-
limits.maxErrors = previous;
|
|
149
|
-
if (track) ancestors.delete(source);
|
|
232
|
+
// Validates a value: every problem is collected as an issue, and the result
|
|
233
|
+
// never throws because of the value. `options`: root (the label of the
|
|
234
|
+
// error lines, the schema name by default), maxErrors, unknown ('reject'
|
|
235
|
+
// or 'ignore' keys the schema does not have), messages (a locale).
|
|
236
|
+
check(source, options) {
|
|
237
|
+
const context = createContext(options, this.name, this.unknown);
|
|
238
|
+
if (this.#tracked && source !== null && typeof source === 'object') {
|
|
239
|
+
context.seen = new Set();
|
|
240
|
+
context.seen.add(source);
|
|
150
241
|
}
|
|
242
|
+
this[RUN](source, context);
|
|
243
|
+
finalize(context.issues, context.messages);
|
|
244
|
+
return new ValidationResult(context);
|
|
151
245
|
}
|
|
152
246
|
|
|
153
247
|
toInterface() {
|
package/src/struct.js
CHANGED
|
@@ -1,10 +1,72 @@
|
|
|
1
|
-
const {
|
|
2
|
-
const {
|
|
1
|
+
const { BRAND, hasBrand, formatters } = require('./util.js');
|
|
2
|
+
const { issues } = require('./issues.js');
|
|
3
3
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
4
4
|
|
|
5
|
-
//
|
|
6
|
-
// like BRAND, so a struct built by another copy of the package
|
|
7
|
-
|
|
5
|
+
// What a struct computes once at construction, kept on the dictionary under a
|
|
6
|
+
// global symbol like BRAND, so a struct built by another copy of the package
|
|
7
|
+
// exposes it too: { plan, known, check }, the plan being one frozen entry per
|
|
8
|
+
// validated field, `known` the dictionary of its keys, and `check` the
|
|
9
|
+
// compiled check over them.
|
|
10
|
+
const STRUCT = Symbol.for('alexify.metaschema.struct');
|
|
11
|
+
|
|
12
|
+
// A field is read with a keyed load, and `Object.hasOwn` is consulted only
|
|
13
|
+
// when the value is undefined, to tell a missing key from one set to
|
|
14
|
+
// undefined. A field named after a member of Object.prototype (`toString`,
|
|
15
|
+
// `constructor`, ...) would read the inherited function from a plain object,
|
|
16
|
+
// so such a field (`own`) always asks `Object.hasOwn` first.
|
|
17
|
+
const scanUnknown = (value, known, context) => {
|
|
18
|
+
let unexpected = null;
|
|
19
|
+
for (const name in value) {
|
|
20
|
+
if (name in known || !Object.hasOwn(value, name)) continue;
|
|
21
|
+
if (unexpected === null) unexpected = [];
|
|
22
|
+
unexpected.push(name);
|
|
23
|
+
}
|
|
24
|
+
if (unexpected !== null) issues.unexpected(context, unexpected);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// The check of a struct, as a closure over its plan: an index loop with no
|
|
28
|
+
// lookups in the raw definition, no brand checks and no path strings. Every
|
|
29
|
+
// plan entry has the same shape and every field check is a function chosen
|
|
30
|
+
// when the field was built, called with the key of the field so that a leaf
|
|
31
|
+
// never touches the path. Unknown keys are looked for only when the value has
|
|
32
|
+
// more keys than the plan found, so a value with exactly the expected keys is
|
|
33
|
+
// never scanned twice.
|
|
34
|
+
const compileStruct = (plan, known) => (value, context, key) => {
|
|
35
|
+
if (value === null || typeof value !== 'object') {
|
|
36
|
+
issues.type(context, 'object', value, key);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const nested = key !== undefined;
|
|
40
|
+
if (nested) context.path.push(key);
|
|
41
|
+
let found = 0;
|
|
42
|
+
for (let index = 0; index < plan.length; index += 1) {
|
|
43
|
+
if (context.count >= context.limit) break;
|
|
44
|
+
const entry = plan[index];
|
|
45
|
+
const name = entry.key;
|
|
46
|
+
const item = value[name];
|
|
47
|
+
if (item === undefined) {
|
|
48
|
+
// Absent, or own and set to undefined: the same for an optional field,
|
|
49
|
+
// a required one asks which (the latter is a type error).
|
|
50
|
+
if (!entry.required) continue;
|
|
51
|
+
if (!Object.hasOwn(value, name)) {
|
|
52
|
+
issues.required(context, name);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
} else if (entry.own && !Object.hasOwn(value, name)) {
|
|
56
|
+
if (entry.required) issues.required(context, name);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
found += 1;
|
|
60
|
+
entry.check(item, context, name);
|
|
61
|
+
}
|
|
62
|
+
if (context.unknown === 'reject' && context.count < context.limit) {
|
|
63
|
+
let total = 0;
|
|
64
|
+
// oxlint-disable-next-line no-unused-vars
|
|
65
|
+
for (const name in value) total += 1;
|
|
66
|
+
if (total !== found) scanUnknown(value, known, context);
|
|
67
|
+
}
|
|
68
|
+
if (nested) context.path.pop();
|
|
69
|
+
};
|
|
8
70
|
|
|
9
71
|
// A struct is a null-prototype dictionary of field name -> Type (or the
|
|
10
72
|
// function of a calculated field), not a class instance with methods: a field
|
|
@@ -13,6 +75,8 @@ const KEYS = Symbol.for('alexify.metaschema.keys');
|
|
|
13
75
|
// resolving to something on Object.prototype.
|
|
14
76
|
const createStruct = (defs, prep) => {
|
|
15
77
|
const fields = Object.create(null);
|
|
78
|
+
const plan = [];
|
|
79
|
+
const known = Object.create(null);
|
|
16
80
|
for (const key of Object.keys(defs)) {
|
|
17
81
|
const entry = defs[key];
|
|
18
82
|
const { field, required } = formatters.key(key, entry?.required);
|
|
@@ -20,44 +84,37 @@ const createStruct = (defs, prep) => {
|
|
|
20
84
|
const { Type, defs: typeDefs } = prep.parse(entry);
|
|
21
85
|
if (!Type) {
|
|
22
86
|
fields[key] = entry;
|
|
87
|
+
known[key] = true;
|
|
23
88
|
continue;
|
|
24
89
|
}
|
|
90
|
+
// The key ('tags?') and the definition ('?string', required: false)
|
|
91
|
+
// both decide whether the field is required, and the field's check is
|
|
92
|
+
// compiled with the answer, so it is settled before the field is built.
|
|
93
|
+
typeDefs.required = (typeDefs.required ?? true) && required;
|
|
25
94
|
const child = new Type(typeDefs, prep);
|
|
26
|
-
child.required &&= required;
|
|
27
95
|
fields[field] = child;
|
|
96
|
+
known[field] = true;
|
|
97
|
+
plan.push({
|
|
98
|
+
key: field,
|
|
99
|
+
type: child,
|
|
100
|
+
required: child.required,
|
|
101
|
+
own: field in Object.prototype,
|
|
102
|
+
check: child.check,
|
|
103
|
+
});
|
|
28
104
|
} catch (error) {
|
|
29
105
|
if (error instanceof SchemaDefinitionError) error.locate(prep.root.name, field);
|
|
30
106
|
throw error;
|
|
31
107
|
}
|
|
32
108
|
}
|
|
109
|
+
Object.freeze(plan);
|
|
110
|
+
const compiled = Object.freeze({ plan, known, check: compileStruct(plan, known) });
|
|
33
111
|
Object.defineProperty(fields, BRAND, { value: 'Struct' });
|
|
34
|
-
Object.defineProperty(fields,
|
|
112
|
+
Object.defineProperty(fields, STRUCT, { value: compiled });
|
|
35
113
|
return fields;
|
|
36
114
|
};
|
|
37
115
|
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if (!isObject) return result.add(issue('type', path, 'not of expected type: object'));
|
|
42
|
-
const keys = fields[KEYS] || Object.keys(fields);
|
|
43
|
-
for (const name of keys) {
|
|
44
|
-
if (result.full) break;
|
|
45
|
-
const type = fields[name];
|
|
46
|
-
if (!hasBrand(type, 'Type')) continue;
|
|
47
|
-
const nestedPath = path ? `${path}.${name}` : name;
|
|
48
|
-
if (!Object.hasOwn(source, name)) {
|
|
49
|
-
if (type.required) result.add(issue('required', nestedPath, 'is required'));
|
|
50
|
-
continue;
|
|
51
|
-
}
|
|
52
|
-
result.add(type.check(source[name], nestedPath));
|
|
53
|
-
}
|
|
54
|
-
for (const name of Object.keys(source)) {
|
|
55
|
-
if (result.full) break;
|
|
56
|
-
if (name in fields) continue;
|
|
57
|
-
const nestedPath = path ? `${path}.${shorten(name)}` : shorten(name);
|
|
58
|
-
result.add(issue('unexpected', nestedPath, 'is not expected'));
|
|
59
|
-
}
|
|
60
|
-
return result;
|
|
61
|
-
};
|
|
116
|
+
const isStruct = (fields) => hasBrand(fields, 'Struct');
|
|
117
|
+
|
|
118
|
+
const checkOf = (fields) => fields[STRUCT].check;
|
|
62
119
|
|
|
63
|
-
module.exports = { createStruct,
|
|
120
|
+
module.exports = { STRUCT, createStruct, isStruct, checkOf };
|
package/src/types.js
CHANGED
|
@@ -4,6 +4,7 @@ const collections = require('./prototypes/collections.js');
|
|
|
4
4
|
const { reference } = require('./prototypes/reference.js');
|
|
5
5
|
const { schema } = require('./prototypes/schema.js');
|
|
6
6
|
const { tuple } = require('./prototypes/tuple.js');
|
|
7
|
+
const { union } = require('./prototypes/union.js');
|
|
7
8
|
const { json } = require('./prototypes/json.js');
|
|
8
9
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
9
10
|
|
|
@@ -15,6 +16,7 @@ const PROTOTYPES = {
|
|
|
15
16
|
one: reference,
|
|
16
17
|
schema,
|
|
17
18
|
tuple,
|
|
19
|
+
union,
|
|
18
20
|
json,
|
|
19
21
|
};
|
|
20
22
|
|
|
@@ -26,6 +28,9 @@ const createType = (name, prototype) => {
|
|
|
26
28
|
static metadata = {};
|
|
27
29
|
static type = name;
|
|
28
30
|
static kind = prototype.kind;
|
|
31
|
+
static rules = new Set(prototype.rules);
|
|
32
|
+
// The definition keys the type reads; the lint reports the others.
|
|
33
|
+
static options = new Set(prototype.options);
|
|
29
34
|
|
|
30
35
|
static assign(key, value) {
|
|
31
36
|
this.metadata[key] = value;
|
|
@@ -37,8 +42,6 @@ const createType = (name, prototype) => {
|
|
|
37
42
|
this.type = type;
|
|
38
43
|
}
|
|
39
44
|
}
|
|
40
|
-
const { rules } = prototype;
|
|
41
|
-
if (rules) Type.setRules(rules);
|
|
42
45
|
Object.assign(Type.prototype, prototype, { type: name });
|
|
43
46
|
return Type;
|
|
44
47
|
};
|
|
@@ -66,8 +69,11 @@ const updateTypeMetadata = (Type, metadata = {}) => {
|
|
|
66
69
|
}
|
|
67
70
|
};
|
|
68
71
|
|
|
72
|
+
// A custom prototype brings `construct` and `checkType`; a built-in one, reused
|
|
73
|
+
// through a `js` alias, compiles its own check instead.
|
|
69
74
|
const checkCustomType = (name, proto) => {
|
|
70
|
-
const {
|
|
75
|
+
const { construct } = proto;
|
|
76
|
+
const checkType = proto.checkType || proto.compile;
|
|
71
77
|
if (!checkType || !construct) {
|
|
72
78
|
throw customTypeError(name, 'must contain "construct" and "checkType" methods');
|
|
73
79
|
}
|