@alexify/metaschema 3.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.
package/src/schema.js CHANGED
@@ -10,7 +10,16 @@ const { finalize, runValidate, settle } = require('./issues.js');
10
10
  const { SchemaDefinitionError } = require('./errors.js');
11
11
  const { createStruct, isStruct, checkOf } = require('./struct.js');
12
12
  const { warning, lintSchema } = require('./lint.js');
13
- const { PREPARE, FINISH, SERIALIZE, infoOf, apply, looped, hasAsync } = require('./codec.js');
13
+ const {
14
+ PREPARE,
15
+ FINISH,
16
+ SERIALIZE,
17
+ infoOf,
18
+ apply,
19
+ looped,
20
+ hasAsync,
21
+ wantOf,
22
+ } = require('./codec.js');
14
23
 
15
24
  // The validation of a schema inside an existing context: `check` starts one,
16
25
  // and a reference field checks its target entity within the context of the
@@ -208,7 +217,7 @@ class Schema extends SchemaMetadata {
208
217
 
209
218
  #pass(phase, source, context) {
210
219
  if (this.#codec === null) this.#codec = infoOf(this);
211
- return apply(this.#codec, this, source, context, undefined, phase);
220
+ return apply(this.#codec, this, source, context, undefined, phase, wantOf(phase, context));
212
221
  }
213
222
 
214
223
  // The defaults of the schema over a value, before its check; the objects
@@ -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
@@ -15,6 +15,18 @@ const STRUCT = Symbol.for('alexify.metaschema.struct');
15
15
  // fields, where a calculated field lives, but a value has no key by that name.
16
16
  const CODEC_KEYS = new Set(['validate', 'parse', 'serialize']);
17
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
+
18
30
  // A field is read with a keyed load, and `Object.hasOwn` is consulted only
19
31
  // when the value is undefined, to tell a missing key from one set to
20
32
  // undefined. A field named after a member of Object.prototype (`toString`,
@@ -37,6 +49,30 @@ const scanUnknown = (value, known, context) => {
37
49
  // never touches the path. Unknown keys are looked for only when the value has
38
50
  // more keys than the plan found, so a value with exactly the expected keys is
39
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
+
40
76
  const compileStruct = (plan, known) => (value, context, key) => {
41
77
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
42
78
  issues.type(context, 'object', value, key);
@@ -50,20 +86,10 @@ const compileStruct = (plan, known) => (value, context, key) => {
50
86
  const entry = plan[index];
51
87
  const name = entry.key;
52
88
  const item = value[name];
53
- if (item === undefined) {
54
- // Absent, or own and set to undefined: the same for an optional field,
55
- // a required one asks which (the latter is a type error).
56
- if (!entry.required) continue;
57
- if (!Object.hasOwn(value, name)) {
58
- issues.required(context, name);
59
- continue;
60
- }
61
- } else if (entry.own && !Object.hasOwn(value, name)) {
62
- if (entry.required) issues.required(context, name);
63
- continue;
64
- }
65
- found += 1;
66
- 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);
67
93
  }
68
94
  if (context.unknown === 'reject' && context.count < context.limit) {
69
95
  let total = 0;
@@ -74,6 +100,25 @@ const compileStruct = (plan, known) => (value, context, key) => {
74
100
  if (nested) context.path.pop();
75
101
  };
76
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
+
77
122
  // A struct is a null-prototype dictionary of field name -> Type (or the
78
123
  // function of a calculated field), not a class instance with methods: a field
79
124
  // may be named `check`, `name` or `constructor`, and an input key such as
@@ -92,7 +137,7 @@ const createStruct = (defs, prep) => {
92
137
  if (!Type) {
93
138
  fields[field] = entry;
94
139
  if (!CODEC_KEYS.has(field)) {
95
- known[field] = true;
140
+ know(known, field);
96
141
  calculated.push(field);
97
142
  }
98
143
  continue;
@@ -103,12 +148,13 @@ const createStruct = (defs, prep) => {
103
148
  typeDefs.required = (typeDefs.required ?? true) && required;
104
149
  const child = new Type(typeDefs, prep);
105
150
  fields[field] = child;
106
- known[field] = true;
151
+ know(known, field);
107
152
  plan.push({
108
153
  key: field,
109
154
  type: child,
110
155
  required: child.required,
111
156
  own: field in Object.prototype,
157
+ aliases: aliasesOf(child, known),
112
158
  check: child.check,
113
159
  });
114
160
  } catch (error) {
@@ -128,4 +174,4 @@ const isStruct = (fields) => hasBrand(fields, 'Struct');
128
174
 
129
175
  const checkOf = (fields) => fields[STRUCT].check;
130
176
 
131
- module.exports = { STRUCT, createStruct, isStruct, checkOf };
177
+ module.exports = { STRUCT, createStruct, isStruct, checkOf, aliasOf };