@alexify/metaschema 3.2.0 → 3.3.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.
@@ -0,0 +1,209 @@
1
+ // A record as MongoDB holds it and back: the program keeps the id of a
2
+ // stored record and its references as strings (`accountId: '?string'`), the
3
+ // database an ObjectId under `_id` and in every reference. The walk goes
4
+ // over the built types as the passes of parse do (`infoOf` of codec.js
5
+ // tells a node's shape), into nested structs, lists, dictionaries, tuples,
6
+ // discriminated unions and the records references embed; a plain union is
7
+ // left as it is. The value given is never written to.
8
+ const { hasBrand, define, isMap } = require('../util.js');
9
+ const { STRUCT, isStruct } = require('../struct.js');
10
+ const { embeds } = require('../prototypes/reference.js');
11
+ const { infoOf } = require('../codec.js');
12
+ const { referencesOf } = require('../context.js');
13
+ const { invalidTarget, invalidOption } = require('../errors.js');
14
+ const { ID, HEX, driverOf, idOf, isObjectId } = require('./bson.js');
15
+
16
+ // The shapes of infoOf in codec.js, by name, for the three walks of the
17
+ // subpath; `mongodb.test.js` holds them to the numbers of the core.
18
+ const SHAPES = Object.freeze({
19
+ LEAF: 0,
20
+ SCHEMA: 1,
21
+ FIELDS: 2,
22
+ NESTED: 3,
23
+ LIST: 4,
24
+ KEYED: 5,
25
+ TUPLE: 6,
26
+ UNION: 7,
27
+ REFERENCE: 8,
28
+ });
29
+
30
+ const { SCHEMA, FIELDS, NESTED, LIST, KEYED, TUPLE, UNION, REFERENCE } = SHAPES;
31
+
32
+ // A plain object of any realm: its prototype is the root of its realm or
33
+ // none (an Array, a Date, a Map or a value of bson has one in between).
34
+ const isPlain = (value) => {
35
+ const prototype = Object.getPrototypeOf(value);
36
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
37
+ };
38
+
39
+ // An id: to an ObjectId on the way out (a string of 24 hex digits, when the
40
+ // ids are ObjectIds), to its hex string on the way in.
41
+ const idValue = (state, value) => {
42
+ if (!state.out) return isObjectId(value) ? value.toHexString() : value;
43
+ if (!state.objectIds || typeof value !== 'string' || !HEX.test(value)) return value;
44
+ return new state.driver.ObjectId(value);
45
+ };
46
+
47
+ // A key of the output: assigned, defined only where assignment would reach
48
+ // the prototype (as the passes of codec.js write theirs).
49
+ const put = (out, key, value) => {
50
+ if (key === '__proto__') define(out, key, value);
51
+ else out[key] = value;
52
+ };
53
+
54
+ const listOf = (value, each) => {
55
+ const out = [];
56
+ for (let index = 0; index < value.length; index += 1) out.push(each(value[index], index));
57
+ return out;
58
+ };
59
+
60
+ // A record of a schema or a nested struct: the id field of a stored kind is
61
+ // `_id` in the document (first, and left out when there is none yet, so
62
+ // that the database gives one; an `_id` the value carries beside it is not
63
+ // the record's and is left out); the keys of calculated fields and the
64
+ // undefined values are not written. A key the schema does not have comes as
65
+ // it is; a record met again on its own path (a loop) too, and a `null` (what
66
+ // `findOne` gives for nothing) for the check to report.
67
+ const record = (state, owner, value) => {
68
+ const fields = hasBrand(owner, 'Schema') ? owner.fields : owner;
69
+ if (!isStruct(fields)) return walk(state, fields, value);
70
+ if (value === null || typeof value !== 'object' || !isPlain(value)) return value;
71
+ if (state.seen.has(value)) return value;
72
+ state.seen.add(value);
73
+ const id = hasBrand(owner, 'Schema') ? idOf(owner) : null;
74
+ const { calculated } = fields[STRUCT];
75
+ const out = {};
76
+ if (state.out && id !== null && value[id] != null) out[ID] = idValue(state, value[id]);
77
+ for (const key of Object.keys(value)) {
78
+ const item = value[key];
79
+ if (state.out) {
80
+ if (key === id || item === undefined || calculated.includes(key)) continue;
81
+ if (key === ID && id !== null && !(ID in fields)) continue;
82
+ } else if (key === ID && !(ID in fields)) {
83
+ // The key of the database: the record's id field, or nothing.
84
+ if (id !== null) put(out, id, idValue(state, item));
85
+ continue;
86
+ }
87
+ const field = fields[key];
88
+ put(out, key, hasBrand(field, 'Type') ? walk(state, field, item) : item);
89
+ }
90
+ state.seen.delete(value);
91
+ return out;
92
+ };
93
+
94
+ // A reference: the record through its entity where it is embedded, else
95
+ // the id (a list of them for `many`). The records embedded are counted as
96
+ // the check counts them, and one deeper than `maxDepth` is left as it is
97
+ // for the check to report: a reference is the one place a graph recurses.
98
+ const reference = (state, node, value) => {
99
+ const target = node.root.findReference(node.one || node.many);
100
+ const embedded = target !== null && embeds(target, node.embed, state.references);
101
+ const one = (item) => (embedded ? walk(state, target, item) : idValue(state, item));
102
+ if (embedded) {
103
+ if (state.depth >= state.maxDepth) return value;
104
+ state.depth += 1;
105
+ }
106
+ let out = value;
107
+ if (node.one) out = one(value);
108
+ else if (Array.isArray(value)) out = listOf(value, one);
109
+ if (embedded) state.depth -= 1;
110
+ return out;
111
+ };
112
+
113
+ const walk = (state, node, value) => {
114
+ if (value == null) return value;
115
+ const info = infoOf(node);
116
+ const { shape } = info;
117
+ if (shape === SCHEMA || shape === FIELDS) return record(state, node, value);
118
+ if (shape === NESTED) return record(state, node.schema, value);
119
+ if (shape === REFERENCE) return reference(state, node, value);
120
+ if (shape === LIST || shape === TUPLE) {
121
+ if (!Array.isArray(value)) return value;
122
+ const child = (index) => (shape === TUPLE ? node.value[index] : node.value);
123
+ return listOf(value, (item, index) =>
124
+ child(index) === undefined ? item : walk(state, child(index), item),
125
+ );
126
+ }
127
+ if (shape === KEYED) {
128
+ if (isMap(value)) {
129
+ const out = new Map();
130
+ for (const pair of value) out.set(pair[0], walk(state, node.value, pair[1]));
131
+ return out;
132
+ }
133
+ if (typeof value !== 'object' || !isPlain(value)) return value;
134
+ const out = {};
135
+ for (const key of Object.keys(value)) put(out, key, walk(state, node.value, value[key]));
136
+ return out;
137
+ }
138
+ if (shape === UNION && info.table !== null && typeof value === 'object') {
139
+ const index = info.table.get(value[node.discriminator]);
140
+ return index === undefined ? value : walk(state, node.union[index], value);
141
+ }
142
+ return value;
143
+ };
144
+
145
+ // The state of one walk, the options of the call checked. The driver is
146
+ // needed to build ObjectIds, so on the way out with `ids: 'objectId'`
147
+ // only: a document is read back without it.
148
+ const stateOf = (target, options, out) => {
149
+ if (!hasBrand(target, 'Schema') || !isStruct(target.fields)) {
150
+ throw invalidTarget('A Schema of a struct is expected');
151
+ }
152
+ const { ids = 'objectId', references = 'kind', maxDepth = 128 } = options ?? {};
153
+ if (ids !== 'objectId' && ids !== 'string') {
154
+ throw invalidOption('ids', '"objectId" or "string"', ids);
155
+ }
156
+ referencesOf(references);
157
+ if (!Number.isInteger(maxDepth) || maxDepth < 1) {
158
+ throw invalidOption('maxDepth', 'a positive integer', maxDepth);
159
+ }
160
+ const objectIds = ids === 'objectId';
161
+ const driver = out && objectIds ? driverOf() : null;
162
+ return { out, objectIds, references, seen: new Set(), driver, depth: 0, maxDepth };
163
+ };
164
+
165
+ // The root of a walk is the record itself: a value of a class (a model
166
+ // instance, a value of bson) has no document, and is reported rather than
167
+ // passed through unchanged.
168
+ const rootOf = (value) => {
169
+ if (value !== null && typeof value === 'object' && !isPlain(value)) {
170
+ throw invalidTarget('A plain object is expected');
171
+ }
172
+ return value;
173
+ };
174
+
175
+ // The document of a value: its serializers run, its ids made ObjectIds and
176
+ // the id of the record moved to `_id`.
177
+ const toDocument = (target, value, options) => {
178
+ const state = stateOf(target, options, true);
179
+ const serialized = target.serialize(rootOf(value), { references: state.references }).value;
180
+ return record(state, target, serialized);
181
+ };
182
+
183
+ const read = (target, document, options) =>
184
+ record(stateOf(target, options, false), target, rootOf(document));
185
+
186
+ const parsing = (options) => ({ coerce: true, ...options });
187
+
188
+ // The value of a document: `_id` back to the id field, ObjectIds to their
189
+ // hex strings, then parse, which coerces unless the options say otherwise.
190
+ const fromDocument = (target, document, options) => {
191
+ const value = read(target, document, options);
192
+ return target.parse(value, parsing(options));
193
+ };
194
+
195
+ const fromDocumentAsync = async (target, document, options) => {
196
+ const value = read(target, document, options);
197
+ return target.parseAsync(value, parsing(options));
198
+ };
199
+
200
+ module.exports = {
201
+ SHAPES,
202
+ toDocument,
203
+ fromDocument,
204
+ fromDocumentAsync,
205
+ walk,
206
+ idValue,
207
+ stateOf,
208
+ listOf,
209
+ };
@@ -0,0 +1,133 @@
1
+ import type {
2
+ CheckOptions,
3
+ InferOutput,
4
+ Model,
5
+ ParseOptions,
6
+ ParseResult,
7
+ Schema,
8
+ TypeEntry,
9
+ ValidationResult,
10
+ } from '../../index.js';
11
+
12
+ // What the subpath reads of the values of bson (4 to 6) or of the driver,
13
+ // which re-exports them; nothing is imported from either.
14
+ export interface ObjectIdLike {
15
+ readonly _bsontype: 'ObjectId' | 'ObjectID';
16
+ toHexString(): string;
17
+ }
18
+ export interface Decimal128Like {
19
+ readonly _bsontype: 'Decimal128';
20
+ toJSON(): unknown;
21
+ }
22
+ export interface BinaryLike {
23
+ readonly _bsontype: 'Binary';
24
+ toJSON(): unknown;
25
+ }
26
+
27
+ // The module of the driver (`require('mongodb')`) or of bson.
28
+ export interface BSONModule {
29
+ ObjectId: new (hex: string) => ObjectIdLike;
30
+ Decimal128?: { fromString(text: string): Decimal128Like };
31
+ Binary?: { createFromBase64(text: string): BinaryLike };
32
+ }
33
+
34
+ // The BSON types, to give a model: `new Model({ ...types, ...own }, entities)`.
35
+ // A value is one by its `_bsontype` and a method, never by `instanceof`;
36
+ // `binary` takes a Uint8Array too.
37
+ export const types: {
38
+ readonly objectId: TypeEntry;
39
+ readonly decimal128: TypeEntry;
40
+ readonly binary: TypeEntry;
41
+ };
42
+
43
+ // Keeps the module of the driver for the functions below and teaches
44
+ // `./coerce` the BSON types (a string of 24 hex digits is an ObjectId, a
45
+ // decimal string a Decimal128, base64 text a Binary). Once: another module
46
+ // after the first throws.
47
+ export function register(options: { bson: BSONModule }): void;
48
+
49
+ export interface DocumentOptions {
50
+ // The ids of stored records and references as ObjectIds (the default) or
51
+ // as the strings the program keeps.
52
+ ids?: 'objectId' | 'string';
53
+ // Which references are records (and so documents with their own `_id`)
54
+ // and which ids, as in `check`.
55
+ references?: 'kind' | 'embed' | 'id';
56
+ // How many embedded records deep the walk goes (128 by default, as in
57
+ // `check`); a record deeper is left as it is for the check to report.
58
+ maxDepth?: number;
59
+ }
60
+
61
+ // The document of a value: its serializers run, the id field of a stored
62
+ // record moved to `_id` (left out when there is none, so that the database
63
+ // gives one), ids made ObjectIds, undefined values and calculated fields left
64
+ // out. Needs `register()`: `ERR_NOT_REGISTERED` otherwise.
65
+ export function toDocument(
66
+ target: Schema,
67
+ value: unknown,
68
+ options?: DocumentOptions,
69
+ ): Record<string, unknown>;
70
+
71
+ // The value of a document: `_id` back to the id field, ObjectIds to their hex
72
+ // strings, then `parse` with `coerce: true` unless the options say otherwise.
73
+ export function fromDocument<D extends string | object>(
74
+ target: Schema<D>,
75
+ document: unknown,
76
+ options?: ParseOptions & Pick<DocumentOptions, 'references'>,
77
+ ): ParseResult<InferOutput<D>>;
78
+ export function fromDocumentAsync<D extends string | object>(
79
+ target: Schema<D>,
80
+ document: unknown,
81
+ options?: ParseOptions & Pick<DocumentOptions, 'references'>,
82
+ ): Promise<ParseResult<InferOutput<D>>>;
83
+
84
+ // An index as `createIndexes` takes it.
85
+ export interface IndexDescription {
86
+ key: Record<string, 1>;
87
+ name?: string;
88
+ unique?: true;
89
+ sparse?: true;
90
+ }
91
+
92
+ // The indexes of a schema, or of every stored entity of a model by name.
93
+ export function indexesOf(target: Schema): IndexDescription[];
94
+ export function indexesOf(target: Model): Record<string, IndexDescription[]>;
95
+
96
+ // An update of the driver: operators and the dotted paths they act on.
97
+ export type UpdateOperator =
98
+ | '$set'
99
+ | '$setOnInsert'
100
+ | '$unset'
101
+ | '$inc'
102
+ | '$mul'
103
+ | '$min'
104
+ | '$max'
105
+ | '$currentDate'
106
+ | '$push'
107
+ | '$addToSet'
108
+ | '$pull'
109
+ | '$pullAll'
110
+ | '$pop';
111
+ export type Update = { [O in UpdateOperator]?: Record<string, unknown> };
112
+
113
+ // The issues of an update against the schema: the field each path names,
114
+ // the value each operator sets, pushes or adds to it. The id of a stored
115
+ // record is set by `$setOnInsert` only.
116
+ export function checkUpdate(
117
+ target: Schema,
118
+ update: Update,
119
+ options?: CheckOptions,
120
+ ): ValidationResult;
121
+
122
+ // The update as the database takes it: the values serialized, their ids made
123
+ // ObjectIds, the id of the record as `_id`. Check it with `checkUpdate` first.
124
+ export function toUpdate(target: Schema, update: Update, options?: DocumentOptions): Update;
125
+
126
+ // `Infer` learns the BSON types once this file is loaded.
127
+ declare module '../../index.js' {
128
+ interface CustomTypes {
129
+ objectId: ObjectIdLike;
130
+ decimal128: Decimal128Like;
131
+ binary: BinaryLike | Uint8Array;
132
+ }
133
+ }
@@ -0,0 +1,24 @@
1
+ // The `./mongodb` subpath: the schema side of a MongoDB program, without a
2
+ // dependency on the driver and without I/O. The BSON types a field may hold
3
+ // (`types`, recognized without importing bson), the module of the driver the
4
+ // program registers (`register({ bson })`, which also teaches `./coerce` to
5
+ // read the BSON types), a record as the database holds it and back
6
+ // (`toDocument`, `fromDocument`), the indexes for `createIndexes`
7
+ // (`indexesOf`) and the updates of the driver checked and converted
8
+ // (`checkUpdate`, `toUpdate`). The collection validator is the mongodb
9
+ // target of `toJSONSchema` (`./generators`) with `ids: 'objectId'`.
10
+ const { types, register } = require('./bson.js');
11
+ const { toDocument, fromDocument, fromDocumentAsync } = require('./document.js');
12
+ const { indexesOf } = require('./indexes.js');
13
+ const { checkUpdate, toUpdate } = require('./update.js');
14
+
15
+ module.exports = {
16
+ types,
17
+ register,
18
+ toDocument,
19
+ fromDocument,
20
+ fromDocumentAsync,
21
+ indexesOf,
22
+ checkUpdate,
23
+ toUpdate,
24
+ };
@@ -0,0 +1,79 @@
1
+ // The indexes of a schema as MongoDB's `createIndexes` takes them: the
2
+ // index definitions of the schema (`{ naturalKey: { unique: [...] } }`, named
3
+ // after their key) and the fields marked `unique`, `index` or `primary`,
4
+ // nested structs and the structs of lists included, by their dotted paths.
5
+ // `_id` is MongoDB's primary key, so `primary` is a unique index; a unique
6
+ // field that may be missing is a sparse index. Data only: the program calls
7
+ // the driver.
8
+ const { hasBrand, define } = require('../util.js');
9
+ const { isStruct } = require('../struct.js');
10
+ const { infoOf } = require('../codec.js');
11
+ const { idFieldOf } = require('../kinds.js');
12
+ const { invalidTarget } = require('../errors.js');
13
+ const { idOf } = require('./bson.js');
14
+ const { SHAPES } = require('./document.js');
15
+
16
+ const { NESTED, LIST } = SHAPES;
17
+
18
+ const keyOf = (columns) => {
19
+ const key = {};
20
+ for (const column of columns) define(key, column, 1);
21
+ return key;
22
+ };
23
+
24
+ // The struct a field holds, itself or as the element of a list, or null.
25
+ const structOf = (field) => {
26
+ let node = field;
27
+ if (infoOf(node).shape === LIST) node = node.value;
28
+ return infoOf(node).shape === NESTED && isStruct(node.schema) ? node.schema : null;
29
+ };
30
+
31
+ const marked = (fields, prefix, skip, list) => {
32
+ for (const name in fields) {
33
+ const field = fields[name];
34
+ if (name === skip || !hasBrand(field, 'Type')) continue;
35
+ const path = prefix + name;
36
+ if (field.unique === true || field.primary === true || field.index === true) {
37
+ const index = { key: keyOf([path]) };
38
+ if (field.unique === true || field.primary === true) {
39
+ index.unique = true;
40
+ if (!field.required) index.sparse = true;
41
+ }
42
+ list.push(index);
43
+ }
44
+ const struct = structOf(field);
45
+ if (struct !== null) marked(struct, `${path}.`, null, list);
46
+ }
47
+ };
48
+
49
+ const indexesOfSchema = (schema) => {
50
+ const list = [];
51
+ for (const name in schema.indexes) {
52
+ const index = schema.indexes[name];
53
+ if (index.many !== undefined) continue;
54
+ const entry = { key: keyOf(index.index || index.primary || index.unique), name };
55
+ if (index.unique !== undefined || index.primary !== undefined) entry.unique = true;
56
+ list.push(entry);
57
+ }
58
+ marked(schema.fields, '', idOf(schema), list);
59
+ return list;
60
+ };
61
+
62
+ // The indexes of a schema, or of every stored entity of a model by name: a
63
+ // collection is what a stored kind (one with an id field) is kept in.
64
+ const indexesOf = (target) => {
65
+ if (hasBrand(target, 'Schema') && isStruct(target.fields)) return indexesOfSchema(target);
66
+ if (!hasBrand(target, 'Model')) {
67
+ throw invalidTarget('A Schema of a struct or a Model is expected');
68
+ }
69
+ const out = {};
70
+ for (const name of target.order) {
71
+ const schema = target.entities.get(name);
72
+ if (idFieldOf(schema) !== null && isStruct(schema.fields)) {
73
+ define(out, name, indexesOfSchema(schema));
74
+ }
75
+ }
76
+ return out;
77
+ };
78
+
79
+ module.exports = { indexesOf };