@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,483 @@
|
|
|
1
|
+
// The reverse of `sample` (`infer`): a definition that accepts every sample
|
|
2
|
+
// given, to bootstrap a model from documents that exist. One pass builds a
|
|
3
|
+
// summary of every place of the values (the kinds seen there, how often,
|
|
4
|
+
// the keys of records with their presence, the elements of lists), fusing
|
|
5
|
+
// the records of one place into one record with optional keys, as the
|
|
6
|
+
// schema inference of Baazizi et al. (EDBT 2017) does; the summary is then
|
|
7
|
+
// written as the most readable definition, and the definition is checked
|
|
8
|
+
// against every sample, so that what comes back is a schema the samples
|
|
9
|
+
// pass. The samples are input: the walk is bounded, no key is trusted, and
|
|
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');
|
|
13
|
+
const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
|
|
14
|
+
const { readsAsStruct } = require('../types.js');
|
|
15
|
+
const { FORMATS } = require('../rules.js');
|
|
16
|
+
const { toDotPath, finalize } = require('../issues.js');
|
|
17
|
+
const en = require('../locales/en.js');
|
|
18
|
+
const { DEPTH, capitalize } = require('./data.js');
|
|
19
|
+
|
|
20
|
+
const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
|
|
21
|
+
|
|
22
|
+
const invalidOptions = (reason) => invalid('ERR_INVALID_OPTIONS', reason);
|
|
23
|
+
|
|
24
|
+
// The kinds a place may hold, a bit each: a place that held values of
|
|
25
|
+
// several kinds is a union of them, and null and undefined decide presence.
|
|
26
|
+
const NULL = 1;
|
|
27
|
+
const UNDEF = 2;
|
|
28
|
+
const BOOLEAN = 4;
|
|
29
|
+
const INTEGER = 8;
|
|
30
|
+
const FLOAT = 16;
|
|
31
|
+
const BIGINT = 32;
|
|
32
|
+
const STRING = 64;
|
|
33
|
+
const DATE = 128;
|
|
34
|
+
const LIST = 256;
|
|
35
|
+
const SET = 512;
|
|
36
|
+
const MAP = 1024;
|
|
37
|
+
const RECORD = 2048;
|
|
38
|
+
// An empty dictionary or Map was seen: a required one rejects it.
|
|
39
|
+
const BLANK = 4096;
|
|
40
|
+
// A value no type describes but `any`: a function, a symbol, an invalid Date.
|
|
41
|
+
const ANY = 8192;
|
|
42
|
+
|
|
43
|
+
const PRESENCE = NULL | UNDEF;
|
|
44
|
+
|
|
45
|
+
// How a key is written: a field, its presence (absent, undefined or null
|
|
46
|
+
// among its values) written as the language writes it.
|
|
47
|
+
const REQUIRED = 0;
|
|
48
|
+
const OPTIONAL = 1;
|
|
49
|
+
const NULLABLE = 2;
|
|
50
|
+
|
|
51
|
+
// The summary of one place: one shape for every node. `strings` is the
|
|
52
|
+
// distinct strings while there are few enough for an enum (undefined before
|
|
53
|
+
// the first, null once there are too many), `texts` how many strings there
|
|
54
|
+
// were, `formats` the registered formats every string so far passed
|
|
55
|
+
// (undefined before the first, null once none is left), `records` how many
|
|
56
|
+
// of the values were records (the presence of a key is counted against it).
|
|
57
|
+
const node = () => ({
|
|
58
|
+
bits: 0,
|
|
59
|
+
count: 0,
|
|
60
|
+
records: 0,
|
|
61
|
+
texts: 0,
|
|
62
|
+
keys: null,
|
|
63
|
+
item: null,
|
|
64
|
+
names: null,
|
|
65
|
+
entries: null,
|
|
66
|
+
strings: undefined,
|
|
67
|
+
formats: undefined,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// A place in the samples, for the errors: the keys of records, `[]` for
|
|
71
|
+
// the elements of a list or the entries of a Map.
|
|
72
|
+
const ITEM = Symbol('item');
|
|
73
|
+
|
|
74
|
+
const where = (state) => {
|
|
75
|
+
let text = '';
|
|
76
|
+
for (let index = 0; index < state.path.length; index += 1) {
|
|
77
|
+
const key = state.path[index];
|
|
78
|
+
if (key === ITEM) text += '[]';
|
|
79
|
+
else if (IDENTIFIER.test(key)) text += text === '' ? shorten(key) : `.${shorten(key)}`;
|
|
80
|
+
else text += `[${JSON.stringify(shorten(key))}]`;
|
|
81
|
+
}
|
|
82
|
+
return text;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const tooDeep = (state) =>
|
|
86
|
+
invalid(
|
|
87
|
+
'ERR_INFER_DEPTH',
|
|
88
|
+
`Sample ${state.index} nests deeper than ${state.maxDepth} levels at "${where(state)}" (a cycle?)`,
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
// The formats of a place narrow with every string: the candidates are the
|
|
92
|
+
// registered formats that infer (a format every word passes says not to),
|
|
93
|
+
// in the order they were registered, and a string drops the ones it fails.
|
|
94
|
+
const addFormats = (target, value, state) => {
|
|
95
|
+
if (target.formats === null) return;
|
|
96
|
+
if (target.formats === undefined) target.formats = state.candidates.slice();
|
|
97
|
+
const list = target.formats;
|
|
98
|
+
let kept = 0;
|
|
99
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
100
|
+
const name = list[index];
|
|
101
|
+
if (FORMATS[name].test(value)) {
|
|
102
|
+
list[kept] = name;
|
|
103
|
+
kept += 1;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
list.length = kept;
|
|
107
|
+
if (kept === 0) target.formats = null;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const addString = (target, value, state) => {
|
|
111
|
+
target.texts += 1;
|
|
112
|
+
if (state.candidates.length > 0) addFormats(target, value, state);
|
|
113
|
+
if (target.strings === null) return;
|
|
114
|
+
if (target.strings === undefined) target.strings = new Set();
|
|
115
|
+
target.strings.add(value);
|
|
116
|
+
if (target.strings.size > state.enum) target.strings = null;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const childOf = (target, key) => {
|
|
120
|
+
if (target.keys === null) target.keys = new Map();
|
|
121
|
+
let child = target.keys.get(key);
|
|
122
|
+
if (child === undefined) {
|
|
123
|
+
child = node();
|
|
124
|
+
target.keys.set(key, child);
|
|
125
|
+
}
|
|
126
|
+
return child;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const addItems = (target, items, state, depth) => {
|
|
130
|
+
if (target.item === null) target.item = node();
|
|
131
|
+
state.path.push(ITEM);
|
|
132
|
+
for (const item of items) add(target.item, item, state, depth + 1);
|
|
133
|
+
state.path.pop();
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// One value into the summary of its place. The tests are the ones the
|
|
137
|
+
// check makes (a Date by its constructor name and a valid time, a Set and a
|
|
138
|
+
// 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
|
+
const add = (target, value, state, depth) => {
|
|
141
|
+
target.count += 1;
|
|
142
|
+
if (value === null) {
|
|
143
|
+
target.bits |= NULL;
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const type = typeof value;
|
|
147
|
+
if (type === 'string') {
|
|
148
|
+
target.bits |= STRING;
|
|
149
|
+
addString(target, value, state);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (type === 'number') {
|
|
153
|
+
target.bits |= Number.isInteger(value) ? INTEGER : FLOAT;
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (type === 'boolean') {
|
|
157
|
+
target.bits |= BOOLEAN;
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (type === 'undefined') {
|
|
161
|
+
target.bits |= UNDEF;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (type === 'bigint') {
|
|
165
|
+
target.bits |= BIGINT;
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (type !== 'object') {
|
|
169
|
+
target.bits |= ANY;
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (depth >= state.maxDepth) throw tooDeep(state);
|
|
173
|
+
const name = value.constructor?.name;
|
|
174
|
+
if (name === 'Date' && typeof value.getTime === 'function') {
|
|
175
|
+
target.bits |= Number.isNaN(value.getTime()) ? ANY : DATE;
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (Array.isArray(value)) {
|
|
179
|
+
target.bits |= LIST;
|
|
180
|
+
addItems(target, value, state, depth);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const iterable = typeof value[Symbol.iterator] === 'function';
|
|
184
|
+
if (name === 'Set' && iterable) {
|
|
185
|
+
target.bits |= SET;
|
|
186
|
+
addItems(target, value, state, depth);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (name === 'Map' && iterable) {
|
|
190
|
+
target.bits |= MAP;
|
|
191
|
+
if (value.size === 0) target.bits |= BLANK;
|
|
192
|
+
if (target.names === null) target.names = node();
|
|
193
|
+
if (target.entries === null) target.entries = node();
|
|
194
|
+
state.path.push(ITEM);
|
|
195
|
+
for (const pair of value) {
|
|
196
|
+
const key = typeof pair[0];
|
|
197
|
+
target.names.bits |= key === 'string' ? STRING : key === 'number' ? FLOAT : ANY;
|
|
198
|
+
add(target.entries, pair[1], state, depth + 1);
|
|
199
|
+
}
|
|
200
|
+
state.path.pop();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
target.bits |= RECORD;
|
|
204
|
+
target.records += 1;
|
|
205
|
+
const keys = Object.keys(value);
|
|
206
|
+
if (keys.length === 0) target.bits |= BLANK;
|
|
207
|
+
for (let index = 0; index < keys.length; index += 1) {
|
|
208
|
+
const key = keys[index];
|
|
209
|
+
state.path.push(key);
|
|
210
|
+
add(childOf(target, key), value[key], state, depth + 1);
|
|
211
|
+
state.path.pop();
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
// The summary of one node into another, copies of the nodes under it: what
|
|
216
|
+
// the values of a dictionary share.
|
|
217
|
+
const fuse = (into, from, cap) => {
|
|
218
|
+
into.bits |= from.bits;
|
|
219
|
+
into.count += from.count;
|
|
220
|
+
into.records += from.records;
|
|
221
|
+
into.texts += from.texts;
|
|
222
|
+
if (from.keys !== null) {
|
|
223
|
+
for (const pair of from.keys) fuse(childOf(into, pair[0]), pair[1], cap);
|
|
224
|
+
}
|
|
225
|
+
if (from.item !== null) into.item = fuse(into.item ?? node(), from.item, cap);
|
|
226
|
+
if (from.names !== null) into.names = fuse(into.names ?? node(), from.names, cap);
|
|
227
|
+
if (from.entries !== null) into.entries = fuse(into.entries ?? node(), from.entries, cap);
|
|
228
|
+
if (from.strings === null || into.strings === null) into.strings = null;
|
|
229
|
+
else if (from.strings !== undefined) {
|
|
230
|
+
if (into.strings === undefined) into.strings = new Set();
|
|
231
|
+
for (const text of from.strings) into.strings.add(text);
|
|
232
|
+
if (into.strings.size > cap) into.strings = null;
|
|
233
|
+
}
|
|
234
|
+
// The formats both kept, in the order of the target.
|
|
235
|
+
if (from.formats === null || into.formats === null) into.formats = null;
|
|
236
|
+
else if (into.formats === undefined) into.formats = from.formats?.slice();
|
|
237
|
+
else if (from.formats !== undefined) {
|
|
238
|
+
const kept = [];
|
|
239
|
+
for (const name of into.formats) if (from.formats.includes(name)) kept.push(name);
|
|
240
|
+
into.formats = kept.length === 0 ? null : kept;
|
|
241
|
+
}
|
|
242
|
+
return into;
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// A key a program would write as a field: a letter, a digit after it.
|
|
246
|
+
const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
|
247
|
+
|
|
248
|
+
// Whether the records of a place are a dictionary rather than a struct: no
|
|
249
|
+
// key is a name (ids, dates, codes as keys, from one sample on), or there
|
|
250
|
+
// are more keys than `map` across several records, every key is missing
|
|
251
|
+
// from some record and the values are all of one kind.
|
|
252
|
+
const dictionary = (target, state) => {
|
|
253
|
+
const { keys } = target;
|
|
254
|
+
if (state.map === false || keys === null || keys.size === 0) return false;
|
|
255
|
+
let named = false;
|
|
256
|
+
for (const key of keys.keys()) {
|
|
257
|
+
if (NAME.test(key)) {
|
|
258
|
+
named = true;
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (!named) return true;
|
|
263
|
+
if (keys.size <= state.map || target.records < 2) return false;
|
|
264
|
+
let kinds = 0;
|
|
265
|
+
for (const child of keys.values()) {
|
|
266
|
+
if (child.count >= target.records) return false;
|
|
267
|
+
const bits = child.bits & ~PRESENCE;
|
|
268
|
+
kinds |= bits & INTEGER ? (bits & ~INTEGER) | FLOAT : bits;
|
|
269
|
+
}
|
|
270
|
+
return kinds !== 0 && (kinds & (kinds - 1)) === 0;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// The definition of a form with its presence: a type name is `?name` or
|
|
274
|
+
// `{ type, nullable }`, an object form takes `required: false` or
|
|
275
|
+
// `nullable: true`, a struct is bare only where it reads as one.
|
|
276
|
+
const written = (form, presence) => {
|
|
277
|
+
const { struct } = form;
|
|
278
|
+
if (struct !== undefined) {
|
|
279
|
+
if (presence === REQUIRED) return readsAsStruct(struct) ? struct : { schema: struct };
|
|
280
|
+
if (presence === OPTIONAL) return { schema: struct, required: false };
|
|
281
|
+
return { schema: struct, nullable: true };
|
|
282
|
+
}
|
|
283
|
+
const { def } = form;
|
|
284
|
+
if (typeof def === 'string') {
|
|
285
|
+
if (presence === REQUIRED) return def;
|
|
286
|
+
return presence === OPTIONAL ? `?${def}` : { type: def, nullable: true };
|
|
287
|
+
}
|
|
288
|
+
if (presence === OPTIONAL) def.required = false;
|
|
289
|
+
else if (presence === NULLABLE) def.nullable = true;
|
|
290
|
+
return def;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// A place that held nothing but null or undefined.
|
|
294
|
+
const bareOf = (bits, absent) => (bits & NULL ? (absent ? '?null' : 'null') : '?unknown');
|
|
295
|
+
|
|
296
|
+
// The element of a list, the value of a dictionary: `?type` when null or
|
|
297
|
+
// undefined was among them.
|
|
298
|
+
const itemOf = (target, state) => {
|
|
299
|
+
if (target === null || target.count === 0) return 'unknown';
|
|
300
|
+
const { bits } = target;
|
|
301
|
+
if ((bits & ~PRESENCE) === 0) return bareOf(bits, (bits & UNDEF) !== 0);
|
|
302
|
+
return written(formOf(target, state), bits & PRESENCE ? OPTIONAL : REQUIRED);
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
// An enum of few recurring values, else the first registered format every
|
|
306
|
+
// string of the place passed, else a string.
|
|
307
|
+
const stringOf = (target, state) => {
|
|
308
|
+
const { strings, texts, formats } = target;
|
|
309
|
+
if (strings != null && texts >= 4 && texts >= 2 * strings.size) {
|
|
310
|
+
return { def: { enum: Array.from(strings) } };
|
|
311
|
+
}
|
|
312
|
+
if (formats != null && formats.length > 0) return { def: { type: 'string', format: formats[0] } };
|
|
313
|
+
return { def: 'string' };
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
const mapOf = (target, state) => {
|
|
317
|
+
const names = target.names === null ? 0 : target.names.bits;
|
|
318
|
+
let key = 'string';
|
|
319
|
+
if (names !== 0 && names !== STRING) {
|
|
320
|
+
if ((names & ~(INTEGER | FLOAT)) !== 0) return { def: 'json' };
|
|
321
|
+
key = 'number';
|
|
322
|
+
}
|
|
323
|
+
const def = { map: { [key]: itemOf(target.entries, state) } };
|
|
324
|
+
if (target.bits & BLANK) def.required = false;
|
|
325
|
+
return { def };
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
// A key of the data as a key of a definition: one ending in `?` would read
|
|
329
|
+
// as an optional key, so it is written with one more.
|
|
330
|
+
const nameOf = (key) => (key.endsWith('?') ? `${key}?` : key);
|
|
331
|
+
|
|
332
|
+
// A key of a struct: optional when some record lacks it or holds undefined,
|
|
333
|
+
// nullable when every record has it and some hold null.
|
|
334
|
+
const keyOf = (child, records, state) => {
|
|
335
|
+
const absent = child.count < records || (child.bits & UNDEF) !== 0;
|
|
336
|
+
const nul = (child.bits & NULL) !== 0;
|
|
337
|
+
if ((child.bits & ~PRESENCE) === 0) return bareOf(child.bits, absent);
|
|
338
|
+
return written(formOf(child, state), absent ? OPTIONAL : nul ? NULLABLE : REQUIRED);
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
const recordOf = (target, state) => {
|
|
342
|
+
if (dictionary(target, state)) {
|
|
343
|
+
const value = node();
|
|
344
|
+
for (const child of target.keys.values()) fuse(value, child, state.enum);
|
|
345
|
+
const def = { object: { string: itemOf(value, state) } };
|
|
346
|
+
if (target.bits & BLANK) def.required = false;
|
|
347
|
+
return { def };
|
|
348
|
+
}
|
|
349
|
+
const fields = {};
|
|
350
|
+
if (target.keys !== null) {
|
|
351
|
+
for (const pair of target.keys) {
|
|
352
|
+
define(fields, nameOf(pair[0]), keyOf(pair[1], target.records, state));
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return { struct: fields };
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
// The form of a place from the kinds it held: one, or a union of them in a
|
|
359
|
+
// fixed order with the record last, since a struct accepts any object that
|
|
360
|
+
// is not an array and the Set, Map and Date branches must be tried first.
|
|
361
|
+
const formOf = (target, state) => {
|
|
362
|
+
const bits = target.bits & ~PRESENCE;
|
|
363
|
+
if (bits & ANY) return { def: 'any' };
|
|
364
|
+
const forms = [];
|
|
365
|
+
if (bits & BOOLEAN) forms.push({ def: 'boolean' });
|
|
366
|
+
if (bits & (INTEGER | FLOAT)) {
|
|
367
|
+
forms.push({ def: (bits & FLOAT) === 0 && state.integer ? 'integer' : 'number' });
|
|
368
|
+
}
|
|
369
|
+
if (bits & BIGINT) forms.push({ def: 'bigint' });
|
|
370
|
+
if (bits & STRING) forms.push(stringOf(target, state));
|
|
371
|
+
if (bits & DATE) forms.push({ def: 'date' });
|
|
372
|
+
if (bits & LIST) forms.push({ def: { array: itemOf(target.item, state) } });
|
|
373
|
+
if (bits & SET) forms.push({ def: { set: itemOf(target.item, state) } });
|
|
374
|
+
if (bits & MAP) forms.push(mapOf(target, state));
|
|
375
|
+
if (bits & RECORD) forms.push(recordOf(target, state));
|
|
376
|
+
if (forms.length === 0) return { def: 'unknown' };
|
|
377
|
+
if (forms.length === 1) return forms[0];
|
|
378
|
+
const union = [];
|
|
379
|
+
for (let index = 0; index < forms.length; index += 1) union.push(written(forms[index], REQUIRED));
|
|
380
|
+
return { def: { union } };
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
const mismatch = (state, index, issue) => {
|
|
384
|
+
finalize([issue], en);
|
|
385
|
+
const at = toDotPath(issue.path, state.name);
|
|
386
|
+
const error = invalid(
|
|
387
|
+
'ERR_INFER_MISMATCH',
|
|
388
|
+
`The inferred definition rejects sample ${index} at "${at}": ${issue.message}`,
|
|
389
|
+
);
|
|
390
|
+
error.index = index;
|
|
391
|
+
return error;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const option = (name, expected) => invalidOptions(`Infer option "${name}" must be ${expected}`);
|
|
395
|
+
|
|
396
|
+
const optionsOf = (options) => {
|
|
397
|
+
if (options === null || typeof options !== 'object') {
|
|
398
|
+
throw invalidOptions('Infer options must be an object');
|
|
399
|
+
}
|
|
400
|
+
const {
|
|
401
|
+
as = 'definition',
|
|
402
|
+
name = '',
|
|
403
|
+
kind = 'struct',
|
|
404
|
+
enum: cap = 8,
|
|
405
|
+
integer = true,
|
|
406
|
+
map = 16,
|
|
407
|
+
maxDepth = DEPTH,
|
|
408
|
+
formats = true,
|
|
409
|
+
} = options;
|
|
410
|
+
if (as !== 'definition' && as !== 'schema') throw option('as', '"definition" or "schema"');
|
|
411
|
+
if (typeof name !== 'string') throw option('name', 'a string');
|
|
412
|
+
if (typeof kind !== 'string' || kind === '') throw option('kind', 'the name of a kind');
|
|
413
|
+
if (cap !== false && (!Number.isInteger(cap) || cap < 0)) {
|
|
414
|
+
throw option('enum', 'an integer of at least 0, or false');
|
|
415
|
+
}
|
|
416
|
+
if (typeof integer !== 'boolean') throw option('integer', 'a boolean');
|
|
417
|
+
if (map !== false && (!Number.isInteger(map) || map < 1)) {
|
|
418
|
+
throw option('map', 'an integer of at least 1, or false');
|
|
419
|
+
}
|
|
420
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > DEPTH) {
|
|
421
|
+
throw option('maxDepth', `an integer from 1 to ${DEPTH}`);
|
|
422
|
+
}
|
|
423
|
+
if (typeof formats !== 'boolean') throw option('formats', 'a boolean');
|
|
424
|
+
const state = { as, name, kind, enum: cap === false ? 0 : cap, integer, map, maxDepth };
|
|
425
|
+
state.path = [];
|
|
426
|
+
state.index = 0;
|
|
427
|
+
// The formats a string place may be, in the order they were registered.
|
|
428
|
+
state.candidates = [];
|
|
429
|
+
if (formats) {
|
|
430
|
+
for (const key in FORMATS) if (FORMATS[key].infer !== false) state.candidates.push(key);
|
|
431
|
+
}
|
|
432
|
+
return state;
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
// The samples as a list, read twice (the summary, then the self-check). A
|
|
436
|
+
// string is iterable, over its characters, and surely a mistake.
|
|
437
|
+
const listOf = (samples) => {
|
|
438
|
+
const iterable =
|
|
439
|
+
samples !== null &&
|
|
440
|
+
samples !== undefined &&
|
|
441
|
+
typeof samples !== 'string' &&
|
|
442
|
+
typeof samples[Symbol.iterator] === 'function';
|
|
443
|
+
if (!iterable) throw invalidTarget('An iterable of samples is expected');
|
|
444
|
+
const list = Array.isArray(samples) ? samples : Array.from(samples);
|
|
445
|
+
if (list.length === 0) throw invalidTarget('At least one sample is expected');
|
|
446
|
+
return list;
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
// A definition (or a Schema, with `as: 'schema'`) that accepts every
|
|
450
|
+
// sample. `options`: `as`, `name`, `kind` (the kind of a root that is a
|
|
451
|
+
// struct, 'struct'), `enum` (the most distinct strings of a place for an
|
|
452
|
+
// enum, 8), `integer` (whole numbers are `integer`, true), `map` (the keys
|
|
453
|
+
// past which records read as a dictionary, 16), `maxDepth` (128).
|
|
454
|
+
const infer = (samples, options = {}) => {
|
|
455
|
+
const state = optionsOf(options);
|
|
456
|
+
const list = listOf(samples);
|
|
457
|
+
const root = node();
|
|
458
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
459
|
+
state.index = index;
|
|
460
|
+
add(root, list[index], state, 0);
|
|
461
|
+
}
|
|
462
|
+
// A root of records is a struct with its kind; a root of records and
|
|
463
|
+
// null or undefined is a union of that one struct, since the `schema`
|
|
464
|
+
// shorthand at the root is the struct itself and cannot be optional.
|
|
465
|
+
let definition;
|
|
466
|
+
const presence = root.bits & PRESENCE ? OPTIONAL : REQUIRED;
|
|
467
|
+
const form = (root.bits & ~PRESENCE) === 0 ? null : formOf(root, state);
|
|
468
|
+
if (form === null) definition = bareOf(root.bits, (root.bits & UNDEF) !== 0);
|
|
469
|
+
else if (form.struct === undefined) definition = written(form, presence);
|
|
470
|
+
else if (presence === REQUIRED) {
|
|
471
|
+
definition = { [capitalize(state.kind)]: {} };
|
|
472
|
+
for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
|
|
473
|
+
} else definition = written({ def: { union: [written(form, REQUIRED)] } }, presence);
|
|
474
|
+
const schema = new Schema(state.name, definition);
|
|
475
|
+
const check = { unknown: 'reject', maxErrors: 1 };
|
|
476
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
477
|
+
const result = schema.check(list[index], check);
|
|
478
|
+
if (!result.valid) throw mismatch(state, index, result.issues[0]);
|
|
479
|
+
}
|
|
480
|
+
return state.as === 'schema' ? schema : definition;
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
module.exports = { infer };
|
package/src/model/merge.js
CHANGED
|
@@ -9,7 +9,14 @@ 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 {
|
|
12
|
+
const {
|
|
13
|
+
same,
|
|
14
|
+
definitionOf,
|
|
15
|
+
structDefinitionOf,
|
|
16
|
+
metadataOf,
|
|
17
|
+
structDefinition,
|
|
18
|
+
atSchema,
|
|
19
|
+
} = require('./data.js');
|
|
13
20
|
|
|
14
21
|
// The keys a field definition settles by a rule of its own; every other key
|
|
15
22
|
// (an annotation, an option of a custom type) comes from the first schema.
|
|
@@ -108,6 +115,7 @@ const mergeKey = (key, a, b, path) => {
|
|
|
108
115
|
}
|
|
109
116
|
return Array.isArray(a) ? mergeList(a, b, path) : mergeFields(a, b, `${path}[]`);
|
|
110
117
|
case 'pattern':
|
|
118
|
+
case 'format':
|
|
111
119
|
case 'default':
|
|
112
120
|
case 'parse':
|
|
113
121
|
case 'serialize':
|
|
@@ -215,12 +223,8 @@ const merge = (a, b, options = {}) => {
|
|
|
215
223
|
namespaces,
|
|
216
224
|
);
|
|
217
225
|
}
|
|
218
|
-
const { kind, scope, store, allow, unknown, custom } = a;
|
|
219
|
-
const meta = { scope, store, allow, unknown, ...custom, ...metadata };
|
|
220
|
-
const { kind: given = kind, ...rest } = meta;
|
|
221
|
-
const definition = { [capitalize(given)]: rest };
|
|
222
226
|
const fields = mergeStruct(structDefinitionOf(a.fields), structDefinitionOf(b.fields), '');
|
|
223
|
-
|
|
227
|
+
const definition = structDefinition(metadataOf(a), metadata, fields);
|
|
224
228
|
for (const source of [a, b]) {
|
|
225
229
|
for (const key in source.indexes) {
|
|
226
230
|
const index = source.indexes[key];
|
package/src/model/restore.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// is read (a tag that does not read, a nesting deeper than DEPTH, an index
|
|
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
|
-
const { define } = require('../util.js');
|
|
13
|
+
const { define, shorten } = require('../util.js');
|
|
14
14
|
const { Schema } = require('../schema.js');
|
|
15
15
|
const { Model } = require('../model.js');
|
|
16
16
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
@@ -102,7 +102,7 @@ const structDef = (fields, at, depth, context) => {
|
|
|
102
102
|
const out = {};
|
|
103
103
|
for (const key of Object.keys(fields)) {
|
|
104
104
|
const item = fields[key];
|
|
105
|
-
const where = `${at}.${key}`;
|
|
105
|
+
const where = `${at}.${shorten(key)}`;
|
|
106
106
|
const def = isFunctionMarker(item)
|
|
107
107
|
? placeholderOf(key, where, context)
|
|
108
108
|
: fieldDef(item, where, depth, context);
|
|
@@ -132,7 +132,7 @@ const entityDef = (name, entity, context) => {
|
|
|
132
132
|
const struct = structDef(fields, name, 0, context);
|
|
133
133
|
for (const key of Object.keys(struct)) define(def, key, struct[key]);
|
|
134
134
|
for (const key of Object.keys(indexes ?? {})) {
|
|
135
|
-
context.at = `${name}.${key}`;
|
|
135
|
+
context.at = `${name}.${shorten(key)}`;
|
|
136
136
|
if (Object.hasOwn(fields, key)) throw invalidSnapshot('An index is named like a field');
|
|
137
137
|
define(def, key, revive(indexes[key], key, context.at, 0, context));
|
|
138
138
|
}
|
package/src/model/sample.js
CHANGED
|
@@ -4,15 +4,17 @@
|
|
|
4
4
|
// built and drawn again when it fails (a pattern a length rule contradicts,
|
|
5
5
|
// a validate function), and a field no draw satisfies is an error: a
|
|
6
6
|
// definition that no value can satisfy is found here, not in production
|
|
7
|
-
// (witness generation as a satisfiability check
|
|
7
|
+
// (witness generation as a satisfiability check).
|
|
8
8
|
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');
|
|
15
16
|
const { int, pick, patternOf, fromPattern } = require('./pattern.js');
|
|
17
|
+
const { FORMATS } = require('../rules.js');
|
|
16
18
|
|
|
17
19
|
const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
|
|
18
20
|
|
|
@@ -47,9 +49,7 @@ const ABSENT = Symbol('absent');
|
|
|
47
49
|
// The built-in type a field validates as: its own, or the one its alias
|
|
48
50
|
// chain ends in; a custom type with a check of its own has none.
|
|
49
51
|
const baseOf = (field) => {
|
|
50
|
-
const
|
|
51
|
-
let Type = field.constructor;
|
|
52
|
-
while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
|
|
52
|
+
const Type = baseTypeOf(field);
|
|
53
53
|
return Type.source === undefined ? Type.type : null;
|
|
54
54
|
};
|
|
55
55
|
|
|
@@ -70,7 +70,10 @@ const lettersOf = (state, count) => {
|
|
|
70
70
|
// pattern whose shortest string is over `length.max` is unsatisfiable before
|
|
71
71
|
// a string is built.
|
|
72
72
|
const stringOf = (state, field, key) => {
|
|
73
|
-
const { pattern, length } = field;
|
|
73
|
+
const { pattern, length, format } = field;
|
|
74
|
+
// A format draws one of the examples it was registered with; the check of
|
|
75
|
+
// the field decides whether its other rules accept it.
|
|
76
|
+
if (format !== undefined) return pick(state, FORMATS[format].examples);
|
|
74
77
|
if (pattern !== undefined) {
|
|
75
78
|
const { node, minLength } = patternOf(pattern);
|
|
76
79
|
const max = length?.max;
|
package/src/model.js
CHANGED
|
@@ -1,21 +1,46 @@
|
|
|
1
|
-
const { firstKey } = require('./metautil.js');
|
|
1
|
+
const { firstKey, isFirstLower } = require('./metautil.js');
|
|
2
2
|
|
|
3
|
-
const { BRAND } = require('./util.js');
|
|
3
|
+
const { BRAND, INSPECT } = require('./util.js');
|
|
4
4
|
const { Schema } = require('./schema.js');
|
|
5
5
|
const { TYPES, createRegistry, typeFactory } = require('./types.js');
|
|
6
6
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
7
7
|
const { warning } = require('./lint.js');
|
|
8
8
|
const { snapshotOf } = require('./snapshot.js');
|
|
9
9
|
|
|
10
|
+
const invalidOption = (name, expected, value) => {
|
|
11
|
+
const reason = `Model option "${name}" must be ${expected}, got ${JSON.stringify(value)}`;
|
|
12
|
+
return new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
13
|
+
};
|
|
14
|
+
|
|
10
15
|
const registryFor = (options) => {
|
|
11
16
|
const { registry = 'shared' } = options;
|
|
12
17
|
if (registry !== 'shared' && registry !== 'isolated') {
|
|
13
|
-
|
|
14
|
-
throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
18
|
+
throw invalidOption('registry', '"shared" or "isolated"', registry);
|
|
15
19
|
}
|
|
16
20
|
return registry === 'isolated' ? createRegistry() : TYPES;
|
|
17
21
|
};
|
|
18
22
|
|
|
23
|
+
// The converters of coercion the model gives for its own type names, read
|
|
24
|
+
// by the `./coerce` subpath before the process-wide table for the fields
|
|
25
|
+
// of its entities (and of a schema that attaches the model): what an
|
|
26
|
+
// isolated registry is to the types. Frozen, with no prototype.
|
|
27
|
+
const coercionsFor = (options) => {
|
|
28
|
+
const { coercions = null } = options;
|
|
29
|
+
if (coercions === null) return null;
|
|
30
|
+
const expected = 'an object of functions by type name';
|
|
31
|
+
if (typeof coercions !== 'object' || Array.isArray(coercions)) {
|
|
32
|
+
throw invalidOption('coercions', expected, coercions);
|
|
33
|
+
}
|
|
34
|
+
const table = Object.create(null);
|
|
35
|
+
for (const name of Object.keys(coercions)) {
|
|
36
|
+
if (!isFirstLower(name) || typeof coercions[name] !== 'function') {
|
|
37
|
+
throw invalidOption('coercions', expected, name);
|
|
38
|
+
}
|
|
39
|
+
table[name] = coercions[name];
|
|
40
|
+
}
|
|
41
|
+
return Object.freeze(table);
|
|
42
|
+
};
|
|
43
|
+
|
|
19
44
|
class Model {
|
|
20
45
|
// The model's own warnings (the cycles met while ordering), found while
|
|
21
46
|
// building; the rest comes from the entities on first use.
|
|
@@ -24,6 +49,7 @@ class Model {
|
|
|
24
49
|
|
|
25
50
|
constructor(types, entities, database = null, options = {}) {
|
|
26
51
|
this.types = typeFactory(types, registryFor(options));
|
|
52
|
+
this.coercions = coercionsFor(options);
|
|
27
53
|
this.entities = new Map();
|
|
28
54
|
this.database = database;
|
|
29
55
|
this.order = new Set();
|
|
@@ -75,6 +101,10 @@ class Model {
|
|
|
75
101
|
return snapshotOf(this);
|
|
76
102
|
}
|
|
77
103
|
|
|
104
|
+
[INSPECT](depth, options, inspect) {
|
|
105
|
+
return `Model ${inspect(this.toJSON(), options)}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
78
108
|
#preprocess() {
|
|
79
109
|
const { entities, order } = this;
|
|
80
110
|
if (entities.has('Identifier')) order.add('Identifier');
|