@alexify/metaschema 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
1
+ // A model from a snapshot (`fromJSON`): the structure, the rules and the
2
+ // metadata come back as they were written; a function has no body in JSON,
3
+ // so a placeholder stands in for it (a validate that passes, a decoder, a
4
+ // serializer and a format that return the value, a default factory and a
5
+ // calculated field that give nothing, a custom type whose check accepts
6
+ // everything and every rule). The model validates the structure, then;
7
+ // `options.types` brings the real custom types where the model should
8
+ // validate as the original did, and `model.placeholders` lists the paths
9
+ // the placeholders stand at. The snapshot is input: whatever fails while it
10
+ // is read (a tag that does not read, a nesting deeper than DEPTH, an index
11
+ // named like a field) is ERR_INVALID_SNAPSHOT located where the walk was,
12
+ // and the kind metadata it declares is never loosened by its `custom` keys.
13
+ const { define } = require('../util.js');
14
+ const { Schema } = require('../schema.js');
15
+ const { Model } = require('../model.js');
16
+ const { SchemaDefinitionError } = require('../errors.js');
17
+ const {
18
+ DEPTH,
19
+ tooDeep,
20
+ invalidSnapshot,
21
+ atSchema,
22
+ isObject,
23
+ isSnapshot,
24
+ isFunctionMarker,
25
+ capitalize,
26
+ } = require('./data.js');
27
+
28
+ const nothing = () => undefined;
29
+ const identity = (value) => value;
30
+
31
+ // What stands in for a function, by the key it is under; `at` is the path
32
+ // the model lists it under (once: a nested struct's validate is written as
33
+ // the field's key and among the struct's fields).
34
+ const placeholderOf = (key, at, context) => {
35
+ context.placeholders.add(at);
36
+ return key === 'parse' || key === 'serialize' || key === 'format' ? identity : nothing;
37
+ };
38
+
39
+ // A value of a snapshot as a value of a definition: the tags revived (a
40
+ // bigint that does not read throws its own error, a date is checked), a
41
+ // function marker as the placeholder of its key. `at` is the path of the
42
+ // value (`context.at` while it is read) and `depth` its nesting, which
43
+ // stops at DEPTH.
44
+ const revive = (value, key, at, depth, context) => {
45
+ context.at = at;
46
+ if (depth > DEPTH) throw tooDeep();
47
+ if (Array.isArray(value)) {
48
+ const list = [];
49
+ for (const item of value) list.push(revive(item, key, at, depth + 1, context));
50
+ return list;
51
+ }
52
+ if (!isObject(value)) return value;
53
+ if (value.$function === true) return placeholderOf(key, at, context);
54
+ if (typeof value.$bigint === 'string') return BigInt(value.$bigint);
55
+ if (typeof value.$date === 'string') {
56
+ const date = new Date(value.$date);
57
+ if (Number.isNaN(+date)) throw invalidSnapshot(`${JSON.stringify(value.$date)} is not a date`);
58
+ return date;
59
+ }
60
+ const out = {};
61
+ for (const name of Object.keys(value)) {
62
+ define(out, name, revive(value[name], name, `${at}.${name}`, depth + 1, context));
63
+ }
64
+ return out;
65
+ };
66
+
67
+ const isField = (value) => isObject(value) && typeof value.type === 'string';
68
+
69
+ // A field of a snapshot as a definition: `type` first, a pattern with flags
70
+ // as a RegExp (it needs a source), a nested struct, an element or the
71
+ // branches as definitions, a schema of one type held by a field as a Schema
72
+ // instance (the one form the schema type takes it in).
73
+ const fieldDef = (def, at, depth, context) => {
74
+ context.at = at;
75
+ if (depth > DEPTH) throw tooDeep();
76
+ if (!isField(def)) throw invalidSnapshot('A field of a snapshot needs a type');
77
+ const out = { type: def.type };
78
+ for (const key of Object.keys(def)) {
79
+ const item = def[key];
80
+ context.at = at;
81
+ if (key === 'type') continue;
82
+ if (key === 'pattern' && isObject(item)) {
83
+ if (typeof item.source !== 'string') throw invalidSnapshot('A pattern needs a string source');
84
+ out.pattern = new RegExp(item.source, item.flags);
85
+ } else if (key === 'schema' && isObject(item)) {
86
+ out.schema = isField(item)
87
+ ? Schema.from(fieldDef(item, at, depth + 1, context))
88
+ : structDef(item, at, depth + 1, context);
89
+ } else if ((key === 'value' || key === 'union') && Array.isArray(item)) {
90
+ const list = [];
91
+ for (const part of item) list.push(fieldDef(part, at, depth + 1, context));
92
+ out[key] = list;
93
+ } else if (key === 'value') out.value = fieldDef(item, at, depth + 1, context);
94
+ else define(out, key, revive(item, key, `${at}.${key}`, depth, context));
95
+ }
96
+ return out;
97
+ };
98
+
99
+ // The fields of a struct: a function marker is a calculated field or one of
100
+ // the functions of the struct, by its key.
101
+ const structDef = (fields, at, depth, context) => {
102
+ const out = {};
103
+ for (const key of Object.keys(fields)) {
104
+ const item = fields[key];
105
+ const where = `${at}.${key}`;
106
+ const def = isFunctionMarker(item)
107
+ ? placeholderOf(key, where, context)
108
+ : fieldDef(item, where, depth, context);
109
+ define(out, key, def);
110
+ }
111
+ return out;
112
+ };
113
+
114
+ // An entity as a definition: its kind as the first key with the metadata,
115
+ // then its fields and its indexes; a schema of one type is that type.
116
+ const entityDef = (name, entity, context) => {
117
+ context.at = name;
118
+ if (!isObject(entity) || typeof entity.kind !== 'string') {
119
+ throw invalidSnapshot('An entity of a snapshot needs a kind');
120
+ }
121
+ const { scope, store, allow, unknown, custom, fields, indexes } = entity;
122
+ if (fields === undefined) return fieldDef(entity.type, name, 0, context);
123
+ for (const key of ['fields', 'custom', 'indexes']) {
124
+ if (entity[key] !== undefined && !isObject(entity[key])) {
125
+ throw invalidSnapshot(`The ${key} of an entity must be an object`);
126
+ }
127
+ }
128
+ // The keys of the kind win over `custom`: a snapshot does not loosen
129
+ // `unknown` through its metadata.
130
+ const revived = revive(custom, 'custom', `${name}.custom`, 0, context);
131
+ const def = { [capitalize(entity.kind)]: { ...revived, scope, store, allow, unknown } };
132
+ const struct = structDef(fields, name, 0, context);
133
+ for (const key of Object.keys(struct)) define(def, key, struct[key]);
134
+ for (const key of Object.keys(indexes ?? {})) {
135
+ context.at = `${name}.${key}`;
136
+ if (Object.hasOwn(fields, key)) throw invalidSnapshot('An index is named like a field');
137
+ define(def, key, revive(indexes[key], key, context.at, 0, context));
138
+ }
139
+ return def;
140
+ };
141
+
142
+ // A type as an entry of the table Model takes: an alias, or a placeholder
143
+ // for a type with a check of its own, unless `options.types` brings the
144
+ // real one. A shared registry takes no placeholder: it would stand for the
145
+ // type in every schema of the process.
146
+ const typeDef = (name, entry, context) => {
147
+ context.at = `types.${name}`;
148
+ if (!isObject(entry)) throw invalidSnapshot('A type of a snapshot needs an object');
149
+ const out = {};
150
+ if (entry.js !== undefined) out.js = entry.js;
151
+ else if (entry.check === true && !Object.hasOwn(context.given, name)) {
152
+ if (context.shared) {
153
+ throw invalidSnapshot(
154
+ `Type "${name}" of the snapshot needs options.types or an isolated registry`,
155
+ );
156
+ }
157
+ if (entry.kind !== undefined) out.kind = entry.kind;
158
+ out.rules = ['length', 'min', 'max', 'pattern'];
159
+ out.construct = nothing;
160
+ out.checkType = nothing;
161
+ context.placeholders.add(`${context.at}.checkType`);
162
+ }
163
+ if (entry.metadata !== undefined) {
164
+ out.metadata = revive(entry.metadata, 'metadata', `${context.at}.metadata`, 0, context);
165
+ }
166
+ return out;
167
+ };
168
+
169
+ // The types in an order the registry accepts: an alias after the type it
170
+ // aliases, down a chain no longer than DEPTH.
171
+ const typesDef = (given, context) => {
172
+ const out = {};
173
+ const seen = new Set();
174
+ const add = (name, depth) => {
175
+ if (seen.has(name)) return;
176
+ if (depth > DEPTH) throw tooDeep();
177
+ seen.add(name);
178
+ const entry = given[name];
179
+ if (isObject(entry) && typeof entry.js === 'string' && Object.hasOwn(given, entry.js)) {
180
+ add(entry.js, depth + 1);
181
+ }
182
+ define(out, name, typeDef(name, entry, context));
183
+ };
184
+ for (const name of Object.keys(given)) add(name, 0);
185
+ return out;
186
+ };
187
+
188
+ // The model of a snapshot. `options.types` are entries of the table Model
189
+ // takes, over the ones of the snapshot (the real custom types); the
190
+ // registry is 'isolated' unless `options.registry` says otherwise, so the
191
+ // placeholders never reach the shared one. The model lists the paths of its
192
+ // placeholders, invisibly to `toJSON`.
193
+ const fromJSON = (snapshot, options = {}) => {
194
+ if (!isSnapshot(snapshot)) {
195
+ throw invalidSnapshot('A snapshot of format 1 with entities is expected');
196
+ }
197
+ if (!isObject(options)) {
198
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Restore options must be an object');
199
+ }
200
+ const { registry = 'isolated', types: given = {} } = options;
201
+ const context = { name: 'types', at: 'types', given, shared: registry === 'shared' };
202
+ context.placeholders = new Set();
203
+ const entities = [];
204
+ let types;
205
+ try {
206
+ types = typesDef(snapshot.types ?? {}, context);
207
+ for (const name of Object.keys(snapshot.entities)) {
208
+ context.name = name;
209
+ entities.push([name, entityDef(name, snapshot.entities[name], context)]);
210
+ }
211
+ } catch (error) {
212
+ // Whatever fails while the snapshot is read is an error of the snapshot
213
+ // (a bigint or a pattern that does not read throws its own), located in
214
+ // the entity at the path the walk was on, as a struct locates a
215
+ // definition error.
216
+ const located = error instanceof SchemaDefinitionError ? error : invalidSnapshot(error.message);
217
+ const field = context.at.slice(context.name.length + 1);
218
+ throw field ? located.locate(context.name, field) : atSchema(located, context.name);
219
+ }
220
+ Object.assign(types, given);
221
+ const model = new Model(types, entities, snapshot.database ?? null, { registry });
222
+ Object.defineProperty(model, 'placeholders', { value: Array.from(context.placeholders) });
223
+ return model;
224
+ };
225
+
226
+ module.exports = { fromJSON };
@@ -0,0 +1,394 @@
1
+ // A witness of a schema (`sample`): a value that `check` accepts, built from
2
+ // the definition with a seeded generator, so the same seed gives the same
3
+ // value on every run. Every field is verified with its own check as it is
4
+ // built and drawn again when it fails (a pattern a length rule contradicts,
5
+ // a validate function), and a field no draw satisfies is an error: a
6
+ // definition that no value can satisfy is found here, not in production
7
+ // (witness generation as a satisfiability check, ROADMAP §3).
8
+ const { hasBrand, define } = require('../util.js');
9
+ const { createContext } = require('../context.js');
10
+ const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
11
+ const { isStruct } = require('../struct.js');
12
+ const { embeds } = require('../prototypes/reference.js');
13
+ const { toDotPath, finalize } = require('../issues.js');
14
+ const en = require('../locales/en.js');
15
+ const { int, pick, patternOf, fromPattern } = require('./pattern.js');
16
+
17
+ const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
18
+
19
+ const invalidOptions = (reason) => invalid('ERR_INVALID_OPTIONS', reason);
20
+
21
+ // mulberry32: a 32-bit generator, the same numbers for a seed everywhere.
22
+ const prng = (seed) => {
23
+ let state = seed | 0;
24
+ return () => {
25
+ state = (state + 0x6d2b79f5) | 0;
26
+ let t = Math.imul(state ^ (state >>> 15), 1 | state);
27
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
28
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
29
+ };
30
+ };
31
+
32
+ // The letters of a free string, by locale.
33
+ const LETTERS = Object.assign(Object.create(null), {
34
+ en: 'abcdefghijklmnopqrstuvwxyz',
35
+ uk: 'абвгґдеєжзиіїйклмнопрстуфхцчшщьюя',
36
+ });
37
+
38
+ // How many draws a field gets before it is given up on, and how many an
39
+ // optional field is present in, out of four.
40
+ const DRAWS = 24;
41
+ const PRESENT = 3;
42
+
43
+ // What a draw returns for a field the value leaves out: an optional
44
+ // reference nested too deep.
45
+ const ABSENT = Symbol('absent');
46
+
47
+ // The built-in type a field validates as: its own, or the one its alias
48
+ // chain ends in; a custom type with a check of its own has none.
49
+ const baseOf = (field) => {
50
+ const { types } = field.root;
51
+ let Type = field.constructor;
52
+ while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
53
+ return Type.source === undefined ? Type.type : null;
54
+ };
55
+
56
+ // A count within the bounds a length rule gives, `low` when it gives none.
57
+ const countOf = (state, length, low, span = 3) => {
58
+ const min = length?.min ?? low;
59
+ const max = length?.max ?? min + span;
60
+ return min + int(state, Math.max(max - min, 0));
61
+ };
62
+
63
+ const lettersOf = (state, count) => {
64
+ let text = '';
65
+ for (let index = 0; index < count; index += 1) text += pick(state, state.letters);
66
+ return text;
67
+ };
68
+
69
+ // A string of the pattern, or of the letters within the length rule; a
70
+ // pattern whose shortest string is over `length.max` is unsatisfiable before
71
+ // a string is built.
72
+ const stringOf = (state, field, key) => {
73
+ const { pattern, length } = field;
74
+ if (pattern !== undefined) {
75
+ const { node, minLength } = patternOf(pattern);
76
+ const max = length?.max;
77
+ if (max !== undefined && minLength > max) {
78
+ const reason = `the pattern needs at least ${minLength} characters, over the maximum ${max}`;
79
+ throw unsatisfiable(state, key, reason);
80
+ }
81
+ const extra = Math.min(max ?? 3, Math.max(3, length?.min ?? 0));
82
+ return fromPattern(state, node, extra);
83
+ }
84
+ return lettersOf(state, countOf(state, length, 1, 7));
85
+ };
86
+
87
+ const asNumber = (value) => (typeof value === 'bigint' ? Number(value) : value);
88
+
89
+ const numberOf = (state, field, whole) => {
90
+ const min = asNumber(field.min);
91
+ const max = asNumber(field.max);
92
+ const low = min ?? (max === undefined ? 0 : max - 100);
93
+ const high = max ?? low + 100;
94
+ const value = low + state.random() * (high - low);
95
+ return whole ? Math.min(Math.ceil(value), Math.floor(high)) : value;
96
+ };
97
+
98
+ // The widest span a bigint is drawn from: what a number holds exactly.
99
+ const SPAN = 2n ** 53n;
100
+
101
+ const bigintOf = (state, field) => {
102
+ const low =
103
+ field.min === undefined
104
+ ? field.max === undefined
105
+ ? 0n
106
+ : BigInt(field.max) - 100n
107
+ : BigInt(field.min);
108
+ const high = field.max === undefined ? low + 100n : BigInt(field.max);
109
+ const span = high - low > SPAN ? SPAN : high - low;
110
+ return low + BigInt(int(state, Number(span)));
111
+ };
112
+
113
+ const idOf = (state, name) => `${name.toLowerCase()}-${int(state, 0xffff).toString(16)}`;
114
+
115
+ const keyOf = (state, index, numeric) =>
116
+ numeric ? index + 1 : `${pick(state, state.letters)}${index}`;
117
+
118
+ const listOf = (state, field, key) => {
119
+ const count = countOf(state, field.length, 0);
120
+ const list = [];
121
+ for (let index = 0; index < count; index += 1) {
122
+ const item = sampleField(field.value, state, index);
123
+ if (item !== ABSENT) list.push(item);
124
+ }
125
+ return field.type === 'set' || baseOf(field) === 'set' ? new Set(list) : list;
126
+ };
127
+
128
+ const keyedOf = (state, field) => {
129
+ const count = countOf(state, field.length, field.required ? 1 : 0);
130
+ const numeric = field.key === 'number';
131
+ const map = baseOf(field) === 'map';
132
+ const out = map ? new Map() : {};
133
+ for (let index = 0; index < count; index += 1) {
134
+ const name = keyOf(state, index, numeric);
135
+ const item = sampleField(field.value, state, name);
136
+ if (item === ABSENT) continue;
137
+ if (map) out.set(name, item);
138
+ else out[name] = item;
139
+ }
140
+ return out;
141
+ };
142
+
143
+ const tupleOf = (state, field) => {
144
+ const list = [];
145
+ for (let index = 0; index < field.value.length; index += 1) {
146
+ const item = sampleField(field.value[index], state, index);
147
+ list.push(item === ABSENT ? undefined : item);
148
+ }
149
+ return list;
150
+ };
151
+
152
+ // The errors of a branch that another branch may not have: a union tries
153
+ // every branch from a random one on and fails with the last error only when
154
+ // every branch failed.
155
+ const RETRIED = new Set(['ERR_UNSATISFIABLE', 'ERR_SAMPLE_PATTERN', 'ERR_SAMPLE_TYPE']);
156
+
157
+ const unionOf = (state, field, key) => {
158
+ const branches = field.union;
159
+ const start = int(state, branches.length - 1);
160
+ const { depth } = state;
161
+ const at = state.path.length;
162
+ let error = null;
163
+ for (let index = 0; index < branches.length; index += 1) {
164
+ const branch = branches[(start + index) % branches.length];
165
+ try {
166
+ return sampleField(branch, state, key);
167
+ } catch (thrown) {
168
+ if (!RETRIED.has(thrown?.code)) throw thrown;
169
+ error = thrown;
170
+ state.depth = depth;
171
+ state.path.length = at;
172
+ }
173
+ }
174
+ throw error;
175
+ };
176
+
177
+ // A referenced entity: its id, or the record itself where the check embeds
178
+ // it, as a nested struct; a record nested deeper than `maxDepth` is left
179
+ // out of an optional field and is an error on a required one.
180
+ const referenceOf = (state, field, key) => {
181
+ const name = field.one || field.many;
182
+ const target = field.root.findReference(name);
183
+ if (target === null) {
184
+ throw unsatisfiable(state, key, `Entity "${name}" is not found`);
185
+ }
186
+ const embedded = embeds(target, field.embed, state.references);
187
+ // The record under the key it is met at, as the check reports it.
188
+ const one = (at) => {
189
+ if (!embedded) return idOf(state, name);
190
+ if (state.depth >= state.maxDepth) return ABSENT;
191
+ state.depth += 1;
192
+ const record = drawValue(target.fields, state, at);
193
+ state.depth -= 1;
194
+ return record;
195
+ };
196
+ if (field.many === undefined) {
197
+ const record = one(key);
198
+ if (record === ABSENT && field.required) {
199
+ throw unsatisfiable(state, key, `"${name}" nests deeper than ${state.maxDepth} references`);
200
+ }
201
+ return record;
202
+ }
203
+ const count = int(state, 3);
204
+ const list = [];
205
+ const nested = key !== undefined;
206
+ if (nested) state.path.push(key);
207
+ for (let index = 0; index < count; index += 1) {
208
+ const record = one(index);
209
+ if (record !== ABSENT) list.push(record);
210
+ }
211
+ if (nested) state.path.pop();
212
+ return list;
213
+ };
214
+
215
+ // A value of a custom type: what `metadata.sample` gives (a function of the
216
+ // field and the random source, or a value), else nothing can.
217
+ const customOf = (state, field, key) => {
218
+ const { sample: given } = field.constructor.metadata;
219
+ if (given === undefined) {
220
+ const hint = `Type "${field.type}" needs metadata.sample to be sampled`;
221
+ throw invalid(
222
+ 'ERR_SAMPLE_TYPE',
223
+ `${hint} in "${toDotPath(pathOf(state, key), state.root.name)}"`,
224
+ );
225
+ }
226
+ return typeof given === 'function' ? given(field, state.random) : given;
227
+ };
228
+
229
+ const pathOf = (state, key) => (key === undefined ? state.path : state.path.concat([key]));
230
+
231
+ // A field no value satisfies, with the seed the draws were made with, so
232
+ // that the error is reproduced with the same call.
233
+ const unsatisfiable = (state, key, reason) => {
234
+ const where = toDotPath(pathOf(state, key), state.root.name);
235
+ const { seed } = state;
236
+ const error = invalid(
237
+ 'ERR_UNSATISFIABLE',
238
+ `No value satisfies "${where}" (seed ${seed}): ${reason}`,
239
+ );
240
+ error.seed = seed;
241
+ return error;
242
+ };
243
+
244
+ // One draw for a field, by the built-in type it validates as.
245
+ const draw = (state, field, key) => {
246
+ const { examples } = field;
247
+ if (Array.isArray(examples) && examples.length > 0 && state.random() < 0.5) {
248
+ return pick(state, examples);
249
+ }
250
+ switch (baseOf(field)) {
251
+ case 'string':
252
+ return stringOf(state, field, key);
253
+ case 'number':
254
+ return numberOf(state, field, false);
255
+ case 'integer':
256
+ return numberOf(state, field, true);
257
+ case 'bigint':
258
+ return bigintOf(state, field);
259
+ case 'boolean':
260
+ return state.random() < 0.5;
261
+ case 'date':
262
+ return new Date(1_600_000_000_000 + Math.floor(state.random() * 100_000_000_000));
263
+ case 'null':
264
+ return null;
265
+ case 'any':
266
+ case 'unknown':
267
+ return lettersOf(state, 4);
268
+ case 'json':
269
+ return {};
270
+ case 'enum':
271
+ return pick(state, field.enum);
272
+ case 'array':
273
+ case 'set':
274
+ return listOf(state, field, key);
275
+ case 'object':
276
+ case 'map':
277
+ return keyedOf(state, field);
278
+ case 'tuple':
279
+ return tupleOf(state, field);
280
+ case 'union':
281
+ return unionOf(state, field, key);
282
+ case 'schema':
283
+ return drawValue(field.schema, state, key);
284
+ case 'reference':
285
+ case 'one':
286
+ case 'many':
287
+ return referenceOf(state, field, key);
288
+ default:
289
+ return customOf(state, field, key);
290
+ }
291
+ };
292
+
293
+ // Whether a draw passes the field's own check (its type, its rules, its
294
+ // validate), in a context of the options the sample is for.
295
+ const accepted = (state, field, value, key) => {
296
+ const context = createContext(state.options, state.root.name, state.root.unknown);
297
+ field.check(value, context, key);
298
+ return context.count === 0 ? null : context.issues[0];
299
+ };
300
+
301
+ // A struct: a value for every field, an optional one three times out of
302
+ // four, null for a nullable one one time out of five.
303
+ const drawStruct = (fields, state, key) => {
304
+ const nested = key !== undefined;
305
+ if (nested) state.path.push(key);
306
+ const out = {};
307
+ for (const name in fields) {
308
+ const field = fields[name];
309
+ if (!hasBrand(field, 'Type')) continue;
310
+ if (!field.required && int(state, PRESENT) === 0) continue;
311
+ if (field.nullable === true && int(state, 4) === 0) {
312
+ define(out, name, null);
313
+ continue;
314
+ }
315
+ const value = sampleField(field, state, name);
316
+ if (value !== ABSENT) define(out, name, value);
317
+ }
318
+ if (nested) state.path.pop();
319
+ return out;
320
+ };
321
+
322
+ // A nested definition: a struct, or a field.
323
+ const drawValue = (node, state, key) =>
324
+ isStruct(node) ? drawStruct(node, state, key) : sampleField(node, state, key);
325
+
326
+ // A field: draws until one passes the field's check.
327
+ const sampleField = (field, state, key) => {
328
+ let issue = null;
329
+ for (let attempt = 0; attempt < DRAWS; attempt += 1) {
330
+ const value = draw(state, field, key);
331
+ if (value === ABSENT) return value;
332
+ issue = accepted(state, field, value, key);
333
+ if (issue === null) return value;
334
+ }
335
+ finalize([issue], en);
336
+ throw unsatisfiable(state, key, issue.message);
337
+ };
338
+
339
+ // How a reference may be held, as in check, and how deep embedded records
340
+ // may nest: a `many` reference fans out by up to four records a level.
341
+ const REFERENCES = ['kind', 'embed', 'id'];
342
+ const MAX_DEPTH = 32;
343
+
344
+ const optionsOf = (options) => {
345
+ if (options === null || typeof options !== 'object') {
346
+ throw invalidOptions('Sample options must be an object');
347
+ }
348
+ const { seed = 1, locale = 'en', references = 'kind', maxDepth = 3 } = options;
349
+ if (!Number.isInteger(seed)) throw invalidOptions('Sample option "seed" must be an integer');
350
+ if (LETTERS[locale] === undefined) {
351
+ throw invalidOptions(
352
+ `Sample option "locale" must be "en" or "uk", got ${JSON.stringify(locale)}`,
353
+ );
354
+ }
355
+ if (!REFERENCES.includes(references)) {
356
+ throw invalidOptions(
357
+ `Sample option "references" must be "kind", "embed" or "id", got ${JSON.stringify(references)}`,
358
+ );
359
+ }
360
+ if (!Number.isInteger(maxDepth) || maxDepth < 0 || maxDepth > MAX_DEPTH) {
361
+ throw invalidOptions(`Sample option "maxDepth" must be an integer from 0 to ${MAX_DEPTH}`);
362
+ }
363
+ return { seed, letters: LETTERS[locale], references, maxDepth };
364
+ };
365
+
366
+ // A value the schema accepts, the same for a seed. `options`: `seed` (1),
367
+ // `locale` ('en' or 'uk', the letters of free strings), `references` (how a
368
+ // reference is held, as in check) and `maxDepth` (how deep embedded records
369
+ // nest, 3, at most 32).
370
+ const sample = (schema, options = {}) => {
371
+ if (!hasBrand(schema, 'Schema')) throw invalidTarget('A Schema is expected');
372
+ const { seed, letters, references, maxDepth } = optionsOf(options);
373
+ const state = {
374
+ random: prng(seed),
375
+ seed,
376
+ letters,
377
+ references,
378
+ maxDepth,
379
+ depth: 0,
380
+ root: schema,
381
+ path: [],
382
+ options: { references, maxErrors: 1, maxDepth: maxDepth + 1 },
383
+ };
384
+ let issue = null;
385
+ for (let attempt = 0; attempt < DRAWS; attempt += 1) {
386
+ const value = drawValue(schema.fields, state, undefined);
387
+ const result = schema.check(value, state.options);
388
+ if (result.valid) return value;
389
+ issue = result.issues[0];
390
+ }
391
+ throw unsatisfiable(state, undefined, issue.message);
392
+ };
393
+
394
+ module.exports = { sample };
package/src/model.js CHANGED
@@ -5,6 +5,7 @@ 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
+ const { snapshotOf } = require('./snapshot.js');
8
9
 
9
10
  const registryFor = (options) => {
10
11
  const { registry = 'shared' } = options;
@@ -67,6 +68,13 @@ class Model {
67
68
  return warnings;
68
69
  }
69
70
 
71
+ // The model as plain JSON: `{ format, database, types, entities }`, the
72
+ // entities in dependency order with their metadata, fields, indexes and
73
+ // relations, and the types they use. What JSON.stringify(model) writes.
74
+ toJSON() {
75
+ return snapshotOf(this);
76
+ }
77
+
70
78
  #preprocess() {
71
79
  const { entities, order } = this;
72
80
  if (entities.has('Identifier')) order.add('Identifier');
@@ -76,7 +76,10 @@ class Preprocessor {
76
76
  const parsed = formatters.type(source.type, source.required);
77
77
  const { type, required } = parsed;
78
78
  if (isFirstUpper(type)) {
79
- const defs = { one: type, required, ...source };
79
+ // A built `many` field re-parsed from its own definition keeps its end
80
+ // of the relation; anything else is a single reference.
81
+ const defs =
82
+ source.many === undefined ? { one: type, required, ...source } : { required, ...source };
80
83
  return { Type: types.reference, defs };
81
84
  }
82
85
  if (!types[type]) {
@@ -10,10 +10,13 @@ const missingSchema = (type) => {
10
10
  const isDefinition = (value) =>
11
11
  value !== null && typeof value === 'object' && !Array.isArray(value);
12
12
 
13
- // The decoder and the serializer of a nested struct: the functions of its
14
- // definition (the options of a Schema it reuses), as its validate is, unless
15
- // the field's own definition gave them.
13
+ // The validate, the decoder and the serializer of a nested struct: the
14
+ // functions of its definition (the options of a Schema it reuses), unless the
15
+ // field's own definition gave them (`{ type: 'schema', schema, validate }`).
16
16
  const adopt = (type, source) => {
17
+ if (type.validate === undefined && typeof source.validate === 'function') {
18
+ type.validate = source.validate;
19
+ }
17
20
  if (type.parse === undefined && typeof source.parse === 'function') type.parse = source.parse;
18
21
  if (type.serialize === undefined && typeof source.serialize === 'function') {
19
22
  type.serialize = source.serialize;
@@ -33,13 +36,11 @@ const schema = {
33
36
  if (hasBrand(definition, 'Schema')) {
34
37
  prep.root.updateFromSchema(definition);
35
38
  this.schema = definition.fields;
36
- this.validate = definition.options.validate || undefined;
37
39
  adopt(this, definition.options);
38
40
  return;
39
41
  }
40
42
  if (isStruct(definition)) this.schema = definition;
41
43
  else this.schema = createStruct(definition, prep);
42
- this.validate = definition.validate || undefined;
43
44
  adopt(this, definition);
44
45
  },
45
46