@alexify/metaschema 0.0.0-stage → 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/src/result.js ADDED
@@ -0,0 +1,124 @@
1
+ const { BRAND, INSPECT, hasBrand } = require('./util.js');
2
+ const { EMPTY, NONE, absorb, finalize, describe, toDotPath } = require('./issues.js');
3
+ const en = require('./locales/en.js');
4
+
5
+ // Defines an own data property, so a key such as `__proto__` taken from a
6
+ // path lands on the object instead of changing its prototype.
7
+ const define = (target, key, value) => {
8
+ Object.defineProperty(target, key, {
9
+ value,
10
+ enumerable: true,
11
+ writable: true,
12
+ configurable: true,
13
+ });
14
+ return value;
15
+ };
16
+
17
+ class ValidationResult {
18
+ #root;
19
+ #messages;
20
+ #errors = null;
21
+
22
+ // A check builds its result from its context, which carries the root label,
23
+ // the locale of the call and the issues under these names; a validator that
24
+ // builds one of its own needs none of them: its issues are relative to the
25
+ // field the validator belongs to.
26
+ constructor(options = {}) {
27
+ const { root = '', messages = en, issues = NONE } = options;
28
+ this.#root = root;
29
+ this.#messages = messages;
30
+ this.issues = issues;
31
+ }
32
+
33
+ get valid() {
34
+ return this.issues.length === 0;
35
+ }
36
+
37
+ // The messages with their location, rendered on first use.
38
+ get errors() {
39
+ if (this.#errors === null) {
40
+ const errors = [];
41
+ for (const issue of this.issues) errors.push(describe(this.#messages, this.#root, issue));
42
+ this.#errors = errors;
43
+ }
44
+ return this.#errors;
45
+ }
46
+
47
+ get summary() {
48
+ return this.errors.join('\n');
49
+ }
50
+
51
+ add(error, code = 'custom') {
52
+ const context = { issues: this.issues, count: this.issues.length, limit: Infinity, path: [] };
53
+ absorb(context, error, code, EMPTY);
54
+ this.issues = context.issues;
55
+ finalize(this.issues, this.#messages);
56
+ this.#errors = null;
57
+ return this;
58
+ }
59
+
60
+ // Messages by dotted path, for forms: `formErrors` holds the messages of
61
+ // the value itself, `fieldErrors` those of its fields.
62
+ flatten() {
63
+ const formErrors = [];
64
+ const fieldErrors = {};
65
+ for (const issue of this.issues) {
66
+ const { path, message } = issue;
67
+ if (path.length === 0) {
68
+ formErrors.push(message);
69
+ continue;
70
+ }
71
+ const key = toDotPath(path);
72
+ const list = Object.hasOwn(fieldErrors, key)
73
+ ? fieldErrors[key]
74
+ : define(fieldErrors, key, []);
75
+ list.push(message);
76
+ }
77
+ return { formErrors, fieldErrors };
78
+ }
79
+
80
+ // Messages as a tree that follows the value: `properties` by key, `items`
81
+ // by index.
82
+ tree() {
83
+ const root = { errors: [] };
84
+ for (const issue of this.issues) {
85
+ let node = root;
86
+ for (const key of issue.path) {
87
+ if (typeof key === 'number') {
88
+ if (node.items === undefined) node.items = [];
89
+ if (node.items[key] === undefined) node.items[key] = { errors: [] };
90
+ node = node.items[key];
91
+ } else {
92
+ if (node.properties === undefined) node.properties = {};
93
+ const name = String(key);
94
+ node = Object.hasOwn(node.properties, name)
95
+ ? node.properties[name]
96
+ : define(node.properties, name, { errors: [] });
97
+ }
98
+ }
99
+ node.errors.push(issue.message);
100
+ }
101
+ return root;
102
+ }
103
+
104
+ // The issues `add` would record for a validator's return value.
105
+ static issuesOf(error, path = [], code = 'custom') {
106
+ const context = { issues: [], count: 0, limit: Infinity, path };
107
+ absorb(context, error, code, EMPTY);
108
+ finalize(context.issues, en);
109
+ return context.issues;
110
+ }
111
+
112
+ static isInstance(error) {
113
+ return hasBrand(error, 'ValidationResult');
114
+ }
115
+
116
+ [INSPECT](depth, options, inspect) {
117
+ const { valid, errors, issues } = this;
118
+ return `ValidationResult ${inspect({ valid, errors, issues }, options)}`;
119
+ }
120
+ }
121
+
122
+ ValidationResult.prototype[BRAND] = 'ValidationResult';
123
+
124
+ module.exports = { ValidationResult };
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 };
@@ -0,0 +1,6 @@
1
+ // Browser twin of ./node.js: the same interface, mapped in by the package.json
2
+ // `browser` field. There is no file system to write to, so it rejects.
3
+
4
+ const saveTypes = () => Promise.reject(new Error('saveTypes is not available in the browser'));
5
+
6
+ module.exports = { saveTypes };
@@ -0,0 +1,5 @@
1
+ const fsp = require('node:fs').promises;
2
+
3
+ const saveTypes = (outputFile, model) => fsp.writeFile(outputFile, model.dts);
4
+
5
+ module.exports = { saveTypes };
package/src/schema.js ADDED
@@ -0,0 +1,281 @@
1
+ const { isFirstUpper } = require('./metautil.js');
2
+
3
+ const { BRAND, INSPECT, RUN, hasBrand } = require('./util.js');
4
+ const { createContext } = require('./context.js');
5
+ const { TYPES } = require('./types.js');
6
+ const { Preprocessor } = require('./preprocessor.js');
7
+ const { SchemaMetadata } = require('./metadata.js');
8
+ const { ValidationResult } = require('./result.js');
9
+ const { finalize, runValidate } = require('./issues.js');
10
+ const { SchemaDefinitionError } = require('./errors.js');
11
+ const { createStruct, isStruct, checkOf } = require('./struct.js');
12
+ const { embeds } = require('./prototypes/reference.js');
13
+ const { warning, lintSchema } = require('./lint.js');
14
+
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',
24
+ };
25
+
26
+ const listOf = (element) => (element.includes(' | ') ? `(${element})[]` : `${element}[]`);
27
+
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.
52
+ const tsType = (def) => {
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
+ }
62
+ if (def.enum) return def.enum.map((value) => JSON.stringify(value)).join(' | ');
63
+ if (def.union) return def.union.map(tsType).join(' | ');
64
+ if (def.scalar) return TS_SCALARS[def.scalar] || 'string';
65
+ if (def.schema) return tsStruct(def.schema);
66
+ if (Array.isArray(def.value)) return `[${def.value.map(tsType).join(', ')}]`;
67
+ if (def.key !== undefined && def.value) {
68
+ const entries = `${def.key}, ${tsType(def.value)}`;
69
+ return def.isInstance({}) ? `Record<${entries}>` : `Map<${entries}>`;
70
+ }
71
+ if (def.value) {
72
+ const element = tsType(def.value);
73
+ return def.isInstance([]) ? listOf(element) : `Set<${element}>`;
74
+ }
75
+ if (def.kind === 'struct') return 'unknown';
76
+ return 'string';
77
+ };
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
+
101
+ const tsFields = (fields) => {
102
+ const lines = [];
103
+ for (const pair of Object.entries(fields)) {
104
+ const key = pair[0];
105
+ const def = pair[1];
106
+ if (!hasBrand(def, 'Type')) continue;
107
+ const optional = def.required ? '' : '?';
108
+ const name = isFirstUpper(def.type) && asId(def) ? `${key}Id` : key;
109
+ lines.push(`${name}${optional}: ${tsType(def)}`);
110
+ }
111
+ return lines;
112
+ };
113
+
114
+ class Schema extends SchemaMetadata {
115
+ // The merged type table of the attached namespaces, rebuilt only when they
116
+ // change.
117
+ #types = null;
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
+
130
+ static from(source, namespaces) {
131
+ return new Schema('', source, namespaces);
132
+ }
133
+
134
+ static extractSchema(def) {
135
+ if (hasBrand(def, 'Schema')) return def;
136
+ if (hasBrand(def.schema, 'Schema')) return def.schema;
137
+ return null;
138
+ }
139
+
140
+ constructor(name, raw, namespaces = []) {
141
+ // A Schema instance is reused, not copied: it keeps its own name, and the
142
+ // namespaces it is given here are attached so a model can resolve its
143
+ // references through it.
144
+ if (hasBrand(raw, 'Schema')) {
145
+ if (name && raw.name && raw.name !== name) {
146
+ const reason = `Schema "${raw.name}" cannot be used as "${name}"`;
147
+ throw new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason);
148
+ }
149
+ raw.attach(...namespaces);
150
+ return raw;
151
+ }
152
+ super();
153
+ this.name = name;
154
+ this.namespaces = new Set(namespaces);
155
+ const preprocessor = new Preprocessor(this);
156
+ const { Type, defs, kindMeta } = preprocessor.parse(raw);
157
+ const isSchemaType = Type.type === 'schema';
158
+ if (!isSchemaType) {
159
+ this.kind = Type.kind;
160
+ this.fields = new Type(defs, preprocessor);
161
+ } else {
162
+ const fields = this.extractMetadata(defs.schema);
163
+ let extras = Object.create(null);
164
+ if (kindMeta) extras = this.updateFromKind(kindMeta);
165
+ const combined = { ...fields, ...extras };
166
+ this.fields = createStruct(combined, preprocessor);
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;
195
+ }
196
+
197
+ get types() {
198
+ if (this.namespaces.size === 0) return TYPES;
199
+ if (this.#types === null) {
200
+ const types = Array.from(this.namespaces).map((ns) => ns.types);
201
+ this.#types = Object.assign(Object.create(null), ...types);
202
+ }
203
+ return this.#types;
204
+ }
205
+
206
+ // The warnings that need the namespaces: references and types that do
207
+ // not resolve.
208
+ checkConsistency() {
209
+ const warn = [];
210
+ const { name, references } = this;
211
+ for (const ref of references) {
212
+ if (isFirstUpper(ref)) {
213
+ const entity = this.findReference(ref);
214
+ if (!entity) {
215
+ warn.push(warning('missing-reference', `"${ref}" referenced by "${name}" is not found`));
216
+ }
217
+ } else if (!this.types[ref]) {
218
+ warn.push(warning('missing-type', `type "${ref}" is not found in "${name}"`));
219
+ }
220
+ }
221
+ return warn;
222
+ }
223
+
224
+ findReference(name) {
225
+ for (const ns of this.namespaces) {
226
+ const entity = ns.entities.get(name);
227
+ if (entity) return entity;
228
+ }
229
+ return null;
230
+ }
231
+
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);
241
+ }
242
+ this[RUN](source, context);
243
+ finalize(context.issues, context.messages);
244
+ return new ValidationResult(context);
245
+ }
246
+
247
+ toInterface() {
248
+ const { name, fields } = this;
249
+ if (!hasBrand(fields, 'Struct')) return `type ${name} = ${tsType(fields)};`;
250
+ const lines = tsFields(fields).map((line) => ` ${line};`);
251
+ return [`interface ${name} {`, ...lines, '}'].join('\n');
252
+ }
253
+
254
+ attach(...namespaces) {
255
+ for (const ns of namespaces) this.namespaces.add(ns);
256
+ this.#types = null;
257
+ }
258
+
259
+ detach(...namespaces) {
260
+ for (const ns of namespaces) this.namespaces.delete(ns);
261
+ this.#types = null;
262
+ }
263
+
264
+ toString() {
265
+ return JSON.stringify(this);
266
+ }
267
+
268
+ toJSON() {
269
+ const { fields } = this;
270
+ return hasBrand(fields, 'Struct') ? { ...fields } : fields.toJSON();
271
+ }
272
+
273
+ [INSPECT](depth, options, inspect) {
274
+ const label = this.name ? `Schema(${this.name})` : 'Schema';
275
+ return `${label} ${inspect(this.toJSON(), options)}`;
276
+ }
277
+ }
278
+
279
+ Schema.prototype[BRAND] = 'Schema';
280
+
281
+ module.exports = { Schema };
package/src/struct.js ADDED
@@ -0,0 +1,120 @@
1
+ const { BRAND, hasBrand, formatters } = require('./util.js');
2
+ const { issues } = require('./issues.js');
3
+ const { SchemaDefinitionError } = require('./errors.js');
4
+
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
+ };
70
+
71
+ // A struct is a null-prototype dictionary of field name -> Type (or the
72
+ // function of a calculated field), not a class instance with methods: a field
73
+ // may be named `check`, `name` or `constructor`, and an input key such as
74
+ // `__proto__` or `toString` must be reported as unexpected instead of silently
75
+ // resolving to something on Object.prototype.
76
+ const createStruct = (defs, prep) => {
77
+ const fields = Object.create(null);
78
+ const plan = [];
79
+ const known = Object.create(null);
80
+ for (const key of Object.keys(defs)) {
81
+ const entry = defs[key];
82
+ const { field, required } = formatters.key(key, entry?.required);
83
+ try {
84
+ const { Type, defs: typeDefs } = prep.parse(entry);
85
+ if (!Type) {
86
+ fields[key] = entry;
87
+ known[key] = true;
88
+ continue;
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;
94
+ const child = new Type(typeDefs, prep);
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
+ });
104
+ } catch (error) {
105
+ if (error instanceof SchemaDefinitionError) error.locate(prep.root.name, field);
106
+ throw error;
107
+ }
108
+ }
109
+ Object.freeze(plan);
110
+ const compiled = Object.freeze({ plan, known, check: compileStruct(plan, known) });
111
+ Object.defineProperty(fields, BRAND, { value: 'Struct' });
112
+ Object.defineProperty(fields, STRUCT, { value: compiled });
113
+ return fields;
114
+ };
115
+
116
+ const isStruct = (fields) => hasBrand(fields, 'Struct');
117
+
118
+ const checkOf = (fields) => fields[STRUCT].check;
119
+
120
+ module.exports = { STRUCT, createStruct, isStruct, checkOf };