@alexify/metaschema 3.1.0 → 3.2.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.
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  Compatibility,
3
3
  Infer,
4
+ InferOptions,
4
5
  MergeOptions,
5
6
  Model,
6
7
  ModelSnapshot,
@@ -50,7 +51,18 @@ export function sample<D extends string | object>(
50
51
  // and the name are the first schema's unless the options say otherwise.
51
52
  export function merge(a: Schema, b: Schema, options?: MergeOptions): Schema;
52
53
 
54
+ // A definition (or a Schema, with `as: 'schema'`) that accepts every sample:
55
+ // the kinds seen at every place, the records of a place fused into one
56
+ // struct with optional keys, a string field of few values as an enum,
57
+ // records of many sparse keys as a dictionary, whole numbers as `integer`.
58
+ // The samples are input: the walk is bounded (`ERR_INFER_DEPTH`), and the
59
+ // definition is checked against every sample before it is returned
60
+ // (`ERR_INFER_MISMATCH` is a bug to report). An argument that is not a
61
+ // non-empty iterable is a `TypeError` with the code `ERR_INVALID_TARGET`.
62
+ export function infer(samples: Iterable<unknown>, options: InferOptions & { as: 'schema' }): Schema;
63
+ export function infer(samples: Iterable<unknown>, options?: InferOptions): object | string;
64
+
53
65
  // Installs `Model.fromJSON`, `Model.diff`, `Model.compatibility`,
54
- // `Model.compatibilityOf`, `Schema.merge` and `schema.sample`. Once per
55
- // process; later calls do nothing.
66
+ // `Model.compatibilityOf`, `Schema.merge`, `Schema.infer` and
67
+ // `schema.sample`. Once per process; later calls do nothing.
56
68
  export function register(): void;
@@ -1,19 +1,22 @@
1
1
  // The `./model` subpath: the model as the source of truth. A model restored
2
2
  // from its snapshot (`fromJSON`), the changes between two versions and their
3
3
  // compatibility class (`diff`, `compatibility`, `compatibilityOf`), a value
4
- // a schema accepts (`sample`), two schemas as one (`merge`), kept out of
5
- // the core entry so
6
- // that a program that only validates does not carry them. The functions take
7
- // Models, Schemas or snapshots; `register()` installs them as members of the
8
- // classes for the programs that want the methods.
4
+ // a schema accepts (`sample`), two schemas as one (`merge`), a definition
5
+ // from the values that exist (`infer`), kept out of the core entry so that a
6
+ // program that only validates does not carry them. The functions take
7
+ // Models, Schemas, snapshots or samples; `register()` installs them as
8
+ // members of the classes for the programs that want the methods.
9
9
  const { Schema } = require('../schema.js');
10
10
  const { Model } = require('../model.js');
11
11
  const { fromJSON } = require('./restore.js');
12
12
  const { diff, compatibility, compatibilityOf } = require('./diff.js');
13
13
  const { sample } = require('./sample.js');
14
14
  const { merge } = require('./merge.js');
15
+ const { infer } = require('./infer.js');
15
16
 
16
- // Installed like class members: not enumerable.
17
+ // Installed like class members: not enumerable. A copy per subpath rather
18
+ // than a helper of the core: the core is measured on its own, the subpaths
19
+ // on top of it.
17
20
  const install = (target, members) => {
18
21
  const descriptors = Object.getOwnPropertyDescriptors(members);
19
22
  for (const name in descriptors) {
@@ -25,13 +28,13 @@ const install = (target, members) => {
25
28
  let registered = false;
26
29
 
27
30
  // Adds `Model.fromJSON`, `Model.diff`, `Model.compatibility` and
28
- // `Model.compatibilityOf`, `Schema.merge` and `schema.sample(options)`.
29
- // Once per process.
31
+ // `Model.compatibilityOf`, `Schema.merge`, `Schema.infer` and
32
+ // `schema.sample(options)`. Once per process.
30
33
  const register = () => {
31
34
  if (registered) return;
32
35
  registered = true;
33
36
  install(Model, { fromJSON, diff, compatibility, compatibilityOf });
34
- install(Schema, { merge });
37
+ install(Schema, { merge, infer });
35
38
  install(Schema.prototype, {
36
39
  sample(options) {
37
40
  return sample(this, options);
@@ -39,4 +42,4 @@ const register = () => {
39
42
  });
40
43
  };
41
44
 
42
- module.exports = { fromJSON, diff, compatibility, compatibilityOf, sample, merge, register };
45
+ module.exports = { fromJSON, diff, compatibility, compatibilityOf, sample, merge, infer, register };
@@ -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 };
@@ -108,6 +108,7 @@ const mergeKey = (key, a, b, path) => {
108
108
  }
109
109
  return Array.isArray(a) ? mergeList(a, b, path) : mergeFields(a, b, `${path}[]`);
110
110
  case 'pattern':
111
+ case 'format':
111
112
  case 'default':
112
113
  case 'parse':
113
114
  case 'serialize':
@@ -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
  }
@@ -4,7 +4,7 @@
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, ROADMAP §3).
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');
@@ -13,6 +13,7 @@ const { embeds } = require('../prototypes/reference.js');
13
13
  const { toDotPath, finalize } = require('../issues.js');
14
14
  const en = require('../locales/en.js');
15
15
  const { int, pick, patternOf, fromPattern } = require('./pattern.js');
16
+ const { FORMATS } = require('../rules.js');
16
17
 
17
18
  const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
18
19
 
@@ -70,7 +71,10 @@ const lettersOf = (state, count) => {
70
71
  // pattern whose shortest string is over `length.max` is unsatisfiable before
71
72
  // a string is built.
72
73
  const stringOf = (state, field, key) => {
73
- const { pattern, length } = field;
74
+ const { pattern, length, format } = field;
75
+ // A format draws one of the examples it was registered with; the check of
76
+ // the field decides whether its other rules accept it.
77
+ if (format !== undefined) return pick(state, FORMATS[format].examples);
74
78
  if (pattern !== undefined) {
75
79
  const { node, minLength } = patternOf(pattern);
76
80
  const max = length?.max;
package/src/model.js CHANGED
@@ -1,6 +1,6 @@
1
1
  const { firstKey } = 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');
@@ -75,6 +75,10 @@ class Model {
75
75
  return snapshotOf(this);
76
76
  }
77
77
 
78
+ [INSPECT](depth, options, inspect) {
79
+ return `Model ${inspect(this.toJSON(), options)}`;
80
+ }
81
+
78
82
  #preprocess() {
79
83
  const { entities, order } = this;
80
84
  if (entities.has('Identifier')) order.add('Identifier');
@@ -90,6 +90,7 @@ class Preprocessor {
90
90
  }
91
91
 
92
92
  typeShorthand(source, first) {
93
+ if (first === undefined) return null;
93
94
  const { types } = this;
94
95
  const parsed = formatters.key(first, source.required);
95
96
  const type = parsed.field;