@alexify/metaschema 2.0.0 → 3.1.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +443 -1
  2. package/README.md +124 -12
  3. package/SECURITY.md +27 -8
  4. package/index.d.ts +537 -84
  5. package/package.json +25 -6
  6. package/src/codec.js +544 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +540 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +68 -19
  12. package/src/errors.js +19 -1
  13. package/src/generators/fromjsonschema.js +520 -0
  14. package/src/generators/index.d.ts +46 -0
  15. package/src/generators/index.js +95 -0
  16. package/src/generators/jsonschema.js +535 -0
  17. package/src/generators/typescript.js +237 -0
  18. package/src/index.js +0 -2
  19. package/src/issues.js +117 -22
  20. package/src/kinds.js +9 -12
  21. package/src/lint.js +31 -14
  22. package/src/locales/en.js +10 -2
  23. package/src/locales/uk.js +7 -2
  24. package/src/metadata.js +41 -44
  25. package/src/metautil.js +8 -1
  26. package/src/model/data.js +122 -0
  27. package/src/model/diff.js +438 -0
  28. package/src/model/index.d.ts +56 -0
  29. package/src/model/index.js +42 -0
  30. package/src/model/merge.js +254 -0
  31. package/src/model/pattern.js +322 -0
  32. package/src/model/restore.js +226 -0
  33. package/src/model/sample.js +394 -0
  34. package/src/model.js +18 -15
  35. package/src/preprocessor.js +9 -11
  36. package/src/prototypes/abstract.js +14 -1
  37. package/src/prototypes/collections.js +20 -3
  38. package/src/prototypes/reference.js +17 -3
  39. package/src/prototypes/scalars.js +1 -3
  40. package/src/prototypes/schema.js +15 -2
  41. package/src/prototypes/tuple.js +14 -9
  42. package/src/prototypes/union.js +57 -18
  43. package/src/result.js +5 -14
  44. package/src/rules.js +55 -26
  45. package/src/runtime/browser.js +2 -2
  46. package/src/runtime/node.js +4 -2
  47. package/src/schema.js +129 -101
  48. package/src/snapshot.js +111 -0
  49. package/src/struct.js +80 -23
  50. package/src/types.js +5 -11
  51. package/src/util.js +39 -0
package/src/schema.js CHANGED
@@ -1,80 +1,25 @@
1
1
  const { isFirstUpper } = require('./metautil.js');
2
2
 
3
- const { BRAND, INSPECT, RUN, hasBrand } = require('./util.js');
3
+ const { BRAND, INSPECT, RUN, HOOK, hasBrand } = require('./util.js');
4
4
  const { createContext } = require('./context.js');
5
5
  const { TYPES } = require('./types.js');
6
6
  const { Preprocessor } = require('./preprocessor.js');
7
7
  const { SchemaMetadata } = require('./metadata.js');
8
8
  const { ValidationResult } = require('./result.js');
9
- const { finalize, runValidate } = require('./issues.js');
9
+ const { finalize, runValidate, settle } = require('./issues.js');
10
10
  const { SchemaDefinitionError } = require('./errors.js');
11
11
  const { createStruct, isStruct, checkOf } = require('./struct.js');
12
- const { embeds } = require('./prototypes/reference.js');
13
12
  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
- };
13
+ const {
14
+ PREPARE,
15
+ FINISH,
16
+ SERIALIZE,
17
+ infoOf,
18
+ apply,
19
+ looped,
20
+ hasAsync,
21
+ wantOf,
22
+ } = require('./codec.js');
78
23
 
79
24
  // The validation of a schema inside an existing context: `check` starts one,
80
25
  // and a reference field checks its target entity within the context of the
@@ -98,26 +43,29 @@ const compileSchema = (schema) => {
98
43
  };
99
44
  };
100
45
 
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;
46
+ const resultOf = (context) => {
47
+ finalize(context.issues, context.messages);
48
+ return new ValidationResult(context);
49
+ };
50
+
51
+ // What parse returns: the output only for a valid value, the issues always.
52
+ const parsed = (context, output) => {
53
+ finalize(context.issues, context.messages);
54
+ const valid = context.count === 0;
55
+ return { valid, value: valid ? output : undefined, issues: context.issues };
112
56
  };
113
57
 
58
+ // The result of parse read as Standard Schema does.
59
+ const standardize = (result) =>
60
+ result.valid ? { value: result.value } : { issues: result.issues };
61
+
114
62
  class Schema extends SchemaMetadata {
115
63
  // The merged type table of the attached namespaces, rebuilt only when they
116
64
  // change.
117
65
  #types = null;
118
66
 
119
- // Whether the root value joins the cycle detection: only a struct with
120
- // references can reach it again.
67
+ // Whether the root value joins the cycle detection (`context.source`):
68
+ // only a struct with references can reach it again.
121
69
  #tracked = false;
122
70
 
123
71
  // The lint of the definition, run on first use: a schema built in a hot
@@ -127,6 +75,9 @@ class Schema extends SchemaMetadata {
127
75
  // The Standard Schema props, built on first use.
128
76
  #standard = null;
129
77
 
78
+ // What the passes of parse and serialize know about the schema, on first use.
79
+ #codec = null;
80
+
130
81
  static from(source, namespaces) {
131
82
  return new Schema('', source, namespaces);
132
83
  }
@@ -167,6 +118,8 @@ class Schema extends SchemaMetadata {
167
118
  }
168
119
  this.#tracked = isSchemaType && this.relations.size > 0;
169
120
  this[RUN] = compileSchema(this);
121
+ const hook = Schema[HOOK];
122
+ if (hook !== undefined) hook(this);
170
123
  }
171
124
 
172
125
  // What is not wrong enough to throw: `Warning [code]: text` strings.
@@ -177,17 +130,23 @@ class Schema extends SchemaMetadata {
177
130
 
178
131
  // Standard Schema v1 (https://standardschema.dev): the interface tRPC,
179
132
  // 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,
133
+ // through. `validate` is `parse` with the policies of the schema: the value
134
+ // that comes back has the defaults and the decoders applied (the value
135
+ // itself when there was nothing to apply), and the issues of an invalid one
136
+ // are the result's own (a message and a path of keys each). A schema with
137
+ // an async validator or decoder validates through parseAsync, as the
138
+ // specification allows. The vendor-specific `libraryOptions` of a call are
139
+ // the options of `parse`. An accessor of the prototype stays out of toJSON,
184
140
  // inspect and Object.keys, and `validate` closes over the schema because a
185
- // consumer calls it unbound.
141
+ // consumer calls it unbound. The `./generators` subpath adds the
142
+ // `jsonSchema` converter of Standard JSON Schema to the props.
186
143
  get '~standard'() {
187
144
  if (this.#standard === null) {
145
+ const async = hasAsync(this);
188
146
  const validate = (value, options) => {
189
- const result = this.check(value, options == null ? undefined : options.libraryOptions);
190
- return result.valid ? { value } : { issues: result.issues };
147
+ const libraryOptions = options == null ? undefined : options.libraryOptions;
148
+ if (async) return this.parseAsync(value, libraryOptions).then(standardize);
149
+ return standardize(this.parse(value, libraryOptions));
191
150
  };
192
151
  this.#standard = { version: 1, vendor: 'alexify.metaschema', validate };
193
152
  }
@@ -197,8 +156,9 @@ class Schema extends SchemaMetadata {
197
156
  get types() {
198
157
  if (this.namespaces.size === 0) return TYPES;
199
158
  if (this.#types === null) {
200
- const types = Array.from(this.namespaces).map((ns) => ns.types);
201
- this.#types = Object.assign(Object.create(null), ...types);
159
+ const types = Object.create(null);
160
+ for (const ns of this.namespaces) Object.assign(types, ns.types);
161
+ this.#types = types;
202
162
  }
203
163
  return this.#types;
204
164
  }
@@ -232,33 +192,101 @@ class Schema extends SchemaMetadata {
232
192
  // Validates a value: every problem is collected as an issue, and the result
233
193
  // never throws because of the value. `options`: root (the label of the
234
194
  // error lines, the schema name by default), maxErrors, unknown ('reject'
235
- // or 'ignore' keys the schema does not have), messages (a locale).
195
+ // or 'ignore' keys the schema does not have), references, messages (a
196
+ // locale). A validator that returns a promise is an error here.
197
+ // `createContext` is called directly in every method here, never through a
198
+ // helper: V8 inlines the allocation into `check` that way (the context is
199
+ // the one allocation of a valid check), and a method in between cost 7%.
236
200
  check(source, options) {
237
201
  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
- }
202
+ if (this.#tracked) context.source = source;
242
203
  this[RUN](source, context);
243
- finalize(context.issues, context.messages);
244
- return new ValidationResult(context);
204
+ return resultOf(context);
205
+ }
206
+
207
+ // The same check, with the validators that return a promise settled after
208
+ // the walk, in field order.
209
+ async checkAsync(source, options) {
210
+ const context = createContext(options, this.name, this.unknown);
211
+ context.async = [];
212
+ if (this.#tracked) context.source = source;
213
+ this[RUN](source, context);
214
+ if (context.async.length > 0) await settle(context);
215
+ return resultOf(context);
216
+ }
217
+
218
+ #pass(phase, source, context) {
219
+ if (this.#codec === null) this.#codec = infoOf(this);
220
+ return apply(this.#codec, this, source, context, undefined, phase, wantOf(phase, context));
245
221
  }
246
222
 
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');
223
+ // The defaults of the schema over a value, before its check; the objects
224
+ // met on the way down are not the check's, and a value that loops through
225
+ // its references is checked as it was given.
226
+ #prepare(source, context) {
227
+ const prepared = this.#pass(PREPARE, source, context);
228
+ const value = looped(context) ? source : prepared;
229
+ context.seen = null;
230
+ if (this.#tracked) context.source = value;
231
+ return value;
232
+ }
233
+
234
+ // Validates a value and builds the value of the program from it: the
235
+ // defaults fill the missing keys, the check runs, and a valid value goes
236
+ // through `unknown: 'strip'`, the decoders of its fields (the parts of a
237
+ // value before the value) and the schema's own `parse`. `{ valid, value,
238
+ // issues }`: the value is undefined when invalid, and the value given when
239
+ // there was nothing to apply; the value given is never written to.
240
+ parse(source, options) {
241
+ const context = createContext(options, this.name, this.unknown, true);
242
+ const value = this.#prepare(source, context);
243
+ this[RUN](value, context);
244
+ const output = context.count === 0 ? this.#pass(FINISH, value, context) : undefined;
245
+ return parsed(context, output);
246
+ }
247
+
248
+ async parseAsync(source, options) {
249
+ const context = createContext(options, this.name, this.unknown, true);
250
+ context.async = [];
251
+ const value = this.#prepare(source, context);
252
+ this[RUN](value, context);
253
+ if (context.async.length > 0) await settle(context);
254
+ let output;
255
+ if (context.count === 0) {
256
+ // Only a promise of the pass is awaited: a thenable in the value is data.
257
+ output = this.#pass(FINISH, value, context);
258
+ if (output instanceof Promise) output = (await output).value;
259
+ }
260
+ return parsed(context, output);
261
+ }
262
+
263
+ // The other direction: the schema's own `serialize`, then the serializers
264
+ // of the fields, from the value down to its parts. `{ value }`, or with
265
+ // `options.check` the verdict of `check` over the result as well.
266
+ serialize(source, options) {
267
+ const context = createContext(options, this.name, this.unknown);
268
+ const value = this.#pass(SERIALIZE, source, context);
269
+ if (options === undefined || options.check !== true) return { value };
270
+ context.seen = null;
271
+ if (this.#tracked) context.source = value;
272
+ this[RUN](value, context);
273
+ finalize(context.issues, context.messages);
274
+ return { valid: context.count === 0, value, issues: context.issues };
252
275
  }
253
276
 
277
+ // The types and the Standard Schema props depend on the namespaces (the
278
+ // latter through the entities an async validator may be in), so both are
279
+ // rebuilt on the next use.
254
280
  attach(...namespaces) {
255
281
  for (const ns of namespaces) this.namespaces.add(ns);
256
282
  this.#types = null;
283
+ this.#standard = null;
257
284
  }
258
285
 
259
286
  detach(...namespaces) {
260
287
  for (const ns of namespaces) this.namespaces.delete(ns);
261
288
  this.#types = null;
289
+ this.#standard = null;
262
290
  }
263
291
 
264
292
  toString() {
@@ -0,0 +1,111 @@
1
+ // The model as data: `model.toJSON()` writes the entities of a model, their
2
+ // fields and the types they use as plain JSON, in dependency order and with
3
+ // a fixed key order, so that two builds of one model give the same text and
4
+ // a committed snapshot is a baseline a later model can be compared with
5
+ // (Drizzle's approach to migrations, without a database). A function has no
6
+ // JSON form and is written as `{ $function: true }` wherever it stands (a
7
+ // validate, a decoder, a default factory, a calculated field); a bigint and a
8
+ // Date are tagged the same way, a RegExp is its source. The metadata of the
9
+ // program (`database`, the `custom` metadata of a kind, an index definition)
10
+ // is written as given. `fromJSON` of the `./model` subpath reads it back.
11
+ const { hasBrand, define } = require('./util.js');
12
+
13
+ const FORMAT = 1;
14
+
15
+ // The own keys of an object, in order, each value written out.
16
+ const objectOf = (value) => {
17
+ const out = {};
18
+ for (const key of Object.keys(value)) {
19
+ const item = value[key];
20
+ if (item !== undefined) define(out, key, valueOf(item));
21
+ }
22
+ return out;
23
+ };
24
+
25
+ // A value of a definition as JSON: a built field as its snapshot, a tag for
26
+ // a function, a bigint or a Date; what has no JSON form at all (a symbol,
27
+ // NaN) is left to JSON.stringify, which drops or nulls it.
28
+ const valueOf = (value) => {
29
+ const type = typeof value;
30
+ if (type === 'function') return { $function: true };
31
+ if (type === 'bigint') return { $bigint: String(value) };
32
+ if (type !== 'object' || value === null) return value;
33
+ if (hasBrand(value, 'Type')) return fieldOf(value);
34
+ if (Array.isArray(value)) {
35
+ const list = [];
36
+ for (let index = 0; index < value.length; index += 1) list.push(valueOf(value[index]));
37
+ return list;
38
+ }
39
+ const name = value.constructor?.name;
40
+ if (name === 'RegExp') {
41
+ return value.flags === 'u' ? value.source : { source: value.source, flags: value.flags };
42
+ }
43
+ if (name === 'Date') return { $date: value.toISOString() };
44
+ return objectOf(value);
45
+ };
46
+
47
+ // A field: its type and whether it is required first, then its other keys
48
+ // sorted, so the text does not depend on how the definition was written.
49
+ const fieldOf = (field) => {
50
+ const out = { type: field.type, required: field.required };
51
+ for (const key of Object.keys(field).sort()) {
52
+ const item = field[key];
53
+ if (key !== 'root' && item !== undefined) out[key] = valueOf(item);
54
+ }
55
+ return out;
56
+ };
57
+
58
+ // An entity: its metadata, then its fields (`fields`) or, for a schema of
59
+ // one type, that type (`type`). The functions of the schema itself (its
60
+ // validate, parse, serialize and format) are written among the fields, as
61
+ // the ones of a nested struct are.
62
+ const entityOf = (schema) => {
63
+ const { kind, scope, store, allow, parent, unknown, custom, options, fields, indexes } = schema;
64
+ const out = { kind, scope, store, allow, parent, unknown, custom };
65
+ if (hasBrand(fields, 'Struct')) {
66
+ out.fields = objectOf(fields);
67
+ for (const key in options) if (options[key] !== null) out.fields[key] = valueOf(options[key]);
68
+ } else out.type = fieldOf(fields);
69
+ const own = {};
70
+ // A `many` field is recorded with the indexes and is not one.
71
+ for (const key in indexes) if (indexes[key].many === undefined) own[key] = indexes[key];
72
+ out.indexes = own;
73
+ out.relations = valueOf(Array.from(schema.relations));
74
+ return out;
75
+ };
76
+
77
+ // The types the entities use, by name: an alias as its `js`, a type with a
78
+ // check of its own as `check: true` with its kind, a built-in only when it
79
+ // carries metadata.
80
+ const typesOf = (model) => {
81
+ const names = new Set();
82
+ for (const entity of model.entities.values()) {
83
+ for (const name of entity.references) names.add(name);
84
+ }
85
+ const out = {};
86
+ for (const name of Array.from(names).sort()) {
87
+ const Type = model.types[name];
88
+ if (Type === undefined) continue;
89
+ const { source } = Type;
90
+ const entry = {};
91
+ if (source !== undefined) {
92
+ if (source.js !== undefined) entry.js = source.js;
93
+ else {
94
+ entry.kind = Type.kind;
95
+ entry.check = true;
96
+ }
97
+ }
98
+ entry.metadata = objectOf(Type.metadata);
99
+ if (source !== undefined || Object.keys(entry.metadata).length > 0) out[name] = entry;
100
+ }
101
+ return out;
102
+ };
103
+
104
+ // The entities in dependency order (`model.order`).
105
+ const snapshotOf = (model) => {
106
+ const entities = {};
107
+ for (const name of model.order) define(entities, name, entityOf(model.entities.get(name)));
108
+ return { format: FORMAT, database: model.database, types: typesOf(model), entities };
109
+ };
110
+
111
+ module.exports = { FORMAT, snapshotOf };
package/src/struct.js CHANGED
@@ -4,11 +4,29 @@ const { SchemaDefinitionError } = require('./errors.js');
4
4
 
5
5
  // What a struct computes once at construction, kept on the dictionary under a
6
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.
7
+ // exposes it too: { plan, known, calculated, check }, the plan being one
8
+ // frozen entry per validated field, `known` the dictionary of the keys a
9
+ // value may carry, `calculated` the keys of the calculated fields among them,
10
+ // and `check` the compiled check over the plan.
10
11
  const STRUCT = Symbol.for('alexify.metaschema.struct');
11
12
 
13
+ // The functions of a nested definition that are the struct's own validate,
14
+ // decoder and serializer (as they are options at the root): they stay in the
15
+ // fields, where a calculated field lives, but a value has no key by that name.
16
+ const CODEC_KEYS = new Set(['validate', 'parse', 'serialize']);
17
+
18
+ const invalidAliases = (reason) => new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason);
19
+
20
+ const ALIASES = 'Option "aliases" needs a list of key names';
21
+
22
+ // The key a value carries for a field that has nothing under its own key: a
23
+ // field renamed with `aliases: ['old']` is still read from its old key, and
24
+ // the field's own key when the value has none of them.
25
+ const aliasOf = (value, aliases, name) => {
26
+ for (const alias of aliases) if (Object.hasOwn(value, alias)) return alias;
27
+ return name;
28
+ };
29
+
12
30
  // A field is read with a keyed load, and `Object.hasOwn` is consulted only
13
31
  // when the value is undefined, to tell a missing key from one set to
14
32
  // undefined. A field named after a member of Object.prototype (`toString`,
@@ -31,8 +49,32 @@ const scanUnknown = (value, known, context) => {
31
49
  // never touches the path. Unknown keys are looked for only when the value has
32
50
  // more keys than the plan found, so a value with exactly the expected keys is
33
51
  // never scanned twice.
52
+ // A field with nothing under its own key (absent, inherited, or own and set
53
+ // to undefined): an alias may hold the value, and the check reports it under
54
+ // the key it found it under. Then the same for an optional field, a required
55
+ // one asks which (own and undefined is a type error). Kept out of the loop
56
+ // of the struct check, whose body is the fast path of a present field; the
57
+ // return is what the field adds to the keys found.
58
+ const checkAbsent = (entry, value, context, name) => {
59
+ const under = aliasOf(value, entry.aliases, name);
60
+ let item;
61
+ if (under !== name) {
62
+ item = value[under];
63
+ context.renamed = true;
64
+ }
65
+ if (item === undefined) {
66
+ if (!entry.required) return 0;
67
+ if (!Object.hasOwn(value, under)) {
68
+ issues.required(context, name);
69
+ return 0;
70
+ }
71
+ }
72
+ entry.check(item, context, under);
73
+ return 1;
74
+ };
75
+
34
76
  const compileStruct = (plan, known) => (value, context, key) => {
35
- if (value === null || typeof value !== 'object') {
77
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
36
78
  issues.type(context, 'object', value, key);
37
79
  return;
38
80
  }
@@ -44,20 +86,10 @@ const compileStruct = (plan, known) => (value, context, key) => {
44
86
  const entry = plan[index];
45
87
  const name = entry.key;
46
88
  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);
89
+ if (item !== undefined && (!entry.own || Object.hasOwn(value, name))) {
90
+ found += 1;
91
+ entry.check(item, context, name);
92
+ } else found += checkAbsent(entry, value, context, name);
61
93
  }
62
94
  if (context.unknown === 'reject' && context.count < context.limit) {
63
95
  let total = 0;
@@ -68,6 +100,25 @@ const compileStruct = (plan, known) => (value, context, key) => {
68
100
  if (nested) context.path.pop();
69
101
  };
70
102
 
103
+ // A key a value may carry: a field, a calculated field or an alias, each
104
+ // once.
105
+ const know = (known, key) => {
106
+ if (key in known) throw invalidAliases(`Key "${key}" is a field or an alias already`);
107
+ known[key] = true;
108
+ };
109
+
110
+ // The aliases of a field: the keys it is also read from, as a list of names.
111
+ const aliasesOf = (field, known) => {
112
+ const { aliases } = field;
113
+ if (aliases === undefined) return [];
114
+ if (!Array.isArray(aliases) || aliases.length === 0) throw invalidAliases(ALIASES);
115
+ for (const alias of aliases) {
116
+ if (typeof alias !== 'string' || alias === '') throw invalidAliases(ALIASES);
117
+ know(known, alias);
118
+ }
119
+ return aliases;
120
+ };
121
+
71
122
  // A struct is a null-prototype dictionary of field name -> Type (or the
72
123
  // function of a calculated field), not a class instance with methods: a field
73
124
  // may be named `check`, `name` or `constructor`, and an input key such as
@@ -77,14 +128,18 @@ const createStruct = (defs, prep) => {
77
128
  const fields = Object.create(null);
78
129
  const plan = [];
79
130
  const known = Object.create(null);
131
+ const calculated = [];
80
132
  for (const key of Object.keys(defs)) {
81
133
  const entry = defs[key];
82
134
  const { field, required } = formatters.key(key, entry?.required);
83
135
  try {
84
136
  const { Type, defs: typeDefs } = prep.parse(entry);
85
137
  if (!Type) {
86
- fields[key] = entry;
87
- known[key] = true;
138
+ fields[field] = entry;
139
+ if (!CODEC_KEYS.has(field)) {
140
+ know(known, field);
141
+ calculated.push(field);
142
+ }
88
143
  continue;
89
144
  }
90
145
  // The key ('tags?') and the definition ('?string', required: false)
@@ -93,12 +148,13 @@ const createStruct = (defs, prep) => {
93
148
  typeDefs.required = (typeDefs.required ?? true) && required;
94
149
  const child = new Type(typeDefs, prep);
95
150
  fields[field] = child;
96
- known[field] = true;
151
+ know(known, field);
97
152
  plan.push({
98
153
  key: field,
99
154
  type: child,
100
155
  required: child.required,
101
156
  own: field in Object.prototype,
157
+ aliases: aliasesOf(child, known),
102
158
  check: child.check,
103
159
  });
104
160
  } catch (error) {
@@ -107,7 +163,8 @@ const createStruct = (defs, prep) => {
107
163
  }
108
164
  }
109
165
  Object.freeze(plan);
110
- const compiled = Object.freeze({ plan, known, check: compileStruct(plan, known) });
166
+ Object.freeze(calculated);
167
+ const compiled = Object.freeze({ plan, known, calculated, check: compileStruct(plan, known) });
111
168
  Object.defineProperty(fields, BRAND, { value: 'Struct' });
112
169
  Object.defineProperty(fields, STRUCT, { value: compiled });
113
170
  return fields;
@@ -117,4 +174,4 @@ const isStruct = (fields) => hasBrand(fields, 'Struct');
117
174
 
118
175
  const checkOf = (fields) => fields[STRUCT].check;
119
176
 
120
- module.exports = { STRUCT, createStruct, isStruct, checkOf };
177
+ module.exports = { STRUCT, createStruct, isStruct, checkOf, aliasOf };
package/src/types.js CHANGED
@@ -25,17 +25,14 @@ const customTypeError = (name, reason) =>
25
25
 
26
26
  const createType = (name, prototype) => {
27
27
  class Type extends AbstractType {
28
- static metadata = {};
28
+ // A null-prototype dictionary: a metadata key may be anything.
29
+ static metadata = Object.create(null);
29
30
  static type = name;
30
31
  static kind = prototype.kind;
31
32
  static rules = new Set(prototype.rules);
32
33
  // The definition keys the type reads; the lint reports the others.
33
34
  static options = new Set(prototype.options);
34
35
 
35
- static assign(key, value) {
36
- this.metadata[key] = value;
37
- }
38
-
39
36
  constructor(def, preprocessor) {
40
37
  super(def, preprocessor);
41
38
  const { type } = this;
@@ -61,12 +58,9 @@ const TYPES = createTypes(PROTOTYPES);
61
58
 
62
59
  const createRegistry = () => createTypes(PROTOTYPES);
63
60
 
64
- const updateTypeMetadata = (Type, metadata = {}) => {
65
- for (const pair of Object.entries(metadata)) {
66
- const key = pair[0];
67
- const value = pair[1];
68
- Type.assign(key, value);
69
- }
61
+ // The own keys of the metadata given, as data: the table has no prototype.
62
+ const updateTypeMetadata = (Type, metadata) => {
63
+ Object.assign(Type.metadata, metadata);
70
64
  };
71
65
 
72
66
  // A custom prototype brings `construct` and `checkType`; a built-in one, reused