@alexify/metaschema 3.3.0 → 3.4.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 (53) hide show
  1. package/CHANGELOG.md +186 -1
  2. package/README.md +24 -16
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +224 -28
  5. package/package.json +13 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +37 -13
  8. package/src/coerce/index.js +34 -1
  9. package/src/compile/emit.js +87 -28
  10. package/src/compile/index.js +9 -4
  11. package/src/definition/index.d.ts +19 -0
  12. package/src/definition/index.js +27 -0
  13. package/src/derive/index.js +15 -8
  14. package/src/errors.js +23 -0
  15. package/src/generators/fromjsonschema.js +14 -0
  16. package/src/generators/index.js +1 -1
  17. package/src/generators/jsonschema.js +44 -7
  18. package/src/generators/typescript.js +11 -0
  19. package/src/index.js +3 -2
  20. package/src/issues.js +9 -7
  21. package/src/kinds.js +4 -1
  22. package/src/lint.js +15 -1
  23. package/src/locales/en.js +6 -0
  24. package/src/locales/uk.js +6 -0
  25. package/src/metadata.js +2 -24
  26. package/src/model/data.js +50 -10
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +10 -3
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +52 -7
  32. package/src/model/sample.js +26 -1
  33. package/src/model.js +25 -53
  34. package/src/mongodb/bson.js +15 -3
  35. package/src/mongodb/document.js +10 -2
  36. package/src/preprocessor.js +1 -2
  37. package/src/prototypes/abstract.js +32 -64
  38. package/src/prototypes/collections.js +3 -90
  39. package/src/prototypes/flags.js +34 -0
  40. package/src/prototypes/json.js +0 -11
  41. package/src/prototypes/reference.js +0 -76
  42. package/src/prototypes/scalars.js +17 -96
  43. package/src/prototypes/schema.js +1 -10
  44. package/src/prototypes/tuple.js +0 -26
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +105 -233
  48. package/src/snapshot.js +216 -41
  49. package/src/stream/index.js +1 -1
  50. package/src/struct.js +6 -91
  51. package/src/types.js +24 -6
  52. package/src/util.js +43 -0
  53. package/src/validation.js +313 -0
@@ -6,6 +6,7 @@ const { isFirstUpper } = require('../metautil.js');
6
6
  const { hasBrand, IDENTIFIER } = require('../util.js');
7
7
  const { SchemaDefinitionError } = require('../errors.js');
8
8
  const { embeds } = require('../prototypes/reference.js');
9
+ const { baseTypeOf } = require('../types.js');
9
10
 
10
11
  const TS_SCALARS = Object.assign(Object.create(null), {
11
12
  string: 'string',
@@ -13,6 +14,7 @@ const TS_SCALARS = Object.assign(Object.create(null), {
13
14
  boolean: 'boolean',
14
15
  bigint: 'bigint',
15
16
  date: 'Date',
17
+ bytes: 'Uint8Array',
16
18
  null: 'null',
17
19
  any: 'any',
18
20
  unknown: 'unknown',
@@ -118,6 +120,15 @@ const tsBase = (def, ts, name, target, top) => {
118
120
  ts.blocks.push(`type ${named} = ${text};`);
119
121
  return named;
120
122
  }
123
+ // By the type, as JSON Schema tells it: `flags` is an option name any type
124
+ // may carry (a pattern's, a custom type's).
125
+ if (baseTypeOf(def).type === 'flags') {
126
+ const names = [];
127
+ for (let index = 0; index < def.flags.length; index += 1) {
128
+ names.push(`${tsKey(def.flags[index])}?: boolean`);
129
+ }
130
+ return `{ ${names.join('; ')} }`;
131
+ }
121
132
  if (def.union) {
122
133
  const branches = [];
123
134
  for (let index = 0; index < def.union.length; index += 1) {
package/src/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  const { constants, getKindMetadata } = require('./kinds.js');
2
- const { Schema } = require('./schema.js');
2
+ // The core entry: the definition half (the classes) with the validation
3
+ // half installed into them (validation.js).
4
+ const { Schema, ValidationResult } = require('./validation.js');
3
5
  const { Model } = require('./model.js');
4
6
  const { SchemaDefinitionError } = require('./errors.js');
5
- const { ValidationResult } = require('./result.js');
6
7
 
7
8
  const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
8
9
 
package/src/issues.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // are rendered once, at the end of the check, through the locale of that check.
5
5
  // Every issue has the same keys in the same order, so loops over them see one
6
6
  // shape.
7
- const { hasBrand, shorten, safeString } = require('./util.js');
7
+ const { hasBrand, shorten, safeString, typeOf } = require('./util.js');
8
8
  const { asyncReturn } = require('./errors.js');
9
9
  const en = require('./locales/en.js');
10
10
 
@@ -37,12 +37,6 @@ const record = (context, code, params, key, message = '') => {
37
37
  push(context, { code, path: pathOf(context, key), message, params });
38
38
  };
39
39
 
40
- const typeOf = (value) => {
41
- if (value === null) return 'null';
42
- if (Array.isArray(value)) return 'array';
43
- return typeof value;
44
- };
45
-
46
40
  const issues = {
47
41
  required: (context, key) => record(context, 'required', EMPTY, key),
48
42
  type: (context, expected, value, key) =>
@@ -55,6 +49,14 @@ const issues = {
55
49
  range: (context, min, max, actual, key) => record(context, 'range', { min, max, actual }, key),
56
50
  pattern: (context, pattern, key) => record(context, 'pattern', { pattern }, key),
57
51
  format: (context, format, key) => record(context, 'format', { format }, key),
52
+ // NaN and the infinities have no decimals: the value is named then.
53
+ decimals: (context, decimals, value, key) =>
54
+ record(
55
+ context,
56
+ 'decimals',
57
+ Number.isFinite(value) ? { decimals } : { decimals, received: String(value) },
58
+ key,
59
+ ),
58
60
  union: (context, expected, discriminator, key) =>
59
61
  record(context, 'union', { expected, discriminator }, key),
60
62
  reference: (context, entity, key) => record(context, 'reference', { entity }, key),
package/src/kinds.js CHANGED
@@ -22,8 +22,11 @@ const projection = (kind, meta, root) => {
22
22
  }
23
23
  const parent = schema;
24
24
  const metadata = { ...meta, kind, scope, store, allow, parent };
25
+ // The projection itself is not built yet, so its own name is no parent.
25
26
  const entity = root.findReference(schema);
26
- if (!entity) throw projectionError(root.name, `parent "${schema}" is not found`);
27
+ if (!entity || entity === root) {
28
+ throw projectionError(root.name, `parent "${schema}" is not found`);
29
+ }
27
30
  const defs = Object.create(null);
28
31
  for (const key of fields) {
29
32
  const field = entity.fields[key];
package/src/lint.js CHANGED
@@ -9,7 +9,7 @@ const warning = (code, text) => `Warning [${code}]: ${text}`;
9
9
 
10
10
  // The types no converter of coercion exists for: a value of them is taken
11
11
  // as it is.
12
- const NEVER_CONVERTED = new Set(['any', 'unknown', 'json', 'null']);
12
+ const NEVER_CONVERTED = new Set(['any', 'unknown', 'json', 'null', 'flags']);
13
13
 
14
14
  // A `coerce` key where no conversion can happen: a reference checked as an
15
15
  // id (the record it names is never entered), a type that takes any value.
@@ -70,6 +70,20 @@ const lintField = (field, path, warnings, element = false, member = false) => {
70
70
  const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
71
71
  warnings.push(warning('unbounded-pattern', text));
72
72
  }
73
+ if (field.decimals !== undefined) {
74
+ // The check tells a decimal too many apart below 2⁴³ units of the last
75
+ // decimal (ULPS of checks.js); a bound past it lets any number through.
76
+ // A side without a bound counts as 1.
77
+ const bound = Math.max(Math.abs(field.min ?? 1), Math.abs(field.max ?? 1));
78
+ const limit = 2 ** 43 / 10 ** field.decimals;
79
+ if (bound >= limit) {
80
+ const below = Number(limit.toPrecision(2));
81
+ const text =
82
+ `"${path}" has ${field.decimals} decimals, ` +
83
+ `which the check tells apart only below ${below}`;
84
+ warnings.push(warning('unenforceable-decimals', text));
85
+ }
86
+ }
73
87
  if (field.coerce !== undefined) {
74
88
  const dead = deadCoerce(field);
75
89
  if (dead !== '') {
package/src/locales/en.js CHANGED
@@ -36,6 +36,11 @@ const pattern = ({ pattern: source }) => `does not match the pattern ${source}`;
36
36
 
37
37
  const format = ({ format: name }) => `is not a valid ${name}`;
38
38
 
39
+ const decimals = ({ decimals: count, received }) =>
40
+ received === undefined
41
+ ? `has more than ${count} decimals`
42
+ : `is ${received}, not a finite number`;
43
+
39
44
  const union = ({ expected, discriminator }) =>
40
45
  discriminator === undefined
41
46
  ? `does not match any of: ${expected.join(', ')}`
@@ -61,6 +66,7 @@ module.exports = {
61
66
  range,
62
67
  pattern,
63
68
  format,
69
+ decimals,
64
70
  union,
65
71
  reference,
66
72
  circular,
package/src/locales/uk.js CHANGED
@@ -34,6 +34,11 @@ const pattern = ({ pattern: source }) => `не відповідає шаблон
34
34
 
35
35
  const format = ({ format: name }) => `не є коректним ${name}`;
36
36
 
37
+ const decimals = ({ decimals: count, received }) =>
38
+ received === undefined
39
+ ? `має більше знаків після коми, ніж ${count}`
40
+ : `дорівнює ${received} і не є скінченним числом`;
41
+
37
42
  const union = ({ expected, discriminator }) =>
38
43
  discriminator === undefined
39
44
  ? `не відповідає жодному з: ${expected.join(', ')}`
@@ -59,6 +64,7 @@ module.exports = {
59
64
  range,
60
65
  pattern,
61
66
  format,
67
+ decimals,
62
68
  union,
63
69
  reference,
64
70
  circular,
package/src/metadata.js CHANGED
@@ -1,8 +1,5 @@
1
1
  const { getKindMetadata } = require('./kinds.js');
2
- const { ValidationResult } = require('./result.js');
3
- const { SchemaDefinitionError, asyncReturn } = require('./errors.js');
4
- const { isThenable } = require('./issues.js');
5
- const { safeString } = require('./util.js');
2
+ const { SchemaDefinitionError } = require('./errors.js');
6
3
 
7
4
  // The functions of a schema definition that are the schema's own: its
8
5
  // validate, its decoder, its serializer and `format`.
@@ -95,25 +92,6 @@ class SchemaMetadata {
95
92
  }
96
93
  return fields;
97
94
  }
98
-
99
- // Runs only the schema-level validate function, as a result of its own; a
100
- // function that returns a promise is an error here, as in check.
101
- validate(value, path = '') {
102
- if (!this.options.validate) return null;
103
- const result = new ValidationResult();
104
- try {
105
- const output = this.options.validate.call(this, value, path);
106
- if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
107
- return result.add(output);
108
- } catch (error) {
109
- if (error?.code === 'ERR_ASYNC_VALIDATOR') throw error;
110
- return result.add({
111
- code: 'exception',
112
- message: `validation failed ${safeString(error)}`,
113
- params: { error },
114
- });
115
- }
116
- }
117
95
  }
118
96
 
119
- module.exports = { ValidationResult, SchemaMetadata };
97
+ module.exports = { SchemaMetadata };
package/src/model/data.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // snapshot is input (a file, a registry, another program), so what it says
4
4
  // is checked before it is read, and every error is ERR_INVALID_SNAPSHOT
5
5
  // located in the entity, never a bare SyntaxError or TypeError.
6
- const { hasBrand, define } = require('../util.js');
6
+ const { hasBrand, define, isDate, isRegExp } = require('../util.js');
7
7
  const { FORMAT } = require('../snapshot.js');
8
8
  const { SchemaDefinitionError } = require('../errors.js');
9
9
  const { isStruct } = require('../struct.js');
@@ -32,12 +32,24 @@ const isSnapshot = (value) =>
32
32
  isObject(value.entities) &&
33
33
  (value.types === undefined || isObject(value.types));
34
34
 
35
- // The snapshot of a model, or the snapshot given.
36
- const snapshotOf = (target) => {
35
+ // The entity a snapshot of one schema is about, when it names one: a key
36
+ // format 1 gained in 3.4, read by nothing else.
37
+ const checkRoot = (snapshot) => {
38
+ const { root } = snapshot;
39
+ if (root === undefined) return;
40
+ if (typeof root !== 'string' || !Object.hasOwn(snapshot.entities, root)) {
41
+ throw invalidSnapshot('The root of a snapshot must name one of its entities');
42
+ }
43
+ };
44
+
45
+ // The snapshot of a model, or the snapshot given, read as one (the writer of
46
+ // the core is `snapshotOf` of snapshot.js).
47
+ const readSnapshot = (target) => {
37
48
  if (hasBrand(target, 'Model')) return target.toJSON();
38
49
  if (!isSnapshot(target)) {
39
50
  throw invalidSnapshot(`A Model or a snapshot of format ${FORMAT} with entities is expected`);
40
51
  }
52
+ checkRoot(target);
41
53
  return target;
42
54
  };
43
55
 
@@ -49,12 +61,12 @@ const same = (a, b, depth = 0) => {
49
61
  if (a === b) return true;
50
62
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
51
63
  if (depth > DEPTH) throw tooDeep();
52
- const name = a.constructor?.name;
53
- if (name === 'RegExp' || name === 'Date') {
54
- if (name !== b.constructor?.name) return false;
55
- return name === 'Date'
56
- ? a.getTime() === b.getTime()
57
- : a.source === b.source && a.flags === b.flags;
64
+ // By their shape, which a value of JSON cannot fake: `{ constructor: {
65
+ // name: 'Date' } }` of a snapshot is data.
66
+ const regExp = isRegExp(a);
67
+ if (regExp || isRegExp(b) || isDate(a) || isDate(b)) {
68
+ if (regExp) return isRegExp(b) && a.source === b.source && a.flags === b.flags;
69
+ return isDate(a) && isDate(b) && a.getTime() === b.getTime();
58
70
  }
59
71
  if (Array.isArray(a)) {
60
72
  if (!Array.isArray(b) || a.length !== b.length) return false;
@@ -121,6 +133,32 @@ const structDefinition = (base, metadata, fields) => {
121
133
  return definition;
122
134
  };
123
135
 
136
+ // The namespaces of a schema built from schemas: theirs, and for a schema
137
+ // that names itself without a model holding it (`parent: '?Category'`
138
+ // resolves to the schema itself), one that holds it, so that what is built
139
+ // from it, under its name or another, reaches the schema it was built from
140
+ // as it did.
141
+ const namespacesOf = (schemas) => {
142
+ const namespaces = new Set();
143
+ for (const schema of schemas) {
144
+ const { name } = schema;
145
+ let held = false;
146
+ for (const ns of schema.namespaces) {
147
+ namespaces.add(ns);
148
+ if (ns.entities.get(name) !== undefined) held = true;
149
+ }
150
+ if (name !== '' && !held && schema.references.has(name)) {
151
+ namespaces.add({
152
+ entities: new Map([[name, schema]]),
153
+ get types() {
154
+ return schema.types;
155
+ },
156
+ });
157
+ }
158
+ }
159
+ return Array.from(namespaces);
160
+ };
161
+
124
162
  module.exports = {
125
163
  DEPTH,
126
164
  invalidSnapshot,
@@ -128,7 +166,8 @@ module.exports = {
128
166
  atSchema,
129
167
  isObject,
130
168
  isSnapshot,
131
- snapshotOf,
169
+ checkRoot,
170
+ readSnapshot,
132
171
  same,
133
172
  isFunctionMarker,
134
173
  capitalize,
@@ -136,4 +175,5 @@ module.exports = {
136
175
  structDefinitionOf,
137
176
  metadataOf,
138
177
  structDefinition,
178
+ namespacesOf,
139
179
  };
package/src/model/diff.js CHANGED
@@ -15,7 +15,7 @@ const {
15
15
  invalidSnapshot,
16
16
  atSchema,
17
17
  isObject,
18
- snapshotOf,
18
+ readSnapshot,
19
19
  same,
20
20
  isFunctionMarker,
21
21
  } = require('./data.js');
@@ -188,8 +188,8 @@ const diffEntity = (name, old, current, changes) => {
188
188
  // entities of `next` in their order (added, or their changes), the entities
189
189
  // that are gone, then the types.
190
190
  const diff = (prev, next) => {
191
- const old = snapshotOf(prev);
192
- const current = snapshotOf(next);
191
+ const old = readSnapshot(prev);
192
+ const current = readSnapshot(next);
193
193
  const changes = [];
194
194
  for (const name of Object.keys(current.entities)) {
195
195
  const to = current.entities[name];
@@ -243,7 +243,8 @@ const includes = (list, value) => {
243
243
  return false;
244
244
  };
245
245
 
246
- // Values added accept more (backward), values removed accept less (forward).
246
+ // Values added accept more (backward), values removed accept less (forward);
247
+ // the names of flags the same way.
247
248
  const enumLevel = (from, to) => {
248
249
  let level = FULL;
249
250
  for (const value of to) if (!includes(from, value)) level &= BACKWARD;
@@ -325,11 +326,13 @@ const keyLevel = (key, from, to, field) => {
325
326
  case 'min':
326
327
  return boundLevel(from, to, true);
327
328
  case 'max':
329
+ case 'decimals':
328
330
  return boundLevel(from, to, false);
329
331
  case 'pattern':
330
332
  case 'format':
331
333
  return from === undefined ? FORWARD : to === undefined ? BACKWARD : NONE;
332
334
  case 'enum':
335
+ case 'flags':
333
336
  return Array.isArray(from) && Array.isArray(to) ? enumLevel(from, to) : NONE;
334
337
  case 'validate':
335
338
  case 'parse':
@@ -6,7 +6,7 @@
6
6
  // program that only validates does not carry them. The functions take
7
7
  // Models, Schemas, snapshots or samples; `register()` installs them as
8
8
  // members of the classes for the programs that want the methods.
9
- const { Schema } = require('../schema.js');
9
+ const { Schema } = require('../validation.js');
10
10
  const { Model } = require('../model.js');
11
11
  const { fromJSON } = require('./restore.js');
12
12
  const { diff, compatibility, compatibilityOf } = require('./diff.js');
@@ -8,8 +8,8 @@
8
8
  // against every sample, so that what comes back is a schema the samples
9
9
  // pass. The samples are input: the walk is bounded, no key is trusted, and
10
10
  // what no type describes is `any` rather than an error.
11
- const { define, IDENTIFIER, shorten } = require('../util.js');
12
- const { Schema } = require('../schema.js');
11
+ const { define, IDENTIFIER, shorten, isBytes } = require('../util.js');
12
+ const { Schema } = require('../validation.js');
13
13
  const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
14
14
  const { readsAsStruct } = require('../types.js');
15
15
  const { FORMATS } = require('../rules.js');
@@ -39,6 +39,7 @@ const RECORD = 2048;
39
39
  const BLANK = 4096;
40
40
  // A value no type describes but `any`: a function, a symbol, an invalid Date.
41
41
  const ANY = 8192;
42
+ const BYTES = 16384;
42
43
 
43
44
  const PRESENCE = NULL | UNDEF;
44
45
 
@@ -136,7 +137,8 @@ const addItems = (target, items, state, depth) => {
136
137
  // One value into the summary of its place. The tests are the ones the
137
138
  // check makes (a Date by its constructor name and a valid time, a Set and a
138
139
  // Map by name, an integer by Number.isInteger, the keys of a record by
139
- // Object.keys), so what infer calls a date the check accepts as one.
140
+ // Object.keys, bytes by the view's own name), so what infer calls a date
141
+ // the check accepts as one.
140
142
  const add = (target, value, state, depth) => {
141
143
  target.count += 1;
142
144
  if (value === null) {
@@ -180,6 +182,10 @@ const add = (target, value, state, depth) => {
180
182
  addItems(target, value, state, depth);
181
183
  return;
182
184
  }
185
+ if (isBytes(value)) {
186
+ target.bits |= BYTES;
187
+ return;
188
+ }
183
189
  const iterable = typeof value[Symbol.iterator] === 'function';
184
190
  if (name === 'Set' && iterable) {
185
191
  target.bits |= SET;
@@ -369,6 +375,7 @@ const formOf = (target, state) => {
369
375
  if (bits & BIGINT) forms.push({ def: 'bigint' });
370
376
  if (bits & STRING) forms.push(stringOf(target, state));
371
377
  if (bits & DATE) forms.push({ def: 'date' });
378
+ if (bits & BYTES) forms.push({ def: 'bytes' });
372
379
  if (bits & LIST) forms.push({ def: { array: itemOf(target.item, state) } });
373
380
  if (bits & SET) forms.push({ def: { set: itemOf(target.item, state) } });
374
381
  if (bits & MAP) forms.push(mapOf(target, state));
@@ -16,6 +16,7 @@ const {
16
16
  metadataOf,
17
17
  structDefinition,
18
18
  atSchema,
19
+ namespacesOf,
19
20
  } = require('./data.js');
20
21
 
21
22
  // The keys a field definition settles by a rule of its own; every other key
@@ -58,7 +59,7 @@ const mergeLength = (a, b, path) => {
58
59
  return length;
59
60
  };
60
61
 
61
- const mergeEnum = (a, b, path) => {
62
+ const mergeEnum = (a, b, path, what = 'enums') => {
62
63
  const values = [];
63
64
  for (const value of a) {
64
65
  for (const other of b) {
@@ -68,7 +69,7 @@ const mergeEnum = (a, b, path) => {
68
69
  }
69
70
  }
70
71
  }
71
- if (values.length === 0) throw conflict('The enums have no value in common', path);
72
+ if (values.length === 0) throw conflict(`The ${what} have no value in common`, path);
72
73
  return values;
73
74
  };
74
75
 
@@ -97,9 +98,12 @@ const mergeKey = (key, a, b, path) => {
97
98
  case 'min':
98
99
  return a > b ? a : b;
99
100
  case 'max':
101
+ case 'decimals':
100
102
  return a < b ? a : b;
101
103
  case 'enum':
102
104
  return mergeEnum(a, b, path);
105
+ case 'flags':
106
+ return mergeEnum(a, b, path, 'flags');
103
107
  case 'validate':
104
108
  return compose(a, b);
105
109
  case 'aliases':
@@ -211,7 +215,7 @@ const merge = (a, b, options = {}) => {
211
215
  throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Merge options must be an object');
212
216
  }
213
217
  const { name = a.name, metadata = {} } = options;
214
- const namespaces = Array.from(new Set([...a.namespaces, ...b.namespaces]));
218
+ const namespaces = namespacesOf([a, b]);
215
219
  const structA = isStruct(a.fields);
216
220
  const structB = isStruct(b.fields);
217
221
  try {
@@ -11,6 +11,7 @@
11
11
  // named like a field) is ERR_INVALID_SNAPSHOT located where the walk was,
12
12
  // and the kind metadata it declares is never loosened by its `custom` keys.
13
13
  const { define, shorten } = require('../util.js');
14
+ const { isFirstLower } = require('../metautil.js');
14
15
  const { Schema } = require('../schema.js');
15
16
  const { Model } = require('../model.js');
16
17
  const { SchemaDefinitionError } = require('../errors.js');
@@ -21,11 +22,23 @@ const {
21
22
  atSchema,
22
23
  isObject,
23
24
  isSnapshot,
25
+ checkRoot,
24
26
  isFunctionMarker,
25
27
  capitalize,
26
28
  } = require('./data.js');
27
29
 
28
30
  const nothing = () => undefined;
31
+
32
+ // The bytes of base64 text: any padded text of the alphabet, as written.
33
+ const bytesOf = (text) => {
34
+ if (text.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) {
35
+ throw invalidSnapshot(`${JSON.stringify(shorten(text))} is not base64`);
36
+ }
37
+ const binary = atob(text);
38
+ const bytes = new Uint8Array(binary.length);
39
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
40
+ return bytes;
41
+ };
29
42
  const identity = (value) => value;
30
43
 
31
44
  // What stands in for a function, by the key it is under; `at` is the path
@@ -57,6 +70,18 @@ const revive = (value, key, at, depth, context) => {
57
70
  if (Number.isNaN(+date)) throw invalidSnapshot(`${JSON.stringify(value.$date)} is not a date`);
58
71
  return date;
59
72
  }
73
+ if (typeof value.$bytes === 'string') return bytesOf(value.$bytes);
74
+ if (Array.isArray(value.$map)) {
75
+ const map = new Map();
76
+ for (const entry of revive(value.$map, key, at, depth, context)) {
77
+ if (!Array.isArray(entry) || entry.length !== 2) {
78
+ throw invalidSnapshot('An entry of a map needs a key and a value');
79
+ }
80
+ map.set(entry[0], entry[1]);
81
+ }
82
+ return map;
83
+ }
84
+ if (Array.isArray(value.$set)) return new Set(revive(value.$set, key, at, depth, context));
60
85
  const out = {};
61
86
  for (const name of Object.keys(value)) {
62
87
  define(out, name, revive(value[name], name, `${at}.${name}`, depth + 1, context));
@@ -111,14 +136,20 @@ const structDef = (fields, at, depth, context) => {
111
136
  return out;
112
137
  };
113
138
 
114
- // An entity as a definition: its kind as the first key with the metadata,
115
- // then its fields and its indexes; a schema of one type is that type.
139
+ // An entity as a definition: its kind as the first key with the metadata
140
+ // (a lowercase name, which becomes the capitalized key), then its fields
141
+ // and its indexes; a schema of one type is that type. A name that starts
142
+ // with `.` is no entity a model writes (it skips them).
116
143
  const entityDef = (name, entity, context) => {
117
144
  context.at = name;
118
- if (!isObject(entity) || typeof entity.kind !== 'string') {
145
+ if (name.startsWith('.')) throw invalidSnapshot('An entity of a snapshot needs a name');
146
+ if (!isObject(entity) || typeof entity.kind !== 'string' || !isFirstLower(entity.kind)) {
119
147
  throw invalidSnapshot('An entity of a snapshot needs a kind');
120
148
  }
121
- const { scope, store, allow, unknown, custom, fields, indexes } = entity;
149
+ const { scope, store, allow, unknown, parent, custom, fields, indexes } = entity;
150
+ if (parent !== undefined && typeof parent !== 'string') {
151
+ throw invalidSnapshot('The parent of an entity must be a name');
152
+ }
122
153
  if (fields === undefined) return fieldDef(entity.type, name, 0, context);
123
154
  for (const key of ['fields', 'custom', 'indexes']) {
124
155
  if (entity[key] !== undefined && !isObject(entity[key])) {
@@ -128,7 +159,8 @@ const entityDef = (name, entity, context) => {
128
159
  // The keys of the kind win over `custom`: a snapshot does not loosen
129
160
  // `unknown` through its metadata.
130
161
  const revived = revive(custom, 'custom', `${name}.custom`, 0, context);
131
- const def = { [capitalize(entity.kind)]: { ...revived, scope, store, allow, unknown } };
162
+ const meta = { ...revived, scope, store, allow, unknown, parent };
163
+ const def = { [capitalize(entity.kind)]: meta };
132
164
  const struct = structDef(fields, name, 0, context);
133
165
  for (const key of Object.keys(struct)) define(def, key, struct[key]);
134
166
  for (const key of Object.keys(indexes ?? {})) {
@@ -185,7 +217,9 @@ const typesDef = (given, context) => {
185
217
  return out;
186
218
  };
187
219
 
188
- // The model of a snapshot. `options.types` are entries of the table Model
220
+ // The model of a snapshot, of a model or of one schema (`root` names the
221
+ // entity it is about; `model.entities.get(snapshot.root)` is that schema
222
+ // again). `options.types` are entries of the table Model
189
223
  // takes, over the ones of the snapshot (the real custom types); the
190
224
  // registry is 'isolated' unless `options.registry` says otherwise, so the
191
225
  // placeholders never reach the shared one. The model lists the paths of its
@@ -194,6 +228,7 @@ const fromJSON = (snapshot, options = {}) => {
194
228
  if (!isSnapshot(snapshot)) {
195
229
  throw invalidSnapshot('A snapshot of format 1 with entities is expected');
196
230
  }
231
+ checkRoot(snapshot);
197
232
  if (!isObject(options)) {
198
233
  throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Restore options must be an object');
199
234
  }
@@ -218,7 +253,17 @@ const fromJSON = (snapshot, options = {}) => {
218
253
  throw field ? located.locate(context.name, field) : atSchema(located, context.name);
219
254
  }
220
255
  Object.assign(types, given);
221
- const model = new Model(types, entities, snapshot.database ?? null, { registry });
256
+ let model;
257
+ try {
258
+ model = new Model(types, entities, snapshot.database ?? null, { registry });
259
+ } catch (error) {
260
+ // What the core rejects is located already; anything else is the
261
+ // snapshot's too, never a bare TypeError.
262
+ if (error instanceof SchemaDefinitionError) throw error;
263
+ const wrapped = invalidSnapshot(`The model of the snapshot cannot be built: ${error.message}`);
264
+ wrapped.cause = error;
265
+ throw wrapped;
266
+ }
222
267
  Object.defineProperty(model, 'placeholders', { value: Array.from(context.placeholders) });
223
268
  return model;
224
269
  };
@@ -89,13 +89,20 @@ const stringOf = (state, field, key) => {
89
89
 
90
90
  const asNumber = (value) => (typeof value === 'bigint' ? Number(value) : value);
91
91
 
92
+ // A number within the bounds; a whole one, or one of `decimals` decimals,
93
+ // rounded toward the inside of the bounds.
92
94
  const numberOf = (state, field, whole) => {
93
95
  const min = asNumber(field.min);
94
96
  const max = asNumber(field.max);
95
97
  const low = min ?? (max === undefined ? 0 : max - 100);
96
98
  const high = max ?? low + 100;
97
99
  const value = low + state.random() * (high - low);
98
- return whole ? Math.min(Math.ceil(value), Math.floor(high)) : value;
100
+ const scale = whole ? 1 : field.decimals === undefined ? 0 : 10 ** field.decimals;
101
+ // Past 2⁵³ units of the last decimal every double is a whole number of
102
+ // them (and the product may be no number at all): the value is one.
103
+ if (scale === 0 || !(Math.abs(value * scale) < 2 ** 53)) return value;
104
+ const up = Math.ceil(value * scale) / scale;
105
+ return up > high ? Math.floor(value * scale) / scale : up;
99
106
  };
100
107
 
101
108
  // The widest span a bigint is drawn from: what a number holds exactly.
@@ -113,6 +120,20 @@ const bigintOf = (state, field) => {
113
120
  return low + BigInt(int(state, Number(span)));
114
121
  };
115
122
 
123
+ // Random bytes within the length rule, up to sixteen without one.
124
+ const bytesOf = (state, field) => {
125
+ const bytes = new Uint8Array(countOf(state, field.length, 0, 16));
126
+ for (let index = 0; index < bytes.length; index += 1) bytes[index] = int(state, 255);
127
+ return bytes;
128
+ };
129
+
130
+ // Every name of a flags field present half the time, each true or false.
131
+ const flagsOf = (state, field) => {
132
+ const out = {};
133
+ for (const name of field.flags) if (state.random() < 0.5) out[name] = state.random() < 0.5;
134
+ return out;
135
+ };
136
+
116
137
  const idOf = (state, name) => `${name.toLowerCase()}-${int(state, 0xffff).toString(16)}`;
117
138
 
118
139
  const keyOf = (state, index, numeric) =>
@@ -263,6 +284,10 @@ const draw = (state, field, key) => {
263
284
  return state.random() < 0.5;
264
285
  case 'date':
265
286
  return new Date(1_600_000_000_000 + Math.floor(state.random() * 100_000_000_000));
287
+ case 'bytes':
288
+ return bytesOf(state, field);
289
+ case 'flags':
290
+ return flagsOf(state, field);
266
291
  case 'null':
267
292
  return null;
268
293
  case 'any':