@alexify/metaschema 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/metadata.js CHANGED
@@ -1,79 +1,21 @@
1
1
  const { getKindMetadata } = require('./kinds.js');
2
- const { BRAND, hasBrand, limits, issue } = require('./util.js');
3
-
4
- const ERR_PREFIX = 'Field';
5
-
6
- const prefixed = (message, path) =>
7
- message.startsWith(ERR_PREFIX) ? message : `${ERR_PREFIX} "${path}" ${message}`;
8
-
9
- // Anything with a message is taken as an issue: the library's own, or a
10
- // { code, message } object returned by a custom validator.
11
- const isIssue = (error) =>
12
- error !== null && typeof error === 'object' && typeof error.message === 'string';
2
+ const { ValidationResult } = require('./result.js');
3
+ const { SchemaDefinitionError } = require('./errors.js');
13
4
  const OPTIONS = ['validate', 'parse', 'serialize', 'format'];
14
5
  const METADATA_COLLECTIONS = ['indexes', 'options'];
15
-
16
- class ValidationResult {
17
- #path;
18
-
19
- constructor(path = '') {
20
- this.#path = path;
21
- this.errors = [];
22
- this.issues = [];
23
- this.valid = true;
24
- }
25
-
26
- // True once the maxErrors of the current check is reached; loops stop early.
27
- get full() {
28
- return this.errors.length >= limits.maxErrors;
29
- }
30
-
31
- add(error, code = 'custom') {
32
- const issues = ValidationResult.isInstance(error)
33
- ? error.issues
34
- : ValidationResult.issuesOf(error, this.#path, code);
35
- // One by one: a spread call has an argument limit, and a validator may
36
- // legitimately return more messages than that.
37
- for (const entry of issues) {
38
- if (this.full) break;
39
- this.issues.push(entry);
40
- this.errors.push(entry.message);
41
- }
42
- this.valid = this.errors.length === 0;
43
- return this;
6
+ const UNKNOWN = ['reject', 'ignore'];
7
+
8
+ // The unknown-keys policy of a schema is the default of its `check`, so a
9
+ // value with keys the schema does not have is rejected or ignored without
10
+ // an option on every call; the option of a call still wins.
11
+ const unknownOf = (unknown) => {
12
+ if (unknown === undefined) return 'reject';
13
+ if (!UNKNOWN.includes(unknown)) {
14
+ const reason = `Schema metadata "unknown" must be "reject" or "ignore", got ${JSON.stringify(unknown)}`;
15
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
44
16
  }
45
-
46
- // Everything a check or validator may return, as issues: true, null and
47
- // undefined are nothing; false is a generic error; a string is a message;
48
- // an array holds any of these; an object with a message is an issue.
49
- static issuesOf(error, path = '', code = 'custom') {
50
- if (error === true || error === null || error === undefined) return [];
51
- if (ValidationResult.isInstance(error)) return error.issues;
52
- if (error === false) return [issue(code, path, 'validation error')];
53
- if (Array.isArray(error)) {
54
- const issues = [];
55
- for (const item of error) issues.push(...ValidationResult.issuesOf(item, path, code));
56
- return issues;
57
- }
58
- if (isIssue(error)) {
59
- const found = { code: error.code || code, path: error.path || path };
60
- return [{ ...found, message: prefixed(error.message, path) }];
61
- }
62
- return [{ code, path, message: prefixed(String(error), path) }];
63
- }
64
-
65
- static format(error, path = '') {
66
- const issues = ValidationResult.issuesOf(error, path);
67
- if (issues.length === 0) return null;
68
- return issues.map((entry) => entry.message);
69
- }
70
-
71
- static isInstance(error) {
72
- return hasBrand(error, 'ValidationResult');
73
- }
74
- }
75
-
76
- ValidationResult.prototype[BRAND] = 'ValidationResult';
17
+ return unknown;
18
+ };
77
19
 
78
20
  class Options {
79
21
  constructor() {
@@ -111,6 +53,7 @@ class SchemaMetadata {
111
53
  this.store = 'memory';
112
54
  this.allow = 'write';
113
55
  this.parent = '';
56
+ this.unknown = 'reject';
114
57
  this.indexes = new Indexes();
115
58
  this.options = new Options();
116
59
  this.custom = {};
@@ -119,12 +62,13 @@ class SchemaMetadata {
119
62
  }
120
63
 
121
64
  #setMany(values) {
122
- const { kind, scope, store, allow, parent, ...custom } = values;
65
+ const { kind, scope, store, allow, parent, unknown, ...custom } = values;
123
66
  this.kind = kind || this.kind;
124
67
  this.scope = scope || this.scope;
125
68
  this.store = store || this.store;
126
69
  this.allow = allow || this.allow;
127
70
  this.parent = parent || this.parent;
71
+ this.unknown = unknownOf(unknown);
128
72
  this.custom = custom;
129
73
  }
130
74
 
@@ -154,13 +98,18 @@ class SchemaMetadata {
154
98
  return fields;
155
99
  }
156
100
 
157
- validate(value, path) {
101
+ // Runs only the schema-level validate function, as a result of its own.
102
+ validate(value, path = '') {
158
103
  if (!this.options.validate) return null;
159
- const result = new ValidationResult(path);
104
+ const result = new ValidationResult();
160
105
  try {
161
106
  return result.add(this.options.validate(value, path));
162
107
  } catch (error) {
163
- return result.add(issue('exception', path, `validation failed ${error}`));
108
+ return result.add({
109
+ code: 'exception',
110
+ message: `validation failed ${error}`,
111
+ params: { error },
112
+ });
164
113
  }
165
114
  }
166
115
  }
package/src/model.js CHANGED
@@ -3,6 +3,7 @@ const { firstKey } = require('./metautil.js');
3
3
  const { Schema } = require('./schema.js');
4
4
  const { TYPES, createRegistry, typeFactory } = require('./types.js');
5
5
  const { SchemaDefinitionError } = require('./errors.js');
6
+ const { warning } = require('./lint.js');
6
7
 
7
8
  const REGISTRIES = ['shared', 'isolated'];
8
9
 
@@ -16,12 +17,16 @@ const registryFor = (options) => {
16
17
  };
17
18
 
18
19
  class Model {
20
+ // The model's own warnings (the cycles met while ordering), found while
21
+ // building; the rest comes from the entities on first use.
22
+ #cycles = [];
23
+ #warnings = null;
24
+
19
25
  constructor(types, entities, database = null, options = {}) {
20
26
  this.types = typeFactory(types, registryFor(options));
21
27
  this.entities = new Map();
22
28
  this.database = database;
23
29
  this.order = new Set();
24
- this.warnings = [];
25
30
  const projections = [];
26
31
  for (const pair of entities) {
27
32
  const name = pair[0];
@@ -43,15 +48,24 @@ class Model {
43
48
  this.#preprocess();
44
49
  }
45
50
 
46
- #preprocess() {
47
- const { entities, order } = this;
48
- for (const pair of entities) {
51
+ // The lint warnings of every entity, the references and types they cannot
52
+ // resolve, and the recursive dependencies, as `Warning [code]: text`.
53
+ get warnings() {
54
+ if (this.#warnings !== null) return this.#warnings;
55
+ const warnings = [];
56
+ for (const pair of this.entities) {
49
57
  const name = pair[0];
50
58
  const entity = pair[1];
51
59
  if (name.startsWith('.')) continue;
52
- const warn = entity.checkConsistency();
53
- this.warnings.push(...warn);
60
+ warnings.push(...entity.warnings, ...entity.checkConsistency());
54
61
  }
62
+ warnings.push(...this.#cycles);
63
+ this.#warnings = warnings;
64
+ return warnings;
65
+ }
66
+
67
+ #preprocess() {
68
+ const { entities, order } = this;
55
69
  if (entities.has('Identifier')) order.add('Identifier');
56
70
  for (const name of entities.keys()) {
57
71
  const isMeta = name.startsWith('.');
@@ -69,7 +83,9 @@ class Model {
69
83
  for (const ref of entity.references) {
70
84
  if (ref === name) continue;
71
85
  if (visiting.has(ref)) {
72
- this.warnings.push(`Warning: "${name}" depends on "${ref}" recursively`);
86
+ this.#cycles.push(
87
+ warning('recursive-reference', `"${name}" depends on "${ref}" recursively`),
88
+ );
73
89
  continue;
74
90
  }
75
91
  this.#reorderEntity(ref, visiting);
@@ -1,11 +1,21 @@
1
1
  const { isFirstUpper, toLowerCamel, firstKey } = require('./metautil.js');
2
2
 
3
- const { formatters } = require('./util.js');
3
+ const { hasBrand, formatters } = require('./util.js');
4
4
  const { SchemaDefinitionError } = require('./errors.js');
5
5
 
6
+ // The first key of an object decides what it is: a Schema or a built field is
7
+ // used as it is, a capitalized key is a kind, `type` is the long form, a type
8
+ // name is that type's shorthand, and anything else is a nested struct.
6
9
  const PARSERS = {
7
10
  string: ['stringShorthand'],
8
- object: ['schemaInstance', 'schemaWithKind', 'typeLongForm', 'typeShorthand', 'kindlessSchema'],
11
+ object: [
12
+ 'schemaInstance',
13
+ 'typeInstance',
14
+ 'schemaWithKind',
15
+ 'typeLongForm',
16
+ 'typeShorthand',
17
+ 'kindlessSchema',
18
+ ],
9
19
  function: ['functionField'],
10
20
  array: ['tupleShorthand'],
11
21
  };
@@ -16,6 +26,12 @@ const sourceType = (src) => {
16
26
  return typeof src;
17
27
  };
18
28
 
29
+ const invalid = (source, srcType = sourceType(source)) =>
30
+ new SchemaDefinitionError(
31
+ 'ERR_INVALID_DEFINITION',
32
+ `Invalid definition: "${source}" of type ${srcType}`,
33
+ );
34
+
19
35
  class Preprocessor {
20
36
  constructor(root) {
21
37
  this.Schema = root.constructor;
@@ -23,35 +39,44 @@ class Preprocessor {
23
39
  this.types = root.types;
24
40
  }
25
41
 
42
+ // The first key of an object is read once here and handed to the parsers
43
+ // that look at it.
26
44
  parse(source) {
27
45
  const srcType = sourceType(source);
28
46
  const parsers = PARSERS[srcType];
29
47
  if (parsers) {
48
+ const first = srcType === 'object' ? firstKey(source) : undefined;
30
49
  for (const name of parsers) {
31
- const result = this[name](source);
50
+ const result = this[name](source, first);
32
51
  if (result) return result;
33
52
  }
34
53
  }
35
- const msg = `Invalid definition: "${source}" of type ${srcType}`;
36
- throw new SchemaDefinitionError('ERR_INVALID_DEFINITION', msg);
54
+ throw invalid(source, srcType);
37
55
  }
38
56
 
57
+ // A Schema instance as a field: `{ schema: instance }` and the long form go
58
+ // through the type parsers, and the schema type accepts the instance there.
39
59
  schemaInstance(source) {
40
- const { types } = this;
41
- const schema = this.Schema.extractSchema(source);
42
- if (!schema) return null;
43
- this.root.updateFromSchema(schema);
44
- const { fields } = schema;
45
- const defs = { schema: fields };
46
- return { Type: types.schema, defs };
60
+ if (!hasBrand(source, 'Schema')) return null;
61
+ const defs = { schema: source };
62
+ return { Type: this.types.schema, defs };
63
+ }
64
+
65
+ // A field already built (a projection copies the fields of its parent) is
66
+ // parsed again from its own definition, so the copy belongs to the schema
67
+ // that holds it.
68
+ typeInstance(source) {
69
+ if (!hasBrand(source, 'Type')) return null;
70
+ return this.typeLongForm({ type: source.type, ...source.toJSON() }, 'type');
47
71
  }
48
72
 
49
73
  stringShorthand(source) {
50
- return this.typeLongForm({ type: source });
74
+ return this.typeLongForm({ type: source }, 'type');
51
75
  }
52
76
 
53
- typeLongForm(source) {
54
- if (!source.type) return null;
77
+ typeLongForm(source, first) {
78
+ if (first !== 'type') return null;
79
+ if (typeof source.type !== 'string') throw invalid(source.type);
55
80
  const { types } = this;
56
81
  const parsed = formatters.type(source.type, source.required);
57
82
  const { type, required } = parsed;
@@ -66,9 +91,8 @@ class Preprocessor {
66
91
  return { Type: types[type], defs };
67
92
  }
68
93
 
69
- typeShorthand(source) {
94
+ typeShorthand(source, first) {
70
95
  const { types } = this;
71
- const first = firstKey(source);
72
96
  const parsed = formatters.key(first, source.required);
73
97
  const type = parsed.field;
74
98
  const required = parsed.required;
@@ -78,9 +102,8 @@ class Preprocessor {
78
102
  return { Type: types[type], defs };
79
103
  }
80
104
 
81
- schemaWithKind(source) {
105
+ schemaWithKind(source, first) {
82
106
  const { types, root } = this;
83
- const first = firstKey(source);
84
107
  if (!isFirstUpper(first)) return null;
85
108
  const { [first]: meta, ...fields } = source;
86
109
  const kind = toLowerCamel(first);
@@ -1,72 +1,109 @@
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);
14
+ const invalidNullable = () =>
15
+ new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "nullable" needs a boolean');
15
16
 
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;
17
+ // A nullable field accepts null in place of a value of its type, whatever
18
+ // its rules; `required` still says whether the key must be there.
19
+ const nullable = (inner) => (value, context, key) => {
20
+ if (value === null) return;
21
+ inner(value, context, key);
22
+ };
20
23
 
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];
24
+ // The check of a field with rules or a validate function: the type check,
25
+ // then the rules, then the validate function. A type failure cancels the
26
+ // rest (a length or a validator makes no sense for a value of another type),
27
+ // and validate runs only on a value that passed everything before it, so it
28
+ // can rely on the type and the rules. A field with neither is its type check
29
+ // alone.
30
+ const withRules = (type, inner, rules) => {
31
+ const { required, validate } = type;
32
+ return (value, context, key) => {
33
+ if (value == null && !required) return;
34
+ const before = context.count;
35
+ inner(value, context, key);
36
+ if (context.count !== before) return;
37
+ for (let index = 0; index < rules.length; index += 1) {
38
+ if (context.count >= context.limit) break;
39
+ rules[index](value, context, key);
25
40
  }
26
- }
41
+ if (validate && context.count === before) {
42
+ const nested = key !== undefined;
43
+ if (nested) context.path.push(key);
44
+ runValidate(type, validate, value, context);
45
+ if (nested) context.path.pop();
46
+ }
47
+ };
48
+ };
49
+
50
+ class AbstractType {
51
+ // The rules the type accepts and the definition keys it reads, by name; a
52
+ // type class sets its own.
53
+ static rules = new Set();
54
+ static options = new Set();
55
+
56
+ // The compiled check of the field: a closure built once from the field,
57
+ // kept out of its definition (toJSON, util.inspect) as a private field.
58
+ #check;
27
59
 
28
60
  constructor(def, preprocessor) {
29
61
  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];
62
+ const { rules } = this.constructor;
63
+ for (const key of Object.keys(def)) {
64
+ const value = def[key];
34
65
  if (key === 'type' || key === this.type) continue;
35
66
  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;
67
+ const format = FORMAT[key];
68
+ if (format === undefined) {
69
+ this[key] = value;
70
+ continue;
71
+ }
72
+ if (!rules.has(key)) throw notApplicable(key, this.type, rules);
73
+ this[key] = format(value);
38
74
  }
39
75
  this.construct(def, preprocessor);
40
76
  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;
77
+ if (this.nullable !== undefined && typeof this.nullable !== 'boolean') throw invalidNullable();
78
+ // The rule checks that apply to this field, compiled once: a field
79
+ // without rules is its type check alone, and check is the hot path.
80
+ const checks = compileRules(this, rules);
81
+ const inner = this.compile();
82
+ const plain = checks.length === 0 && !this.validate;
83
+ const check = plain ? inner : withRules(this, inner, checks);
84
+ this.#check = this.nullable === true ? nullable(check) : check;
46
85
  }
47
86
 
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
- }
87
+ // Records the problems of a value into the context of the current check,
88
+ // under `key` when the field is reached through one.
89
+ get check() {
90
+ return this.#check;
91
+ }
92
+
93
+ // The type check of a field, as a closure built once from the field. A
94
+ // built-in prototype compiles its own; a custom type has a
95
+ // `checkType(value, path)` that returns messages, run through the
96
+ // validator contract.
97
+ compile() {
98
+ const type = this;
99
+ const { required } = this;
100
+ return (value, context, key) => {
101
+ if (value == null && !required) return;
102
+ const nested = key !== undefined;
103
+ if (nested) context.path.push(key);
104
+ runCheckType(type, value, context);
105
+ if (nested) context.path.pop();
106
+ };
70
107
  }
71
108
 
72
109
  toJSON() {
@@ -1,8 +1,12 @@
1
- const { ValidationResult } = require('../metadata.js');
2
- const { issue, shorten } = require('../util.js');
1
+ const { issues } = require('../issues.js');
3
2
 
3
+ // Collections iterate their source directly: an object with for...in over
4
+ // its own keys, a Map and a Set through their iterators, an array by index.
5
+ // A collection pushes its own key on the path before its elements and pops
6
+ // it after them; an element is checked with its key or index.
4
7
  const object = {
5
8
  rules: ['length'],
9
+ options: ['key', 'value', 'length'],
6
10
  kind: 'struct',
7
11
 
8
12
  construct(def, prep) {
@@ -16,50 +20,104 @@ const object = {
16
20
  this.value = new Type(defs, prep);
17
21
  },
18
22
 
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}`));
23
+ compile() {
24
+ const { required, type, key: keyType } = this;
25
+ const { check } = this.value;
26
+ return (value, context, key) => {
27
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
28
+ if (!required && value == null) return;
29
+ issues.type(context, type, value, key);
30
+ return;
33
31
  }
34
- result.add(this.value.check(fieldValue, `${path}.${shorten(field)}`));
35
- }
36
- return result;
32
+ const nested = key !== undefined;
33
+ if (nested) context.path.push(key);
34
+ let count = 0;
35
+ for (const name in value) {
36
+ if (!Object.hasOwn(value, name)) continue;
37
+ if (context.count >= context.limit) break;
38
+ count += 1;
39
+ // oxlint-disable-next-line valid-typeof
40
+ if (typeof name !== keyType) {
41
+ issues.key(context, keyType, name);
42
+ break;
43
+ }
44
+ check(value[name], context, name);
45
+ }
46
+ if (count === 0 && required) issues.required(context);
47
+ if (nested) context.path.pop();
48
+ };
37
49
  },
38
50
 
39
51
  isInstance(value) {
40
52
  return value !== null && typeof value === 'object' && !Array.isArray(value);
41
53
  },
42
-
43
- entries(value) {
44
- return Object.entries(value);
45
- },
46
54
  };
47
55
 
48
56
  const map = {
49
57
  ...object,
50
58
 
59
+ compile() {
60
+ const { required, type, key: keyType } = this;
61
+ const { check } = this.value;
62
+ return (value, context, key) => {
63
+ if (value?.constructor?.name !== 'Map') {
64
+ if (!required && value == null) return;
65
+ issues.type(context, type, value, key);
66
+ return;
67
+ }
68
+ if (value.size === 0) {
69
+ if (required) issues.required(context, key);
70
+ return;
71
+ }
72
+ const nested = key !== undefined;
73
+ if (nested) context.path.push(key);
74
+ for (const pair of value) {
75
+ if (context.count >= context.limit) break;
76
+ const name = pair[0];
77
+ // oxlint-disable-next-line valid-typeof
78
+ if (typeof name !== keyType) {
79
+ issues.key(context, keyType, name);
80
+ break;
81
+ }
82
+ check(pair[1], context, name);
83
+ }
84
+ if (nested) context.path.pop();
85
+ };
86
+ },
87
+
51
88
  isInstance(value) {
52
89
  return value?.constructor?.name === 'Map';
53
90
  },
91
+ };
54
92
 
55
- entries(value) {
56
- return [...value.entries()];
57
- },
93
+ // An array and a Set are walked the same way, by position; only the type
94
+ // test differs.
95
+ const compileList = (type, isList) => {
96
+ const { required } = type;
97
+ const { check } = type.value;
98
+ const name = type.type;
99
+ return (value, context, key) => {
100
+ if (!isList(value)) {
101
+ if (!required && value == null) return;
102
+ issues.type(context, name, value, key);
103
+ return;
104
+ }
105
+ const nested = key !== undefined;
106
+ if (nested) context.path.push(key);
107
+ let index = 0;
108
+ for (const item of value) {
109
+ if (context.count >= context.limit) break;
110
+ check(item, context, index);
111
+ index += 1;
112
+ }
113
+ if (nested) context.path.pop();
114
+ };
58
115
  };
59
116
 
60
117
  const array = {
61
118
  kind: 'struct',
62
119
  rules: ['length'],
120
+ options: ['value', 'length'],
63
121
 
64
122
  construct(def, prep) {
65
123
  const { type } = this;
@@ -68,18 +126,8 @@ const array = {
68
126
  this.value = new Type(defs, prep);
69
127
  },
70
128
 
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;
129
+ compile() {
130
+ return compileList(this, this.isInstance);
83
131
  },
84
132
 
85
133
  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