@alexify/metaschema 1.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +551 -1
  2. package/README.md +235 -34
  3. package/SECURITY.md +32 -11
  4. package/index.d.ts +798 -23
  5. package/package.json +30 -6
  6. package/src/codec.js +490 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +512 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +141 -0
  12. package/src/errors.js +10 -1
  13. package/src/generators/index.d.ts +29 -0
  14. package/src/generators/index.js +90 -0
  15. package/src/generators/jsonschema.js +535 -0
  16. package/src/generators/typescript.js +237 -0
  17. package/src/index.js +1 -3
  18. package/src/issues.js +291 -0
  19. package/src/kinds.js +9 -12
  20. package/src/lint.js +98 -0
  21. package/src/locales/en.d.ts +5 -0
  22. package/src/locales/en.js +66 -0
  23. package/src/locales/uk.d.ts +5 -0
  24. package/src/locales/uk.js +62 -0
  25. package/src/metadata.js +65 -119
  26. package/src/metautil.js +8 -1
  27. package/src/model.js +31 -20
  28. package/src/preprocessor.js +45 -27
  29. package/src/prototypes/abstract.js +101 -51
  30. package/src/prototypes/collections.js +106 -41
  31. package/src/prototypes/json.js +9 -5
  32. package/src/prototypes/reference.js +91 -20
  33. package/src/prototypes/scalars.js +124 -16
  34. package/src/prototypes/schema.js +31 -6
  35. package/src/prototypes/tuple.js +57 -29
  36. package/src/prototypes/union.js +139 -0
  37. package/src/result.js +115 -0
  38. package/src/rules.js +185 -0
  39. package/src/runtime/browser.js +2 -2
  40. package/src/runtime/node.js +4 -2
  41. package/src/schema.js +181 -68
  42. package/src/struct.js +101 -33
  43. package/src/types.js +14 -14
  44. package/src/util.js +41 -50
@@ -1,72 +1,122 @@
1
- const { ValidationResult } = require('../metadata.js');
2
- const { BRAND, INSPECT, ancestors, issue, formatters, checks } = require('../util.js');
1
+ const { BRAND, INSPECT } = require('../util.js');
2
+ const { FORMAT, notApplicable, compileRules } = require('../rules.js');
3
+ const { runValidate, runCheckType } = require('../issues.js');
3
4
  const { SchemaDefinitionError } = require('../errors.js');
4
5
 
5
6
  // Keys of a field definition become properties of the field, so a key that
6
- // names one of its methods (or the prototype itself) would replace it.
7
- const RESERVED = new Set(['__proto__', 'prototype']);
7
+ // names one of its methods (or the prototype itself) would replace it. The
8
+ // methods of the type contract are reserved whether the type has them or not.
9
+ const RESERVED = new Set(['__proto__', 'prototype', 'check', 'checkType', 'compile', 'construct']);
8
10
 
9
11
  const reservedKey = (key) =>
10
12
  new SchemaDefinitionError('ERR_RESERVED_KEY', `Key "${key}" is reserved in a field definition`);
11
13
 
12
- class AbstractType {
13
- static checks = Object.create(null);
14
- static formatters = Object.create(null);
15
-
16
- // The rule checks that apply to this field, chosen once at construction:
17
- // `length` only matters to a field that has a length, and check is the hot
18
- // path.
19
- #rules;
20
-
21
- static setRules(rules = []) {
22
- for (const rule of rules) {
23
- if (formatters[rule]) AbstractType.formatters[rule] = formatters[rule];
24
- if (checks[rule]) AbstractType.checks[rule] = checks[rule];
25
- }
14
+ const invalidNullable = () =>
15
+ new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "nullable" needs a boolean');
16
+
17
+ const invalidCodec = (key) =>
18
+ new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a function`);
19
+
20
+ // `parse` (the decoder) and `serialize` are read by parse and serialize, on
21
+ // any type; a definition that gave them anything else can never work.
22
+ const checkCodecs = (type) => {
23
+ if (type.parse !== undefined && typeof type.parse !== 'function') throw invalidCodec('parse');
24
+ if (type.serialize !== undefined && typeof type.serialize !== 'function') {
25
+ throw invalidCodec('serialize');
26
26
  }
27
+ };
28
+
29
+ // A nullable field accepts null in place of a value of its type, whatever
30
+ // its rules; `required` still says whether the key must be there.
31
+ const nullable = (inner) => (value, context, key) => {
32
+ if (value === null) return;
33
+ inner(value, context, key);
34
+ };
35
+
36
+ // The check of a field with rules or a validate function: the type check,
37
+ // then the rules, then the validate function. A type failure cancels the
38
+ // rest (a length or a validator makes no sense for a value of another type),
39
+ // and validate runs only on a value that passed everything before it, so it
40
+ // can rely on the type and the rules. A field with neither is its type check
41
+ // alone.
42
+ const withRules = (type, inner, rules) => {
43
+ const { required, validate } = type;
44
+ return (value, context, key) => {
45
+ if (value == null && !required) return;
46
+ const before = context.count;
47
+ inner(value, context, key);
48
+ if (context.count !== before) return;
49
+ for (let index = 0; index < rules.length; index += 1) {
50
+ if (context.count >= context.limit) break;
51
+ rules[index](value, context, key);
52
+ }
53
+ if (validate && context.count === before) {
54
+ const nested = key !== undefined;
55
+ if (nested) context.path.push(key);
56
+ runValidate(type, validate, value, context);
57
+ if (nested) context.path.pop();
58
+ }
59
+ };
60
+ };
61
+
62
+ class AbstractType {
63
+ // The rules the type accepts and the definition keys it reads, by name; a
64
+ // type class sets its own.
65
+ static rules = new Set();
66
+ static options = new Set();
67
+
68
+ // The compiled check of the field: a closure built once from the field,
69
+ // kept out of its definition (toJSON, util.inspect) as a private field.
70
+ #check;
27
71
 
28
72
  constructor(def, preprocessor) {
29
73
  this.root = preprocessor.root;
30
- const { formatters: typeFormatters } = AbstractType;
31
- for (const pair of Object.entries(def)) {
32
- const key = pair[0];
33
- const value = pair[1];
74
+ const { rules } = this.constructor;
75
+ for (const key of Object.keys(def)) {
76
+ const value = def[key];
34
77
  if (key === 'type' || key === this.type) continue;
35
78
  if (RESERVED.has(key) || typeof this[key] === 'function') throw reservedKey(key);
36
- if (typeFormatters[key]) this[key] = typeFormatters[key](value);
37
- else this[key] = value;
79
+ const format = FORMAT[key];
80
+ if (format === undefined) {
81
+ this[key] = value;
82
+ continue;
83
+ }
84
+ if (!rules.has(key)) throw notApplicable(key, this.type, rules);
85
+ this[key] = format(value);
38
86
  }
39
87
  this.construct(def, preprocessor);
40
88
  if (this.type) this.root.references.add(this.type);
41
- const rules = [];
42
- for (const name of Object.keys(AbstractType.checks)) {
43
- if (this[name]) rules.push(AbstractType.checks[name]);
44
- }
45
- this.#rules = rules;
89
+ if (this.nullable !== undefined && typeof this.nullable !== 'boolean') throw invalidNullable();
90
+ checkCodecs(this);
91
+ // The rule checks that apply to this field, compiled once: a field
92
+ // without rules is its type check alone, and check is the hot path.
93
+ const checks = compileRules(this);
94
+ const inner = this.compile();
95
+ const plain = checks.length === 0 && !this.validate;
96
+ const check = plain ? inner : withRules(this, inner, checks);
97
+ this.#check = this.nullable === true ? nullable(check) : check;
46
98
  }
47
99
 
48
- check(value, path) {
49
- const result = new ValidationResult(path);
50
- const isEmpty = value === null || value === undefined;
51
- if (!this.required && isEmpty) return result;
52
- const isObject = typeof value === 'object' && value !== null;
53
- if (isObject && ancestors.has(value)) {
54
- return result.add(issue('circular', path, 'is a circular reference'));
55
- }
56
- if (isObject) ancestors.add(value);
57
- try {
58
- result.add(this.checkType(value, path), 'type');
59
- if (this.validate && !result.full) result.add(this.validate(value, path));
60
- for (const rule of this.#rules) {
61
- if (result.full) break;
62
- result.add(rule(value, this, path));
63
- }
64
- return result;
65
- } catch (error) {
66
- return result.add(issue('exception', path, `validation failed ${error}`));
67
- } finally {
68
- if (isObject) ancestors.delete(value);
69
- }
100
+ // Records the problems of a value into the context of the current check,
101
+ // under `key` when the field is reached through one.
102
+ get check() {
103
+ return this.#check;
104
+ }
105
+
106
+ // The type check of a field, as a closure built once from the field. A
107
+ // built-in prototype compiles its own; a custom type has a
108
+ // `checkType(value, path)` that returns messages, run through the
109
+ // validator contract.
110
+ compile() {
111
+ const type = this;
112
+ const { required } = this;
113
+ return (value, context, key) => {
114
+ if (value == null && !required) return;
115
+ const nested = key !== undefined;
116
+ if (nested) context.path.push(key);
117
+ runCheckType(type, value, context);
118
+ if (nested) context.path.pop();
119
+ };
70
120
  }
71
121
 
72
122
  toJSON() {
@@ -1,65 +1,140 @@
1
- const { ValidationResult } = require('../metadata.js');
2
- const { issue, shorten } = require('../util.js');
1
+ const { issues } = require('../issues.js');
2
+ const { SchemaDefinitionError } = require('../errors.js');
3
3
 
4
+ // The keys of a keyed collection are strings or numbers; anything else can
5
+ // never match a key, and the JIT quotes the key type into its source.
6
+ const invalidKey = (type) => {
7
+ const reason = `Type "${type}" needs a key type of "string" or "number"`;
8
+ return new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason);
9
+ };
10
+
11
+ // Collections iterate their source directly: an object with for...in over
12
+ // its own keys, a Map and a Set through their iterators, an array by index.
13
+ // A collection pushes its own key on the path before its elements and pops
14
+ // it after them; an element is checked with its key or index.
4
15
  const object = {
5
16
  rules: ['length'],
17
+ options: ['key', 'value', 'length'],
6
18
  kind: 'struct',
7
19
 
8
20
  construct(def, prep) {
9
21
  const { type } = this;
10
22
  const { [type]: short, key, value } = def;
11
- const pair = short ? Object.entries(short)[0] : [key, value];
12
- const keyType = pair[0];
13
- const valueDef = pair[1];
23
+ let keyType = key;
24
+ let valueDef = value;
25
+ // The shorthand holds one pair: `{ object: { string: 'number' } }`.
26
+ if (short !== null && typeof short === 'object') {
27
+ for (const name in short) {
28
+ if (!Object.hasOwn(short, name)) continue;
29
+ keyType = name;
30
+ valueDef = short[name];
31
+ break;
32
+ }
33
+ }
34
+ if (keyType !== 'string' && keyType !== 'number') throw invalidKey(type);
14
35
  this.key = keyType;
15
36
  const { Type, defs } = prep.parse(valueDef);
16
37
  this.value = new Type(defs, prep);
17
38
  },
18
39
 
19
- checkType(source, path) {
20
- if (!this.isInstance(source)) {
21
- return issue('type', path, `not of expected type: ${this.type}`);
22
- }
23
- const entries = this.entries(source);
24
- if (entries.length === 0 && this.required) return issue('required', path, 'is required');
25
- const result = new ValidationResult(path);
26
- for (const pair of entries) {
27
- if (result.full) break;
28
- const field = pair[0];
29
- const fieldValue = pair[1];
30
- // oxlint-disable-next-line valid-typeof
31
- if (typeof field !== this.key) {
32
- return result.add(issue('type', path, `keys must be of type ${this.key}`));
40
+ compile() {
41
+ const { required, type, key: keyType } = this;
42
+ const { check } = this.value;
43
+ return (value, context, key) => {
44
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
45
+ if (!required && value == null) return;
46
+ issues.type(context, type, value, key);
47
+ return;
33
48
  }
34
- result.add(this.value.check(fieldValue, `${path}.${shorten(field)}`));
35
- }
36
- return result;
49
+ const nested = key !== undefined;
50
+ if (nested) context.path.push(key);
51
+ let count = 0;
52
+ for (const name in value) {
53
+ if (!Object.hasOwn(value, name)) continue;
54
+ if (context.count >= context.limit) break;
55
+ count += 1;
56
+ // oxlint-disable-next-line valid-typeof
57
+ if (typeof name !== keyType) {
58
+ issues.key(context, keyType, name);
59
+ break;
60
+ }
61
+ check(value[name], context, name);
62
+ }
63
+ if (count === 0 && required) issues.required(context);
64
+ if (nested) context.path.pop();
65
+ };
37
66
  },
38
67
 
39
68
  isInstance(value) {
40
69
  return value !== null && typeof value === 'object' && !Array.isArray(value);
41
70
  },
42
-
43
- entries(value) {
44
- return Object.entries(value);
45
- },
46
71
  };
47
72
 
48
73
  const map = {
49
74
  ...object,
50
75
 
76
+ compile() {
77
+ const { required, type, key: keyType } = this;
78
+ const { check } = this.value;
79
+ return (value, context, key) => {
80
+ if (value?.constructor?.name !== 'Map') {
81
+ if (!required && value == null) return;
82
+ issues.type(context, type, value, key);
83
+ return;
84
+ }
85
+ if (value.size === 0) {
86
+ if (required) issues.required(context, key);
87
+ return;
88
+ }
89
+ const nested = key !== undefined;
90
+ if (nested) context.path.push(key);
91
+ for (const pair of value) {
92
+ if (context.count >= context.limit) break;
93
+ const name = pair[0];
94
+ // oxlint-disable-next-line valid-typeof
95
+ if (typeof name !== keyType) {
96
+ issues.key(context, keyType, name);
97
+ break;
98
+ }
99
+ check(pair[1], context, name);
100
+ }
101
+ if (nested) context.path.pop();
102
+ };
103
+ },
104
+
51
105
  isInstance(value) {
52
106
  return value?.constructor?.name === 'Map';
53
107
  },
108
+ };
54
109
 
55
- entries(value) {
56
- return [...value.entries()];
57
- },
110
+ // An array and a Set are walked the same way, by position; only the type
111
+ // test differs.
112
+ const compileList = (type, isList) => {
113
+ const { required } = type;
114
+ const { check } = type.value;
115
+ const name = type.type;
116
+ return (value, context, key) => {
117
+ if (!isList(value)) {
118
+ if (!required && value == null) return;
119
+ issues.type(context, name, value, key);
120
+ return;
121
+ }
122
+ const nested = key !== undefined;
123
+ if (nested) context.path.push(key);
124
+ let index = 0;
125
+ for (const item of value) {
126
+ if (context.count >= context.limit) break;
127
+ check(item, context, index);
128
+ index += 1;
129
+ }
130
+ if (nested) context.path.pop();
131
+ };
58
132
  };
59
133
 
60
134
  const array = {
61
135
  kind: 'struct',
62
136
  rules: ['length'],
137
+ options: ['value', 'length'],
63
138
 
64
139
  construct(def, prep) {
65
140
  const { type } = this;
@@ -68,18 +143,8 @@ const array = {
68
143
  this.value = new Type(defs, prep);
69
144
  },
70
145
 
71
- checkType(source, path) {
72
- if (!this.isInstance(source)) {
73
- return issue('type', path, `not of expected type: ${this.type}`);
74
- }
75
- // A Set is copied to index it; an array is walked as it is.
76
- const value = Array.isArray(source) ? source : [...source];
77
- const result = new ValidationResult(path);
78
- for (let index = 0; index < value.length; index += 1) {
79
- if (result.full) break;
80
- result.add(this.value.check(value[index], `${path}[${index}]`));
81
- }
82
- return result;
146
+ compile() {
147
+ return compileList(this, this.isInstance);
83
148
  },
84
149
 
85
150
  isInstance(value) {
@@ -1,14 +1,18 @@
1
- const { issue } = require('../util.js');
1
+ const { issues } = require('../issues.js');
2
2
 
3
3
  const json = {
4
4
  kind: 'struct',
5
+ options: [],
5
6
 
6
7
  construct() {},
7
8
 
8
- checkType(value, path) {
9
- const isObject = value !== null && typeof value === 'object';
10
- if (!isObject) return issue('type', path, 'not of expected type: object');
11
- return null;
9
+ compile() {
10
+ const { required } = this;
11
+ return (value, context, key) => {
12
+ if (value !== null && typeof value === 'object') return;
13
+ if (!required && value == null) return;
14
+ issues.type(context, 'object', value, key);
15
+ };
12
16
  },
13
17
  };
14
18
 
@@ -1,9 +1,56 @@
1
1
  const { SchemaDefinitionError } = require('../errors.js');
2
- const { ValidationResult } = require('../metadata.js');
3
- const { issue } = require('../util.js');
2
+ const { RUN } = require('../util.js');
3
+ const { issues } = require('../issues.js');
4
+
5
+ const invalidEmbed = () =>
6
+ new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "embed" needs a boolean');
7
+
8
+ // A reference is the one place a schema can recurse (Category.parent is a
9
+ // Category), so it is where a value met again while it is still being
10
+ // checked is a cycle, reported instead of recursed into, and where a graph
11
+ // nested deeper than the check allows is reported instead of overflowing the
12
+ // stack.
13
+ const runReferenced = (schema, value, context, key) => {
14
+ if (value === null || typeof value !== 'object') {
15
+ schema[RUN](value, context, key);
16
+ return;
17
+ }
18
+ if (context.depth >= context.maxDepth) {
19
+ issues.depth(context, context.maxDepth, key);
20
+ return;
21
+ }
22
+ let { seen } = context;
23
+ if (seen === null) {
24
+ // The first embedded record creates the set, and the value the check
25
+ // started from joins it then, so a check that embeds nothing pays nothing.
26
+ seen = new Set();
27
+ if (context.source !== null) seen.add(context.source);
28
+ context.seen = seen;
29
+ }
30
+ if (seen.has(value)) {
31
+ issues.circular(context, key);
32
+ return;
33
+ }
34
+ seen.add(value);
35
+ context.depth += 1;
36
+ schema[RUN](value, context, key);
37
+ context.depth -= 1;
38
+ seen.delete(value);
39
+ };
40
+
41
+ // Whether a referenced value is the record itself (the graph view) or its
42
+ // id (the storage view): the mode of the check when it says so, otherwise
43
+ // the field's `embed`, otherwise the store of the target's kind. A stored
44
+ // kind lives in its own table, so a row holds its id; a memory kind has no
45
+ // table of its own, so it is part of the row.
46
+ const embeds = (schema, embed, mode) => {
47
+ if (mode !== 'kind') return mode === 'embed';
48
+ return embed === undefined ? schema.store !== 'persistent' : embed;
49
+ };
4
50
 
5
51
  const reference = {
6
52
  kind: 'struct',
53
+ options: ['one', 'many', 'embed'],
7
54
 
8
55
  construct(def) {
9
56
  const key = def.many === undefined ? 'one' : 'many';
@@ -12,31 +59,55 @@ const reference = {
12
59
  const reason = `Reference "${key}" needs an entity name, got ${JSON.stringify(target)}`;
13
60
  throw new SchemaDefinitionError('ERR_INVALID_REFERENCE', reason);
14
61
  }
15
- const relation = key === 'many' ? 'many-to-one' : 'one-to-many';
62
+ if (this.embed !== undefined && typeof this.embed !== 'boolean') throw invalidEmbed();
63
+ // Read from the referencing side: a `many` field holds the many end of
64
+ // a one-to-many relation, a single reference the many end of many-to-one.
65
+ const relation = key === 'many' ? 'one-to-many' : 'many-to-one';
16
66
  this[key] = target;
17
67
  this.type = target;
18
68
  this.root.relations.add({ to: target, type: relation });
19
69
  },
20
70
 
21
- checkType(source, path) {
22
- const { one, many, root } = this;
71
+ // The target is looked up at check time: entities of a model are built in
72
+ // any order and a namespace may be attached later.
73
+ compile() {
74
+ const { one, many, root, required, embed } = this;
23
75
  if (one) {
24
- const schema = root.findReference(one);
25
- if (!schema) return issue('reference', path, `Entity "${one}" is not found`);
26
- return schema.check(source, path);
27
- }
28
- const schema = root.findReference(many);
29
- if (!schema) return issue('reference', path, `Entity "${many}" is not found`);
30
- if (!Array.isArray(source)) {
31
- return issue('type', path, `not of expected type: array of ${many}`);
32
- }
33
- const result = new ValidationResult(path);
34
- for (let index = 0; index < source.length; index += 1) {
35
- if (result.full) break;
36
- result.add(schema.check(source[index], `${path}[${index}]`));
76
+ return (value, context, key) => {
77
+ if (!required && value == null) return;
78
+ const schema = root.findReference(one);
79
+ if (!schema) {
80
+ issues.reference(context, one, key);
81
+ return;
82
+ }
83
+ if (embeds(schema, embed, context.references)) runReferenced(schema, value, context, key);
84
+ else if (typeof value !== 'string') issues.type(context, 'string', value, key);
85
+ };
37
86
  }
38
- return result;
87
+ const expected = `array of ${many}`;
88
+ return (value, context, key) => {
89
+ if (!required && value == null) return;
90
+ const schema = root.findReference(many);
91
+ if (!schema) {
92
+ issues.reference(context, many, key);
93
+ return;
94
+ }
95
+ if (!Array.isArray(value)) {
96
+ issues.type(context, expected, value, key);
97
+ return;
98
+ }
99
+ const nested = key !== undefined;
100
+ if (nested) context.path.push(key);
101
+ const embedded = embeds(schema, embed, context.references);
102
+ for (let index = 0; index < value.length; index += 1) {
103
+ if (context.count >= context.limit) break;
104
+ const item = value[index];
105
+ if (embedded) runReferenced(schema, item, context, index);
106
+ else if (typeof item !== 'string') issues.type(context, 'string', item, index);
107
+ }
108
+ if (nested) context.path.pop();
109
+ };
39
110
  },
40
111
  };
41
112
 
42
- module.exports = { reference };
113
+ module.exports = { reference, embeds };