@alexify/metaschema 3.1.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.
- package/CHANGELOG.md +314 -1
- package/README.md +535 -20
- package/SECURITY.md +26 -7
- package/index.d.ts +496 -2
- package/package.json +53 -5
- package/src/codec.js +239 -74
- package/src/coerce/index.d.ts +34 -0
- package/src/coerce/index.js +352 -0
- package/src/compile/code.js +1 -1
- package/src/compile/emit.js +32 -7
- package/src/compile/index.d.ts +6 -0
- package/src/compile/index.js +12 -1
- package/src/context.js +11 -10
- package/src/derive/index.d.ts +86 -0
- package/src/derive/index.js +266 -0
- package/src/errors.js +28 -1
- package/src/formats/index.d.ts +31 -0
- package/src/formats/index.js +557 -0
- package/src/generators/fromjsonschema.js +16 -14
- package/src/generators/index.js +2 -1
- package/src/generators/jsonschema.js +47 -13
- package/src/issues.js +37 -20
- package/src/kinds.js +11 -2
- package/src/lint.js +24 -0
- package/src/locales/en.js +11 -2
- package/src/locales/uk.js +10 -2
- package/src/metadata.js +7 -2
- package/src/model/data.js +17 -0
- package/src/model/diff.js +1 -0
- package/src/model/index.d.ts +14 -2
- package/src/model/index.js +13 -10
- package/src/model/infer.js +483 -0
- package/src/model/merge.js +10 -6
- package/src/model/restore.js +3 -3
- package/src/model/sample.js +8 -5
- package/src/model.js +34 -4
- package/src/mongodb/bson.js +118 -0
- package/src/mongodb/document.js +209 -0
- package/src/mongodb/index.d.ts +133 -0
- package/src/mongodb/index.js +24 -0
- package/src/mongodb/indexes.js +79 -0
- package/src/mongodb/update.js +258 -0
- package/src/preprocessor.js +1 -0
- package/src/prototypes/abstract.js +9 -3
- package/src/prototypes/collections.js +4 -3
- package/src/prototypes/scalars.js +4 -4
- package/src/prototypes/union.js +2 -2
- package/src/result.js +6 -0
- package/src/rules.js +53 -4
- package/src/schema.js +53 -28
- package/src/snapshot.js +1 -1
- package/src/stream/index.d.ts +68 -0
- package/src/stream/index.js +247 -0
- package/src/struct.js +1 -1
- package/src/types.js +33 -1
- package/src/util.js +18 -0
|
@@ -0,0 +1,118 @@
|
|
|
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 { register: coercion } = require('../coerce/index.js');
|
|
11
|
+
|
|
12
|
+
// The tag every value of bson carries, and the key of a document.
|
|
13
|
+
const TAG = '_bsontype';
|
|
14
|
+
const ID = '_id';
|
|
15
|
+
|
|
16
|
+
const tagOf = (value) => (value !== null && typeof value === 'object' ? value[TAG] : undefined);
|
|
17
|
+
|
|
18
|
+
const isObjectId = (value) => {
|
|
19
|
+
const tag = tagOf(value);
|
|
20
|
+
return (tag === 'ObjectId' || tag === 'ObjectID') && typeof value.toHexString === 'function';
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const isDecimal128 = (value) => tagOf(value) === 'Decimal128' && typeof value.toJSON === 'function';
|
|
24
|
+
|
|
25
|
+
const isBinary = (value) =>
|
|
26
|
+
(tagOf(value) === 'Binary' && typeof value.toJSON === 'function') ||
|
|
27
|
+
Object.prototype.toString.call(value) === '[object Uint8Array]';
|
|
28
|
+
|
|
29
|
+
const construct = () => {};
|
|
30
|
+
|
|
31
|
+
// A custom type as a model takes it: the check, the BSON type of the
|
|
32
|
+
// mongodb target and the JSON Schema of the value on the wire.
|
|
33
|
+
const typeOf = (test, bson, jsonSchema) =>
|
|
34
|
+
Object.freeze({
|
|
35
|
+
construct,
|
|
36
|
+
checkType: (value) => test(value),
|
|
37
|
+
metadata: Object.freeze({ bson, jsonSchema }),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const HEX = /^[0-9a-fA-F]{24}$/;
|
|
41
|
+
|
|
42
|
+
// The types to give a model: `new Model({ ...types, ...own }, entities)`.
|
|
43
|
+
// They are not registered by register(): a type name is a shorthand key of
|
|
44
|
+
// a definition, so a program says where it uses them.
|
|
45
|
+
const types = Object.freeze({
|
|
46
|
+
objectId: typeOf(isObjectId, 'objectId', { type: 'string', pattern: HEX.source }),
|
|
47
|
+
decimal128: typeOf(isDecimal128, 'decimal', { type: 'string' }),
|
|
48
|
+
binary: typeOf(isBinary, 'binData', { type: 'string', contentEncoding: 'base64' }),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// The module of the driver (or of bson) the program registered.
|
|
52
|
+
let driver = null;
|
|
53
|
+
|
|
54
|
+
const driverOf = () => {
|
|
55
|
+
if (driver === null) throw notRegistered('An ObjectId', 'mongodb');
|
|
56
|
+
return driver;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// The converters of coercion for the BSON types, the ones parse runs on the
|
|
60
|
+
// input of a field of such a type: a 24-digit hex string is an ObjectId, a
|
|
61
|
+
// decimal string or a number a Decimal128, base64 text a Binary. What they
|
|
62
|
+
// cannot read comes back as it was, for the check to report.
|
|
63
|
+
const toObjectId = (value) =>
|
|
64
|
+
typeof value === 'string' && HEX.test(value) ? new driver.ObjectId(value) : value;
|
|
65
|
+
|
|
66
|
+
// A decimal written as one (`fromString` of the driver reads `NaN`, `inf`
|
|
67
|
+
// and an exponent too), or a finite number.
|
|
68
|
+
const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
69
|
+
|
|
70
|
+
const toDecimal128 = (value) => {
|
|
71
|
+
if (typeof value === 'number') {
|
|
72
|
+
return Number.isFinite(value) ? driver.Decimal128.fromString(String(value)) : value;
|
|
73
|
+
}
|
|
74
|
+
return typeof value === 'string' && DECIMAL.test(value)
|
|
75
|
+
? driver.Decimal128.fromString(value)
|
|
76
|
+
: value;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// Text of the base64 shape only: the decoder of the driver reads anything,
|
|
80
|
+
// and the empty string is never converted.
|
|
81
|
+
const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
82
|
+
|
|
83
|
+
const toBinary = (value) =>
|
|
84
|
+
typeof value === 'string' && value.length % 4 === 0 && BASE64.test(value)
|
|
85
|
+
? driver.Binary.createFromBase64(value)
|
|
86
|
+
: value;
|
|
87
|
+
|
|
88
|
+
// Takes the module of the driver (`require('mongodb')`, which carries the
|
|
89
|
+
// bson it was built with) or of bson, and installs the converters of the
|
|
90
|
+
// BSON types into the coercion of `./coerce`: the one of a type the module
|
|
91
|
+
// cannot build (a slim build without `Decimal128` or `Binary`) is not
|
|
92
|
+
// installed, so that such a value is reported by the check rather than
|
|
93
|
+
// lost in a converter that throws. Once: another module after the first is
|
|
94
|
+
// an error, since values of the first are in the program.
|
|
95
|
+
const register = (options) => {
|
|
96
|
+
const bson = options === null || typeof options !== 'object' ? undefined : options.bson;
|
|
97
|
+
const valid = bson !== null && typeof bson === 'object' && typeof bson.ObjectId === 'function';
|
|
98
|
+
if (!valid) {
|
|
99
|
+
throw invalidOption('bson', 'the module of the mongodb driver or of bson', typeof bson);
|
|
100
|
+
}
|
|
101
|
+
if (driver !== null && driver !== bson) {
|
|
102
|
+
throw invalidOption('bson', 'the module registered before', 'another one');
|
|
103
|
+
}
|
|
104
|
+
const converters = { objectId: toObjectId };
|
|
105
|
+
if (typeof bson.Decimal128?.fromString === 'function') converters.decimal128 = toDecimal128;
|
|
106
|
+
if (typeof bson.Binary?.createFromBase64 === 'function') converters.binary = toBinary;
|
|
107
|
+
driver = bson;
|
|
108
|
+
coercion(converters);
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// The id field a stored kind adds, which a document holds as `_id`, unless
|
|
112
|
+
// the schema has an `_id` of its own.
|
|
113
|
+
const idOf = (schema) => {
|
|
114
|
+
const id = idFieldOf(schema);
|
|
115
|
+
return id === null || ID in schema.fields ? null : id;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
module.exports = { ID, HEX, types, register, driverOf, idOf, isObjectId };
|
|
@@ -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 };
|