@alexify/metaschema 3.2.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 (62) hide show
  1. package/CHANGELOG.md +307 -1
  2. package/README.md +173 -89
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +601 -29
  5. package/package.json +28 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +201 -46
  8. package/src/coerce/index.d.ts +34 -0
  9. package/src/coerce/index.js +385 -0
  10. package/src/compile/emit.js +87 -28
  11. package/src/compile/index.js +9 -4
  12. package/src/context.js +6 -1
  13. package/src/definition/index.d.ts +19 -0
  14. package/src/definition/index.js +27 -0
  15. package/src/derive/index.d.ts +86 -0
  16. package/src/derive/index.js +273 -0
  17. package/src/errors.js +46 -4
  18. package/src/formats/index.d.ts +20 -8
  19. package/src/formats/index.js +450 -39
  20. package/src/generators/fromjsonschema.js +21 -2
  21. package/src/generators/index.js +1 -1
  22. package/src/generators/jsonschema.js +90 -21
  23. package/src/generators/typescript.js +11 -0
  24. package/src/index.js +3 -2
  25. package/src/issues.js +9 -7
  26. package/src/kinds.js +15 -3
  27. package/src/lint.js +38 -0
  28. package/src/locales/en.js +6 -0
  29. package/src/locales/uk.js +6 -0
  30. package/src/metadata.js +6 -24
  31. package/src/model/data.js +67 -10
  32. package/src/model/diff.js +7 -4
  33. package/src/model/index.js +1 -1
  34. package/src/model/infer.js +10 -3
  35. package/src/model/merge.js +16 -9
  36. package/src/model/restore.js +52 -7
  37. package/src/model/sample.js +28 -4
  38. package/src/model.js +54 -56
  39. package/src/mongodb/bson.js +130 -0
  40. package/src/mongodb/document.js +217 -0
  41. package/src/mongodb/index.d.ts +133 -0
  42. package/src/mongodb/index.js +24 -0
  43. package/src/mongodb/indexes.js +79 -0
  44. package/src/mongodb/update.js +258 -0
  45. package/src/preprocessor.js +1 -2
  46. package/src/prototypes/abstract.js +41 -67
  47. package/src/prototypes/collections.js +3 -90
  48. package/src/prototypes/flags.js +34 -0
  49. package/src/prototypes/json.js +0 -11
  50. package/src/prototypes/reference.js +0 -76
  51. package/src/prototypes/scalars.js +17 -96
  52. package/src/prototypes/schema.js +1 -10
  53. package/src/prototypes/tuple.js +0 -26
  54. package/src/prototypes/union.js +12 -82
  55. package/src/rules.js +33 -157
  56. package/src/schema.js +105 -220
  57. package/src/snapshot.js +216 -41
  58. package/src/stream/index.js +1 -1
  59. package/src/struct.js +6 -91
  60. package/src/types.js +43 -6
  61. package/src/util.js +43 -0
  62. package/src/validation.js +313 -0
@@ -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));
@@ -9,7 +9,15 @@ const { Schema } = require('../schema.js');
9
9
  const { isStruct } = require('../struct.js');
10
10
  const { isThenable } = require('../issues.js');
11
11
  const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
12
- const { same, capitalize, definitionOf, structDefinitionOf, atSchema } = require('./data.js');
12
+ const {
13
+ same,
14
+ definitionOf,
15
+ structDefinitionOf,
16
+ metadataOf,
17
+ structDefinition,
18
+ atSchema,
19
+ namespacesOf,
20
+ } = require('./data.js');
13
21
 
14
22
  // The keys a field definition settles by a rule of its own; every other key
15
23
  // (an annotation, an option of a custom type) comes from the first schema.
@@ -51,7 +59,7 @@ const mergeLength = (a, b, path) => {
51
59
  return length;
52
60
  };
53
61
 
54
- const mergeEnum = (a, b, path) => {
62
+ const mergeEnum = (a, b, path, what = 'enums') => {
55
63
  const values = [];
56
64
  for (const value of a) {
57
65
  for (const other of b) {
@@ -61,7 +69,7 @@ const mergeEnum = (a, b, path) => {
61
69
  }
62
70
  }
63
71
  }
64
- 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);
65
73
  return values;
66
74
  };
67
75
 
@@ -90,9 +98,12 @@ const mergeKey = (key, a, b, path) => {
90
98
  case 'min':
91
99
  return a > b ? a : b;
92
100
  case 'max':
101
+ case 'decimals':
93
102
  return a < b ? a : b;
94
103
  case 'enum':
95
104
  return mergeEnum(a, b, path);
105
+ case 'flags':
106
+ return mergeEnum(a, b, path, 'flags');
96
107
  case 'validate':
97
108
  return compose(a, b);
98
109
  case 'aliases':
@@ -204,7 +215,7 @@ const merge = (a, b, options = {}) => {
204
215
  throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Merge options must be an object');
205
216
  }
206
217
  const { name = a.name, metadata = {} } = options;
207
- const namespaces = Array.from(new Set([...a.namespaces, ...b.namespaces]));
218
+ const namespaces = namespacesOf([a, b]);
208
219
  const structA = isStruct(a.fields);
209
220
  const structB = isStruct(b.fields);
210
221
  try {
@@ -216,12 +227,8 @@ const merge = (a, b, options = {}) => {
216
227
  namespaces,
217
228
  );
218
229
  }
219
- const { kind, scope, store, allow, unknown, custom } = a;
220
- const meta = { scope, store, allow, unknown, ...custom, ...metadata };
221
- const { kind: given = kind, ...rest } = meta;
222
- const definition = { [capitalize(given)]: rest };
223
230
  const fields = mergeStruct(structDefinitionOf(a.fields), structDefinitionOf(b.fields), '');
224
- for (const key of Object.keys(fields)) define(definition, key, fields[key]);
231
+ const definition = structDefinition(metadataOf(a), metadata, fields);
225
232
  for (const source of [a, b]) {
226
233
  for (const key in source.indexes) {
227
234
  const index = source.indexes[key];
@@ -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
  };
@@ -9,6 +9,7 @@ const { hasBrand, define } = require('../util.js');
9
9
  const { createContext } = require('../context.js');
10
10
  const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
11
11
  const { isStruct } = require('../struct.js');
12
+ const { baseTypeOf } = require('../types.js');
12
13
  const { embeds } = require('../prototypes/reference.js');
13
14
  const { toDotPath, finalize } = require('../issues.js');
14
15
  const en = require('../locales/en.js');
@@ -48,9 +49,7 @@ const ABSENT = Symbol('absent');
48
49
  // The built-in type a field validates as: its own, or the one its alias
49
50
  // chain ends in; a custom type with a check of its own has none.
50
51
  const baseOf = (field) => {
51
- const { types } = field.root;
52
- let Type = field.constructor;
53
- while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
52
+ const Type = baseTypeOf(field);
54
53
  return Type.source === undefined ? Type.type : null;
55
54
  };
56
55
 
@@ -90,13 +89,20 @@ const stringOf = (state, field, key) => {
90
89
 
91
90
  const asNumber = (value) => (typeof value === 'bigint' ? Number(value) : value);
92
91
 
92
+ // A number within the bounds; a whole one, or one of `decimals` decimals,
93
+ // rounded toward the inside of the bounds.
93
94
  const numberOf = (state, field, whole) => {
94
95
  const min = asNumber(field.min);
95
96
  const max = asNumber(field.max);
96
97
  const low = min ?? (max === undefined ? 0 : max - 100);
97
98
  const high = max ?? low + 100;
98
99
  const value = low + state.random() * (high - low);
99
- 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;
100
106
  };
101
107
 
102
108
  // The widest span a bigint is drawn from: what a number holds exactly.
@@ -114,6 +120,20 @@ const bigintOf = (state, field) => {
114
120
  return low + BigInt(int(state, Number(span)));
115
121
  };
116
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
+
117
137
  const idOf = (state, name) => `${name.toLowerCase()}-${int(state, 0xffff).toString(16)}`;
118
138
 
119
139
  const keyOf = (state, index, numeric) =>
@@ -264,6 +284,10 @@ const draw = (state, field, key) => {
264
284
  return state.random() < 0.5;
265
285
  case 'date':
266
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);
267
291
  case 'null':
268
292
  return null;
269
293
  case 'any':
package/src/model.js CHANGED
@@ -1,32 +1,53 @@
1
- const { firstKey } = require('./metautil.js');
1
+ const { firstKey, isFirstLower } = require('./metautil.js');
2
2
 
3
- const { BRAND, INSPECT } = require('./util.js');
3
+ const { BRAND, INSPECT, CYCLES } = require('./util.js');
4
4
  const { Schema } = require('./schema.js');
5
5
  const { TYPES, createRegistry, typeFactory } = require('./types.js');
6
- const { SchemaDefinitionError } = require('./errors.js');
7
- const { warning } = require('./lint.js');
8
- const { snapshotOf } = require('./snapshot.js');
6
+ const { SchemaDefinitionError, noValidation } = require('./errors.js');
7
+ const { snapshotOf, orderOf } = require('./snapshot.js');
8
+
9
+ const invalidOption = (name, expected, value) => {
10
+ const reason = `Model option "${name}" must be ${expected}, got ${JSON.stringify(value)}`;
11
+ return new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
12
+ };
9
13
 
10
14
  const registryFor = (options) => {
11
15
  const { registry = 'shared' } = options;
12
16
  if (registry !== 'shared' && registry !== 'isolated') {
13
- const reason = `Model option "registry" must be "shared" or "isolated", got ${JSON.stringify(registry)}`;
14
- throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
17
+ throw invalidOption('registry', '"shared" or "isolated"', registry);
15
18
  }
16
19
  return registry === 'isolated' ? createRegistry() : TYPES;
17
20
  };
18
21
 
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;
22
+ // The converters of coercion the model gives for its own type names, read
23
+ // by the `./coerce` subpath before the process-wide table for the fields
24
+ // of its entities (and of a schema that attaches the model): what an
25
+ // isolated registry is to the types. Frozen, with no prototype.
26
+ const coercionsFor = (options) => {
27
+ const { coercions = null } = options;
28
+ if (coercions === null) return null;
29
+ const expected = 'an object of functions by type name';
30
+ if (typeof coercions !== 'object' || Array.isArray(coercions)) {
31
+ throw invalidOption('coercions', expected, coercions);
32
+ }
33
+ const table = Object.create(null);
34
+ for (const name of Object.keys(coercions)) {
35
+ if (!isFirstLower(name) || typeof coercions[name] !== 'function') {
36
+ throw invalidOption('coercions', expected, name);
37
+ }
38
+ table[name] = coercions[name];
39
+ }
40
+ return Object.freeze(table);
41
+ };
24
42
 
43
+ class Model {
25
44
  constructor(types, entities, database = null, options = {}) {
26
45
  this.types = typeFactory(types, registryFor(options));
46
+ this.coercions = coercionsFor(options);
27
47
  this.entities = new Map();
28
48
  this.database = database;
29
49
  this.order = new Set();
50
+ this[CYCLES] = [];
30
51
  const projections = [];
31
52
  for (const pair of entities) {
32
53
  const name = pair[0];
@@ -48,26 +69,6 @@ class Model {
48
69
  this.#preprocess();
49
70
  }
50
71
 
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
- const add = (list) => {
57
- for (let index = 0; index < list.length; index += 1) warnings.push(list[index]);
58
- };
59
- for (const pair of this.entities) {
60
- const name = pair[0];
61
- const entity = pair[1];
62
- if (name.startsWith('.')) continue;
63
- add(entity.warnings);
64
- add(entity.checkConsistency());
65
- }
66
- add(this.#cycles);
67
- this.#warnings = warnings;
68
- return warnings;
69
- }
70
-
71
72
  // The model as plain JSON: `{ format, database, types, entities }`, the
72
73
  // entities in dependency order with their metadata, fields, indexes and
73
74
  // relations, and the types they use. What JSON.stringify(model) writes.
@@ -79,37 +80,34 @@ class Model {
79
80
  return `Model ${inspect(this.toJSON(), options)}`;
80
81
  }
81
82
 
83
+ // Depth-first ordering (`orderOf`): an entity after everything it
84
+ // references among the entities, `Identifier` first; a reference back into
85
+ // the path of the walk is a cycle of any length, recorded.
82
86
  #preprocess() {
83
87
  const { entities, order } = this;
84
88
  if (entities.has('Identifier')) order.add('Identifier');
85
- for (const name of entities.keys()) {
86
- const isMeta = name.startsWith('.');
87
- if (!isMeta) this.#reorderEntity(name, new Set());
88
- }
89
- }
90
-
91
- // Depth-first ordering: an entity is added after everything it references.
92
- // `visiting` holds the current path, so a reference back into it is a cycle
93
- // of any length, not only one through the entity the walk started from.
94
- #reorderEntity(name, visiting) {
95
- const entity = this.entities.get(name);
96
- if (!entity || this.order.has(name)) return;
97
- visiting.add(name);
98
- for (const ref of entity.references) {
99
- if (ref === name) continue;
100
- if (visiting.has(ref)) {
101
- this.#cycles.push(
102
- warning('recursive-reference', `"${name}" depends on "${ref}" recursively`),
103
- );
104
- continue;
89
+ const starts = [];
90
+ for (const pair of entities) if (!pair[0].startsWith('.')) starts.push(pair);
91
+ const edgesOf = (entity) => {
92
+ const edges = [];
93
+ for (const ref of entity.references) {
94
+ const target = entities.get(ref);
95
+ if (target !== undefined) edges.push([ref, target]);
105
96
  }
106
- this.#reorderEntity(ref, visiting);
107
- }
108
- visiting.delete(name);
109
- this.order.add(name);
97
+ return edges;
98
+ };
99
+ orderOf(starts, edgesOf, (name, ref) => this[CYCLES].push([name, ref]), order);
110
100
  }
111
101
  }
112
102
 
103
+ // The warnings of a model are the validation half's, as a schema's are.
104
+ Object.defineProperty(Model.prototype, 'warnings', {
105
+ get() {
106
+ throw noValidation('warnings');
107
+ },
108
+ configurable: true,
109
+ });
110
+
113
111
  Model.prototype[BRAND] = 'Model';
114
112
 
115
113
  module.exports = { Model };
@@ -0,0 +1,130 @@
1
+ // The BSON side of the `./mongodb` subpath: the types a field holds a value
2
+ // of the driver in, and the module of the driver the program registers, the
3
+ // one that turns the ids a record carries as strings into ObjectIds. Nothing
4
+ // is imported from bson or mongodb: a value of the driver is recognized by
5
+ // its `_bsontype` and by a method that JSON cannot give a value (a body of a
6
+ // request claiming to be an ObjectId is data), never by `instanceof`, so a
7
+ // value of another realm or of another copy of bson is one too.
8
+ const { idFieldOf } = require('../kinds.js');
9
+ const { invalidOption, notRegistered } = require('../errors.js');
10
+ const { isBytes } = require('../util.js');
11
+ const { register: coercion } = require('../coerce/index.js');
12
+
13
+ // The tag every value of bson carries, and the key of a document.
14
+ const TAG = '_bsontype';
15
+ const ID = '_id';
16
+
17
+ const tagOf = (value) => (value !== null && typeof value === 'object' ? value[TAG] : undefined);
18
+
19
+ const isObjectId = (value) => {
20
+ const tag = tagOf(value);
21
+ return (tag === 'ObjectId' || tag === 'ObjectID') && typeof value.toHexString === 'function';
22
+ };
23
+
24
+ const isDecimal128 = (value) => tagOf(value) === 'Decimal128' && typeof value.toJSON === 'function';
25
+
26
+ // The bytes of a generic Binary of the driver (subtype 0, or 2, its old
27
+ // form), copied off the memory the driver read it into; null for anything
28
+ // else. A Binary of another subtype (a UUID, an encrypted value, a vector)
29
+ // written back as bytes would lose its subtype, so it is left for the check.
30
+ const binaryBytes = (value) => {
31
+ const binary = tagOf(value) === 'Binary' && typeof value.toJSON === 'function';
32
+ if (!binary || !isBytes(value.buffer)) return null;
33
+ const subtype = value.sub_type;
34
+ if (subtype !== 0 && subtype !== 2) return null;
35
+ return new Uint8Array(value.buffer.subarray(0, value.position));
36
+ };
37
+
38
+ const isBinary = (value) =>
39
+ (tagOf(value) === 'Binary' && typeof value.toJSON === 'function') || isBytes(value);
40
+
41
+ const construct = () => {};
42
+
43
+ // A custom type as a model takes it: the check, the BSON type of the
44
+ // mongodb target and the JSON Schema of the value on the wire.
45
+ const typeOf = (test, bson, jsonSchema) =>
46
+ Object.freeze({
47
+ construct,
48
+ checkType: (value) => test(value),
49
+ metadata: Object.freeze({ bson, jsonSchema }),
50
+ });
51
+
52
+ const HEX = /^[0-9a-fA-F]{24}$/;
53
+
54
+ // The types to give a model: `new Model({ ...types, ...own }, entities)`.
55
+ // They are not registered by register(): a type name is a shorthand key of
56
+ // a definition, so a program says where it uses them.
57
+ const types = Object.freeze({
58
+ objectId: typeOf(isObjectId, 'objectId', { type: 'string', pattern: HEX.source }),
59
+ decimal128: typeOf(isDecimal128, 'decimal', { type: 'string' }),
60
+ binary: typeOf(isBinary, 'binData', { type: 'string', contentEncoding: 'base64' }),
61
+ });
62
+
63
+ // The module of the driver (or of bson) the program registered.
64
+ let driver = null;
65
+
66
+ const driverOf = () => {
67
+ if (driver === null) throw notRegistered('An ObjectId', 'mongodb');
68
+ return driver;
69
+ };
70
+
71
+ // The converters of coercion for the BSON types, the ones parse runs on the
72
+ // input of a field of such a type: a 24-digit hex string is an ObjectId, a
73
+ // decimal string or a number a Decimal128, base64 text a Binary. What they
74
+ // cannot read comes back as it was, for the check to report.
75
+ const toObjectId = (value) =>
76
+ typeof value === 'string' && HEX.test(value) ? new driver.ObjectId(value) : value;
77
+
78
+ // A decimal written as one (`fromString` of the driver reads `NaN`, `inf`
79
+ // and an exponent too), or a finite number.
80
+ const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
81
+
82
+ const toDecimal128 = (value) => {
83
+ if (typeof value === 'number') {
84
+ return Number.isFinite(value) ? driver.Decimal128.fromString(String(value)) : value;
85
+ }
86
+ return typeof value === 'string' && DECIMAL.test(value)
87
+ ? driver.Decimal128.fromString(value)
88
+ : value;
89
+ };
90
+
91
+ // Text of the base64 shape only: the decoder of the driver reads anything,
92
+ // and the empty string is never converted.
93
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
94
+
95
+ const toBinary = (value) =>
96
+ typeof value === 'string' && value.length % 4 === 0 && BASE64.test(value)
97
+ ? driver.Binary.createFromBase64(value)
98
+ : value;
99
+
100
+ // Takes the module of the driver (`require('mongodb')`, which carries the
101
+ // bson it was built with) or of bson, and installs the converters of the
102
+ // BSON types into the coercion of `./coerce`: the one of a type the module
103
+ // cannot build (a slim build without `Decimal128` or `Binary`) is not
104
+ // installed, so that such a value is reported by the check rather than
105
+ // lost in a converter that throws. Once: another module after the first is
106
+ // an error, since values of the first are in the program.
107
+ const register = (options) => {
108
+ const bson = options === null || typeof options !== 'object' ? undefined : options.bson;
109
+ const valid = bson !== null && typeof bson === 'object' && typeof bson.ObjectId === 'function';
110
+ if (!valid) {
111
+ throw invalidOption('bson', 'the module of the mongodb driver or of bson', typeof bson);
112
+ }
113
+ if (driver !== null && driver !== bson) {
114
+ throw invalidOption('bson', 'the module registered before', 'another one');
115
+ }
116
+ const converters = { objectId: toObjectId };
117
+ if (typeof bson.Decimal128?.fromString === 'function') converters.decimal128 = toDecimal128;
118
+ if (typeof bson.Binary?.createFromBase64 === 'function') converters.binary = toBinary;
119
+ driver = bson;
120
+ coercion(converters);
121
+ };
122
+
123
+ // The id field a stored kind adds, which a document holds as `_id`, unless
124
+ // the schema has an `_id` of its own.
125
+ const idOf = (schema) => {
126
+ const id = idFieldOf(schema);
127
+ return id === null || ID in schema.fields ? null : id;
128
+ };
129
+
130
+ module.exports = { ID, HEX, types, register, driverOf, idOf, isObjectId, binaryBytes };