@alexify/metaschema 3.0.0 → 3.2.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 (47) hide show
  1. package/CHANGELOG.md +312 -1
  2. package/README.md +463 -17
  3. package/SECURITY.md +26 -7
  4. package/index.d.ts +338 -3
  5. package/package.json +42 -5
  6. package/src/codec.js +161 -73
  7. package/src/compile/code.js +1 -1
  8. package/src/compile/emit.js +60 -7
  9. package/src/compile/index.d.ts +6 -0
  10. package/src/compile/index.js +14 -3
  11. package/src/context.js +8 -9
  12. package/src/errors.js +18 -1
  13. package/src/formats/index.d.ts +19 -0
  14. package/src/formats/index.js +146 -0
  15. package/src/generators/fromjsonschema.js +517 -0
  16. package/src/generators/index.d.ts +19 -2
  17. package/src/generators/index.js +16 -10
  18. package/src/generators/jsonschema.js +2 -0
  19. package/src/issues.js +37 -20
  20. package/src/lint.js +12 -3
  21. package/src/locales/en.js +11 -2
  22. package/src/locales/uk.js +10 -2
  23. package/src/metadata.js +3 -2
  24. package/src/model/data.js +122 -0
  25. package/src/model/diff.js +439 -0
  26. package/src/model/index.d.ts +68 -0
  27. package/src/model/index.js +45 -0
  28. package/src/model/infer.js +483 -0
  29. package/src/model/merge.js +255 -0
  30. package/src/model/pattern.js +322 -0
  31. package/src/model/restore.js +226 -0
  32. package/src/model/sample.js +398 -0
  33. package/src/model.js +13 -1
  34. package/src/preprocessor.js +5 -1
  35. package/src/prototypes/collections.js +4 -3
  36. package/src/prototypes/scalars.js +4 -4
  37. package/src/prototypes/schema.js +6 -5
  38. package/src/prototypes/union.js +2 -2
  39. package/src/result.js +6 -0
  40. package/src/rules.js +53 -4
  41. package/src/schema.js +28 -7
  42. package/src/snapshot.js +111 -0
  43. package/src/stream/index.d.ts +68 -0
  44. package/src/stream/index.js +247 -0
  45. package/src/struct.js +64 -18
  46. package/src/types.js +14 -1
  47. package/src/util.js +18 -0
@@ -1,5 +1,6 @@
1
1
  const { issues } = require('../issues.js');
2
2
  const { SchemaDefinitionError } = require('../errors.js');
3
+ const { isMap, isSet } = require('../util.js');
3
4
 
4
5
  // The keys of a keyed collection are strings or numbers; anything else can
5
6
  // never match a key, and the JIT quotes the key type into its source.
@@ -77,7 +78,7 @@ const map = {
77
78
  const { required, type, key: keyType } = this;
78
79
  const { check } = this.value;
79
80
  return (value, context, key) => {
80
- if (value?.constructor?.name !== 'Map') {
81
+ if (!isMap(value)) {
81
82
  if (!required && value == null) return;
82
83
  issues.type(context, type, value, key);
83
84
  return;
@@ -103,7 +104,7 @@ const map = {
103
104
  },
104
105
 
105
106
  isInstance(value) {
106
- return value?.constructor?.name === 'Map';
107
+ return isMap(value);
107
108
  },
108
109
  };
109
110
 
@@ -156,7 +157,7 @@ const set = {
156
157
  ...array,
157
158
 
158
159
  isInstance(value) {
159
- return value?.constructor?.name === 'Set';
160
+ return isSet(value);
160
161
  },
161
162
  };
162
163
 
@@ -1,6 +1,6 @@
1
1
  const { SchemaDefinitionError } = require('../errors.js');
2
2
  const { issues } = require('../issues.js');
3
- const { ENUM_SET_SIZE } = require('../util.js');
3
+ const { ENUM_SET_SIZE, isDate } = require('../util.js');
4
4
 
5
5
  const missingEnum = (type) => {
6
6
  const hint = `Type "${type}" needs a list of values: { type: '${type}', enum: [...] }`;
@@ -86,7 +86,7 @@ const date = {
86
86
  compile() {
87
87
  const { required } = this;
88
88
  return (value, context, key) => {
89
- if (value?.constructor?.name === 'Date' && !Number.isNaN(value.getTime())) return;
89
+ if (isDate(value) && !Number.isNaN(value.getTime())) return;
90
90
  if (!required && value == null) return;
91
91
  issues.type(context, 'date', value, key);
92
92
  };
@@ -131,8 +131,8 @@ const unknown = { ...any, scalar: 'unknown' };
131
131
  const string = {
132
132
  ...scalar,
133
133
  scalar: 'string',
134
- rules: ['length', 'pattern'],
135
- options: ['length', 'unicode', 'pattern'],
134
+ rules: ['length', 'pattern', 'format'],
135
+ options: ['length', 'unicode', 'pattern', 'format'],
136
136
  };
137
137
  const number = { ...scalar, scalar: 'number', rules: ['min', 'max'], options: ['min', 'max'] };
138
138
  const bigint = { ...scalar, scalar: 'bigint', rules: ['min', 'max'], options: ['min', 'max'] };
@@ -10,10 +10,13 @@ const missingSchema = (type) => {
10
10
  const isDefinition = (value) =>
11
11
  value !== null && typeof value === 'object' && !Array.isArray(value);
12
12
 
13
- // The decoder and the serializer of a nested struct: the functions of its
14
- // definition (the options of a Schema it reuses), as its validate is, unless
15
- // the field's own definition gave them.
13
+ // The validate, the decoder and the serializer of a nested struct: the
14
+ // functions of its definition (the options of a Schema it reuses), unless the
15
+ // field's own definition gave them (`{ type: 'schema', schema, validate }`).
16
16
  const adopt = (type, source) => {
17
+ if (type.validate === undefined && typeof source.validate === 'function') {
18
+ type.validate = source.validate;
19
+ }
17
20
  if (type.parse === undefined && typeof source.parse === 'function') type.parse = source.parse;
18
21
  if (type.serialize === undefined && typeof source.serialize === 'function') {
19
22
  type.serialize = source.serialize;
@@ -33,13 +36,11 @@ const schema = {
33
36
  if (hasBrand(definition, 'Schema')) {
34
37
  prep.root.updateFromSchema(definition);
35
38
  this.schema = definition.fields;
36
- this.validate = definition.options.validate || undefined;
37
39
  adopt(this, definition.options);
38
40
  return;
39
41
  }
40
42
  if (isStruct(definition)) this.schema = definition;
41
43
  else this.schema = createStruct(definition, prep);
42
- this.validate = definition.validate || undefined;
43
44
  adopt(this, definition);
44
45
  },
45
46
 
@@ -1,5 +1,5 @@
1
1
  const { SchemaDefinitionError } = require('../errors.js');
2
- const { issues } = require('../issues.js');
2
+ const { issues, release } = require('../issues.js');
3
3
 
4
4
  const invalidUnion = (reason) => new SchemaDefinitionError('ERR_INVALID_UNION', `Union ${reason}`);
5
5
 
@@ -129,7 +129,7 @@ const union = {
129
129
  if (context.count === count) return;
130
130
  context.issues.length = count;
131
131
  context.count = count;
132
- if (context.async !== null) context.async.length = pending;
132
+ if (context.async !== null) release(context.async, pending);
133
133
  }
134
134
  issues.union(context, expected, undefined, key);
135
135
  };
package/src/result.js CHANGED
@@ -104,6 +104,12 @@ class ValidationResult {
104
104
  return hasBrand(error, 'ValidationResult');
105
105
  }
106
106
 
107
+ // The result as data, for a log or a response: JSON.stringify(result) has
108
+ // the verdict beside the issues (`errors` is derived from them).
109
+ toJSON() {
110
+ return { valid: this.valid, issues: this.issues };
111
+ }
112
+
107
113
  [INSPECT](depth, options, inspect) {
108
114
  const { valid, errors, issues } = this;
109
115
  return `ValidationResult ${inspect({ valid, errors, issues }, options)}`;
package/src/rules.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // the type check.
7
7
  const { issues } = require('./issues.js');
8
8
  const { SchemaDefinitionError } = require('./errors.js');
9
+ const { isMap, isSet } = require('./util.js');
9
10
 
10
11
  const invalidRule = (reason) => new SchemaDefinitionError('ERR_INVALID_RULE', reason);
11
12
 
@@ -52,11 +53,28 @@ const formatPattern = (value) => {
52
53
 
53
54
  // The formatter of each rule, by name; the names are the rules that exist. A
54
55
  // null-prototype dictionary: a definition key may be called `constructor`.
56
+ // The formats a string may name (`format: 'email'`): a null-prototype table
57
+ // of `{ test, examples }` entries, empty until `register()` of the formats
58
+ // subpath fills it (the core knows the rule, the subpath the formats), read
59
+ // when the field is built. A name the table lacks is a definition error with
60
+ // the hint, never a check that passes everything.
61
+ const FORMATS = Object.create(null);
62
+
63
+ const formatName = (value) => {
64
+ if (typeof value !== 'string') throw invalidRule('Rule "format" needs the name of a format');
65
+ if (FORMATS[value] === undefined) {
66
+ const hint = 'register() of @alexify/metaschema/formats';
67
+ throw invalidRule(`Rule "format" names a format that is not registered: "${value}" (${hint})`);
68
+ }
69
+ return value;
70
+ };
71
+
55
72
  const FORMAT = Object.assign(Object.create(null), {
56
73
  length: formatLength,
57
74
  min: formatLimit('min'),
58
75
  max: formatLimit('max'),
59
76
  pattern: formatPattern,
77
+ format: formatName,
60
78
  });
61
79
 
62
80
  const notApplicable = (rule, type, rules) => {
@@ -92,8 +110,7 @@ const keyCount = (value) => {
92
110
  // length of an array, the size of a Set or a Map, the own keys of an object.
93
111
  const lengthOf = (value) => {
94
112
  if (typeof value === 'string' || Array.isArray(value)) return value.length;
95
- const name = value.constructor?.name;
96
- return name === 'Set' || name === 'Map' ? value.size : keyCount(value);
113
+ return isMap(value) || isSet(value) ? value.size : keyCount(value);
97
114
  };
98
115
 
99
116
  // A string field measures its units, or its code points when it asks for
@@ -145,11 +162,33 @@ const compileRange = (type) => {
145
162
  };
146
163
  };
147
164
 
165
+ // The units a pattern may be run over: `length.max` (twice it when the
166
+ // length counts code points, each at most two units), so that a string past
167
+ // the bound, reported for its length already, never reaches a pattern that
168
+ // backtracks over it; no limit without the bound.
169
+ const patternLimit = (type) => {
170
+ const max = type.length?.max;
171
+ if (max === undefined) return Infinity;
172
+ return type.unicode === true ? 2 * max : max;
173
+ };
174
+
148
175
  const compilePattern = (type) => {
149
176
  const { pattern } = type;
150
177
  const { source } = pattern;
178
+ const limit = patternLimit(type);
151
179
  return (value, context, key) => {
152
- if (!pattern.test(value)) issues.pattern(context, source, key);
180
+ if (value.length <= limit && !pattern.test(value)) issues.pattern(context, source, key);
181
+ };
182
+ };
183
+
184
+ // A format is the test the subpath registered under its name, run after the
185
+ // pattern and under the same bound.
186
+ const compileFormat = (type) => {
187
+ const { format } = type;
188
+ const { test } = FORMATS[format];
189
+ const limit = patternLimit(type);
190
+ return (value, context, key) => {
191
+ if (value.length <= limit && !test(value)) issues.format(context, format, key);
153
192
  };
154
193
  };
155
194
 
@@ -171,6 +210,7 @@ const ruleNames = (type) => {
171
210
  const COMPILERS = Object.assign(Object.create(null), {
172
211
  length: compileLength,
173
212
  pattern: compilePattern,
213
+ format: compileFormat,
174
214
  range: compileRange,
175
215
  });
176
216
 
@@ -182,4 +222,13 @@ const compileRules = (type) => {
182
222
  return checks;
183
223
  };
184
224
 
185
- module.exports = { FORMAT, notApplicable, ruleNames, compileRules, codePoints, lengthOf };
225
+ module.exports = {
226
+ FORMAT,
227
+ FORMATS,
228
+ notApplicable,
229
+ ruleNames,
230
+ compileRules,
231
+ patternLimit,
232
+ codePoints,
233
+ lengthOf,
234
+ };
package/src/schema.js CHANGED
@@ -6,11 +6,20 @@ 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, settle } = require('./issues.js');
9
+ const { finalize, runValidate, settle, release } = 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
@@ -50,6 +59,18 @@ const parsed = (context, output) => {
50
59
  const standardize = (result) =>
51
60
  result.valid ? { value: result.value } : { issues: result.issues };
52
61
 
62
+ // The walk of an async check: a throw out of it (a getter of the value that
63
+ // throws, the engine's limit on a pattern) leaves the promises the walk
64
+ // queued observed, so that none of them rejects unhandled.
65
+ const walkAsync = (schema, value, context) => {
66
+ try {
67
+ schema[RUN](value, context);
68
+ } catch (error) {
69
+ release(context.async, 0);
70
+ throw error;
71
+ }
72
+ };
73
+
53
74
  class Schema extends SchemaMetadata {
54
75
  // The merged type table of the attached namespaces, rebuilt only when they
55
76
  // change.
@@ -195,20 +216,20 @@ class Schema extends SchemaMetadata {
195
216
  return resultOf(context);
196
217
  }
197
218
 
198
- // The same check, with the validators that return a promise settled after
199
- // the walk, in field order.
219
+ // The same check, with the validators that return a promise in flight
220
+ // together and settled after the walk, in field order.
200
221
  async checkAsync(source, options) {
201
222
  const context = createContext(options, this.name, this.unknown);
202
223
  context.async = [];
203
224
  if (this.#tracked) context.source = source;
204
- this[RUN](source, context);
225
+ walkAsync(this, source, context);
205
226
  if (context.async.length > 0) await settle(context);
206
227
  return resultOf(context);
207
228
  }
208
229
 
209
230
  #pass(phase, source, context) {
210
231
  if (this.#codec === null) this.#codec = infoOf(this);
211
- return apply(this.#codec, this, source, context, undefined, phase);
232
+ return apply(this.#codec, this, source, context, undefined, phase, wantOf(phase, context));
212
233
  }
213
234
 
214
235
  // The defaults of the schema over a value, before its check; the objects
@@ -240,7 +261,7 @@ class Schema extends SchemaMetadata {
240
261
  const context = createContext(options, this.name, this.unknown, true);
241
262
  context.async = [];
242
263
  const value = this.#prepare(source, context);
243
- this[RUN](value, context);
264
+ walkAsync(this, value, context);
244
265
  if (context.async.length > 0) await settle(context);
245
266
  let output;
246
267
  if (context.count === 0) {
@@ -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) define(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 };
@@ -0,0 +1,68 @@
1
+ import type {
2
+ EachAsyncOptions,
3
+ EachOptions,
4
+ Infer,
5
+ InferOutput,
6
+ ParseEachOptions,
7
+ ParseResult,
8
+ RecordEntry,
9
+ Schema,
10
+ TransformOptions,
11
+ ValidationResult,
12
+ } from '../../index.js';
13
+
14
+ // `check` on every record of an iterable, as a generator of
15
+ // `{ index, record, result }` in the order of the records; the options are
16
+ // those of `check`, plus `maxInvalid`, the number of invalid records after
17
+ // which the iteration ends. A target that is not a Schema, or a source that
18
+ // is not iterable, is a `TypeError` with the code `ERR_INVALID_TARGET`.
19
+ export function checkEach<T>(
20
+ schema: Schema,
21
+ records: Iterable<T>,
22
+ options?: EachOptions,
23
+ ): Generator<RecordEntry<T, ValidationResult>, void, undefined>;
24
+
25
+ // `parse` on every record of an iterable: the same, with the result of
26
+ // `parse` in each entry.
27
+ export function parseEach<T, D extends string | object>(
28
+ schema: Schema<D>,
29
+ records: Iterable<T>,
30
+ options?: ParseEachOptions,
31
+ ): Generator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
32
+
33
+ // `checkAsync` on every record of a sync or async iterable, as an async
34
+ // generator in the order of the records, with up to `concurrency` records
35
+ // in flight (one by default).
36
+ export function checkEachAsync<T>(
37
+ schema: Schema,
38
+ records: Iterable<T> | AsyncIterable<T>,
39
+ options?: EachOptions & EachAsyncOptions,
40
+ ): AsyncGenerator<RecordEntry<T, ValidationResult>, void, undefined>;
41
+
42
+ // `parseAsync` on every record of a sync or async iterable: the same, with
43
+ // the result of `parseAsync` in each entry.
44
+ export function parseEachAsync<T, D extends string | object>(
45
+ schema: Schema<D>,
46
+ records: Iterable<T> | AsyncIterable<T>,
47
+ options?: ParseEachOptions & EachAsyncOptions,
48
+ ): AsyncGenerator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
49
+
50
+ // A TransformStream over the records of a stream: a valid record goes on as
51
+ // its parsed value (`mode: 'parse'`, the default) or as it is
52
+ // (`mode: 'check'`); an invalid one is handed to `onInvalid` and dropped, or
53
+ // ends the stream with a `TypeError` of the code `ERR_INVALID_RECORD` (with
54
+ // `index`, `record` and `result` on it) when there is no `onInvalid` or
55
+ // `maxInvalid` is reached. `async: true` runs the async methods.
56
+ export function transform<D extends string | object>(
57
+ schema: Schema<D>,
58
+ options: TransformOptions & { mode: 'check' },
59
+ ): TransformStream<unknown, Infer<D>>;
60
+ export function transform<D extends string | object>(
61
+ schema: Schema<D>,
62
+ options?: TransformOptions,
63
+ ): TransformStream<unknown, InferOutput<D>>;
64
+
65
+ // Installs `schema.checkEach`, `schema.parseEach`, `schema.checkEachAsync`,
66
+ // `schema.parseEachAsync` and `schema.transform`. Once per process; later
67
+ // calls do nothing.
68
+ export function register(): void;