@alexify/metaschema 3.0.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +312 -1
  2. package/README.md +463 -17
  3. package/SECURITY.md +26 -7
  4. package/index.d.ts +338 -3
  5. package/package.json +42 -5
  6. package/src/codec.js +161 -73
  7. package/src/compile/code.js +1 -1
  8. package/src/compile/emit.js +60 -7
  9. package/src/compile/index.d.ts +6 -0
  10. package/src/compile/index.js +14 -3
  11. package/src/context.js +8 -9
  12. package/src/errors.js +18 -1
  13. package/src/formats/index.d.ts +19 -0
  14. package/src/formats/index.js +146 -0
  15. package/src/generators/fromjsonschema.js +517 -0
  16. package/src/generators/index.d.ts +19 -2
  17. package/src/generators/index.js +16 -10
  18. package/src/generators/jsonschema.js +2 -0
  19. package/src/issues.js +37 -20
  20. package/src/lint.js +12 -3
  21. package/src/locales/en.js +11 -2
  22. package/src/locales/uk.js +10 -2
  23. package/src/metadata.js +3 -2
  24. package/src/model/data.js +122 -0
  25. package/src/model/diff.js +439 -0
  26. package/src/model/index.d.ts +68 -0
  27. package/src/model/index.js +45 -0
  28. package/src/model/infer.js +483 -0
  29. package/src/model/merge.js +255 -0
  30. package/src/model/pattern.js +322 -0
  31. package/src/model/restore.js +226 -0
  32. package/src/model/sample.js +398 -0
  33. package/src/model.js +13 -1
  34. package/src/preprocessor.js +5 -1
  35. package/src/prototypes/collections.js +4 -3
  36. package/src/prototypes/scalars.js +4 -4
  37. package/src/prototypes/schema.js +6 -5
  38. package/src/prototypes/union.js +2 -2
  39. package/src/result.js +6 -0
  40. package/src/rules.js +53 -4
  41. package/src/schema.js +28 -7
  42. package/src/snapshot.js +111 -0
  43. package/src/stream/index.d.ts +68 -0
  44. package/src/stream/index.js +247 -0
  45. package/src/struct.js +64 -18
  46. package/src/types.js +14 -1
  47. package/src/util.js +18 -0
@@ -0,0 +1,517 @@
1
+ // The other direction of the JSON Schema generator: a definition (or a
2
+ // Schema) from a JSON Schema document, for the subset a validation schema is
3
+ // made of: types, properties and required, enum and const, items and tuples,
4
+ // anyOf/oneOf as a union, `$ref` into the definitions, the rules (`minLength`,
5
+ // `maximum`, `minItems`, ...), null as nullable or optional, and the
6
+ // annotations. A keyword outside it (`allOf` with several schemas, `not`,
7
+ // `if`, `patternProperties`, `exclusiveMinimum`, ...) is ERR_UNSUPPORTED_SCHEMA
8
+ // with its place in the document, or dropped with `unsupported: 'ignore'`.
9
+ // The document is untrusted input: a pointer reads own keys only, a `$ref` is
10
+ // converted once per pointer, and the nesting is bounded.
11
+ const { isFirstUpper } = require('../metautil.js');
12
+ const { define, shorten } = require('../util.js');
13
+ const { Schema } = require('../schema.js');
14
+ const { readsAsStruct } = require('../types.js');
15
+ const { FORMATS } = require('../rules.js');
16
+ const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
17
+
18
+ const invalidOptions = (reason) => new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
19
+
20
+ // The keys of a JSON object are strings, so a number key is this pattern.
21
+ const NUMBER_KEY = '^-?\\d+(\\.\\d+)?$';
22
+
23
+ // Keywords that say nothing about the value: identifiers, comments and the
24
+ // annotations with no counterpart (`format` is an annotation in JSON Schema
25
+ // unless the dialect asserts it, and metaschema has `pattern` for that).
26
+ const IGNORED = new Set([
27
+ '$schema',
28
+ '$id',
29
+ '$comment',
30
+ '$defs',
31
+ 'definitions',
32
+ 'components',
33
+ 'format',
34
+ 'readOnly',
35
+ 'writeOnly',
36
+ 'contentMediaType',
37
+ 'contentEncoding',
38
+ 'additionalProperties',
39
+ 'nullable',
40
+ ]);
41
+
42
+ const ANNOTATIONS = ['title', 'description', 'default', 'examples', 'deprecated'];
43
+
44
+ // The types a node may name: those of JSON Schema, and the two the keywords
45
+ // of a node without a `type` are read as.
46
+ const KNOWN = new Set([
47
+ 'string',
48
+ 'number',
49
+ 'integer',
50
+ 'boolean',
51
+ 'null',
52
+ 'object',
53
+ 'array',
54
+ 'any',
55
+ 'json',
56
+ ]);
57
+
58
+ // How deep a document may nest: past it the conversion stops whatever the
59
+ // mode, since a lenient conversion must not recurse without end either.
60
+ const MAX_DEPTH = 128;
61
+
62
+ const option = (options, name, allowed) => {
63
+ const value = options[name];
64
+ if (value === undefined) return allowed[0];
65
+ if (!allowed.includes(value)) {
66
+ let list = '';
67
+ for (let index = 0; index < allowed.length; index += 1) {
68
+ list += `${index === 0 ? '' : ', '}${JSON.stringify(allowed[index])}`;
69
+ }
70
+ throw invalidOptions(`Option "${name}" must be one of ${list}, got ${JSON.stringify(value)}`);
71
+ }
72
+ return value;
73
+ };
74
+
75
+ const createContext = (document, options) => {
76
+ if (options === null || typeof options !== 'object') {
77
+ throw invalidOptions('Options must be an object');
78
+ }
79
+ const { name = '', onUnsupported } = options;
80
+ if (typeof name !== 'string') throw invalidOptions('Option "name" must be a string');
81
+ if (onUnsupported !== undefined && typeof onUnsupported !== 'function') {
82
+ throw invalidOptions('Option "onUnsupported" must be a function');
83
+ }
84
+ return {
85
+ document,
86
+ name,
87
+ as: option(options, 'as', ['definition', 'schema']),
88
+ references: option(options, 'references', ['inline', 'name']),
89
+ lenient: option(options, 'unsupported', ['throw', 'ignore']) === 'ignore',
90
+ onUnsupported,
91
+ // The place in the document, as the segments of a JSON pointer.
92
+ path: [],
93
+ // How many nodes the conversion is inside.
94
+ depth: 0,
95
+ // The pointers of the definitions being inlined, so that a cycle is found.
96
+ stack: new Set(),
97
+ // The definitions inlined so far, by pointer: a `$ref` met again is the
98
+ // same definition, not a second walk of the document.
99
+ cache: new Map(),
100
+ };
101
+ };
102
+
103
+ // The place in the document as a JSON pointer (RFC 6901); a key of the
104
+ // document may be huge, a message must not be.
105
+ const pointerOf = (path) => {
106
+ let pointer = '';
107
+ for (const segment of path) {
108
+ pointer += `/${shorten(segment).replace(/~/g, '~0').replace(/\//g, '~1')}`;
109
+ }
110
+ return pointer;
111
+ };
112
+
113
+ // A node outside the subset: the error with its place, or a drop that
114
+ // `onUnsupported` is told of (in the throw mode the error carries both).
115
+ const unsupported = (context, what) => {
116
+ const where = pointerOf(context.path);
117
+ if (context.lenient) {
118
+ if (context.onUnsupported !== undefined) context.onUnsupported(what, where);
119
+ return;
120
+ }
121
+ const reason = `${what} is not supported in a JSON Schema at "${where}"`;
122
+ throw new SchemaDefinitionError('ERR_UNSUPPORTED_SCHEMA', reason);
123
+ };
124
+
125
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
126
+
127
+ // A JSON Schema pattern is ECMA-262 without the `u` flag, and the rule of a
128
+ // field compiles with it, so a pattern that does not compile under the flag
129
+ // has no form here.
130
+ const compilesWithU = (pattern) => {
131
+ try {
132
+ RegExp(pattern, 'u');
133
+ return true;
134
+ } catch {
135
+ return false;
136
+ }
137
+ };
138
+
139
+ // A definition of a type with no other key is its name.
140
+ const compact = (def, required) => {
141
+ const keys = Object.keys(def);
142
+ if (keys.length === 1 && typeof def.type === 'string') {
143
+ return required ? def.type : `?${def.type}`;
144
+ }
145
+ if (!required) def.required = false;
146
+ return def;
147
+ };
148
+
149
+ const annotate = (def, node) => {
150
+ for (const name of ANNOTATIONS) if (node[name] !== undefined) def[name] = node[name];
151
+ if (node.example !== undefined && def.examples === undefined) def.examples = [node.example];
152
+ return def;
153
+ };
154
+
155
+ // A JSON pointer into the document (RFC 6901 as a URI fragment): `#`, or
156
+ // `#/$defs/Name` and the like, read through own keys only, so that
157
+ // `#/__proto__` or `#/constructor` finds nothing. The target is known by its
158
+ // decoded pointer, under which `A` and `%41` are one name, and two pointers
159
+ // that end alike are two.
160
+ const resolve = (context, ref) => {
161
+ if (typeof ref !== 'string' || (ref !== '#' && !ref.startsWith('#/'))) {
162
+ unsupported(context, `The reference ${JSON.stringify(ref)}`);
163
+ return null;
164
+ }
165
+ if (ref === '#') return { pointer: '', name: context.name, node: context.document };
166
+ const segments = ref.slice(2).split('/');
167
+ const keys = [];
168
+ let node = context.document;
169
+ for (const segment of segments) {
170
+ let key;
171
+ try {
172
+ key = decodeURIComponent(segment);
173
+ } catch {
174
+ unsupported(context, `The reference ${JSON.stringify(ref)} (a bad escape)`);
175
+ return null;
176
+ }
177
+ key = key.replace(/~1/g, '/').replace(/~0/g, '~');
178
+ keys.push(key);
179
+ node = isObject(node) && Object.hasOwn(node, key) ? node[key] : undefined;
180
+ }
181
+ if (node === undefined) {
182
+ unsupported(context, `The reference ${JSON.stringify(ref)} (nothing there)`);
183
+ return null;
184
+ }
185
+ return { pointer: pointerOf(keys), name: keys[keys.length - 1], node };
186
+ };
187
+
188
+ // A `$ref` inlined is converted once per pointer: the places that inline it
189
+ // share the converted subtree and get a copy of its top-level object, which
190
+ // is the one the annotations, `nullable` and `required` of the place are
191
+ // written to. A copy of the subtree would be as large as the output, which a
192
+ // diamond of definitions makes exponential.
193
+ const reference = (context, node) => {
194
+ const target = resolve(context, node.$ref);
195
+ if (target === null) return 'any';
196
+ const { pointer, name } = target;
197
+ if (context.references === 'name' || target.node === context.document) {
198
+ if (!isFirstUpper(name)) {
199
+ unsupported(context, `The reference ${JSON.stringify(node.$ref)} (not an entity name)`);
200
+ return 'any';
201
+ }
202
+ return name;
203
+ }
204
+ let def = context.cache.get(pointer);
205
+ if (def === undefined) {
206
+ if (context.stack.has(pointer)) {
207
+ unsupported(context, `The recursive reference ${JSON.stringify(node.$ref)}`);
208
+ return 'any';
209
+ }
210
+ context.stack.add(pointer);
211
+ def = longOf(context, target.node);
212
+ context.stack.delete(pointer);
213
+ context.cache.set(pointer, def);
214
+ }
215
+ return { ...def };
216
+ };
217
+
218
+ const structOf = (context, node, used) => {
219
+ const { properties, required = [] } = node;
220
+ used.add('properties');
221
+ used.add('required');
222
+ if (!Array.isArray(required)) unsupported(context, 'A "required" that is not a list');
223
+ const fields = {};
224
+ context.path.push('properties');
225
+ for (const key of Object.keys(properties)) {
226
+ context.path.push(key);
227
+ const def = convert(
228
+ context,
229
+ properties[key],
230
+ Array.isArray(required) && required.includes(key),
231
+ );
232
+ context.path.pop();
233
+ define(fields, key, def);
234
+ }
235
+ context.path.pop();
236
+ return fields;
237
+ };
238
+
239
+ // A JSON Schema type as a definition: the rules of the type, then the rest.
240
+ const typed = (context, node, type, used) => {
241
+ const def = { type };
242
+ const take = (name) => {
243
+ used.add(name);
244
+ return node[name];
245
+ };
246
+ if (type === 'string') {
247
+ const min = take('minLength');
248
+ const max = take('maxLength');
249
+ if (min !== undefined || max !== undefined) def.length = { min, max };
250
+ const pattern = take('pattern');
251
+ if (pattern !== undefined) {
252
+ if (typeof pattern !== 'string') unsupported(context, 'A "pattern" that is not a string');
253
+ else if (compilesWithU(pattern)) def.pattern = pattern;
254
+ else {
255
+ const shown = JSON.stringify(pattern);
256
+ unsupported(context, `The pattern ${shown} (not a valid pattern under the u flag)`);
257
+ }
258
+ }
259
+ // A format the formats subpath registered is the rule; any other stays
260
+ // the annotation JSON Schema says it is.
261
+ const format = take('format');
262
+ if (typeof format === 'string' && FORMATS[format] !== undefined) def.format = format;
263
+ return def;
264
+ }
265
+ if (type === 'number' || type === 'integer') {
266
+ const min = take('minimum');
267
+ const max = take('maximum');
268
+ if (min !== undefined) def.min = min;
269
+ if (max !== undefined) def.max = max;
270
+ return def;
271
+ }
272
+ if (type === 'array') {
273
+ const items = take('items');
274
+ const prefix = take('prefixItems');
275
+ const min = take('minItems');
276
+ const max = take('maxItems');
277
+ const elements = Array.isArray(prefix) ? prefix : Array.isArray(items) ? items : null;
278
+ if (elements !== null) {
279
+ // A tuple: the elements up to minItems are required, the rest optional.
280
+ take('additionalItems');
281
+ if (items !== false && !Array.isArray(items) && items !== undefined) {
282
+ unsupported(context, 'A tuple with more items');
283
+ }
284
+ def.type = 'tuple';
285
+ def.value = [];
286
+ const key = Array.isArray(prefix) ? 'prefixItems' : 'items';
287
+ context.path.push(key);
288
+ for (let index = 0; index < elements.length; index += 1) {
289
+ context.path.push(index);
290
+ def.value.push(convert(context, elements[index], min === undefined || index < min));
291
+ context.path.pop();
292
+ }
293
+ context.path.pop();
294
+ return def;
295
+ }
296
+ def.type = take('uniqueItems') === true ? 'set' : 'array';
297
+ context.path.push('items');
298
+ def.value = items === undefined ? 'any' : convert(context, items);
299
+ context.path.pop();
300
+ if (min !== undefined || max !== undefined) def.length = { min, max };
301
+ return def;
302
+ }
303
+ if (type === 'object') {
304
+ const min = take('minProperties');
305
+ const max = take('maxProperties');
306
+ if (isObject(node.properties)) {
307
+ def.type = 'schema';
308
+ def.schema = structOf(context, node, used);
309
+ if (min !== undefined || max !== undefined) {
310
+ unsupported(context, 'A struct with minProperties or maxProperties');
311
+ }
312
+ return def;
313
+ }
314
+ const { additionalProperties: values } = node;
315
+ if (values === undefined || values === true) return { type: 'json' };
316
+ if (values === false) unsupported(context, 'An object with no properties');
317
+ def.type = 'object';
318
+ def.key = 'string';
319
+ const names = take('propertyNames');
320
+ if (names !== undefined) {
321
+ if (isObject(names) && names.pattern === NUMBER_KEY) def.key = 'number';
322
+ else unsupported(context, 'A "propertyNames" other than the number key pattern');
323
+ }
324
+ context.path.push('additionalProperties');
325
+ def.value = convert(context, values);
326
+ context.path.pop();
327
+ if (min !== undefined || max !== undefined) def.length = { min, max };
328
+ return def;
329
+ }
330
+ return def;
331
+ };
332
+
333
+ // The branches of an anyOf or oneOf: null among them makes the value
334
+ // nullable, one branch is that branch, more are a union (with OpenAPI's
335
+ // discriminator when the node has one).
336
+ const branches = (context, node, key, used) => {
337
+ used.add(key);
338
+ const list = node[key];
339
+ const defs = [];
340
+ let nullable = false;
341
+ context.path.push(key);
342
+ for (let index = 0; index < list.length; index += 1) {
343
+ const branch = list[index];
344
+ if (isObject(branch) && branch.type === 'null' && Object.keys(branch).length === 1) {
345
+ nullable = true;
346
+ continue;
347
+ }
348
+ context.path.push(index);
349
+ defs.push(longOf(context, branch));
350
+ context.path.pop();
351
+ }
352
+ context.path.pop();
353
+ if (defs.length === 0) return { def: { type: 'null' }, nullable: false };
354
+ if (defs.length === 1) return { def: defs[0], nullable };
355
+ const def = { type: 'union', union: [] };
356
+ for (const branch of defs) def.union.push(compactDef(branch, true));
357
+ const { discriminator } = node;
358
+ if (discriminator !== undefined) {
359
+ used.add('discriminator');
360
+ if (isObject(discriminator) && typeof discriminator.propertyName === 'string') {
361
+ def.discriminator = discriminator.propertyName;
362
+ } else unsupported(context, 'A discriminator without a propertyName');
363
+ }
364
+ return { def, nullable };
365
+ };
366
+
367
+ // A node of the document as a definition object `{ type, ... }`.
368
+ const nodeOf = (context, node, used) => {
369
+ if (node.$ref !== undefined) {
370
+ used.add('$ref');
371
+ const def = reference(context, node);
372
+ return typeof def === 'string' ? { type: def } : def;
373
+ }
374
+ if (Array.isArray(node.allOf)) {
375
+ used.add('allOf');
376
+ if (node.allOf.length !== 1) {
377
+ unsupported(context, 'An "allOf" of several schemas');
378
+ return { type: 'any' };
379
+ }
380
+ context.path.push('allOf', 0);
381
+ const def = longOf(context, node.allOf[0]);
382
+ context.path.splice(-2, 2);
383
+ return def;
384
+ }
385
+ if (Array.isArray(node.anyOf) || Array.isArray(node.oneOf)) {
386
+ const key = Array.isArray(node.anyOf) ? 'anyOf' : 'oneOf';
387
+ const { def, nullable } = branches(context, node, key, used);
388
+ if (nullable) def.nullable = true;
389
+ return def;
390
+ }
391
+ if (node.enum !== undefined || node.const !== undefined) {
392
+ used.add('enum');
393
+ used.add('const');
394
+ const values = node.enum === undefined ? [node.const] : node.enum;
395
+ if (!Array.isArray(values)) {
396
+ unsupported(context, 'An "enum" that is not a list');
397
+ return { type: 'any' };
398
+ }
399
+ const def = { type: 'enum', enum: [] };
400
+ for (const value of values) {
401
+ if (value === null) def.nullable = true;
402
+ else def.enum.push(value);
403
+ }
404
+ if (def.enum.length === 0) return { type: 'null' };
405
+ return def;
406
+ }
407
+ used.add('type');
408
+ let { type } = node;
409
+ let nullable = false;
410
+ if (Array.isArray(type)) {
411
+ const rest = [];
412
+ for (const name of type) if (name !== 'null') rest.push(name);
413
+ nullable = rest.length !== type.length;
414
+ for (const name of rest) {
415
+ if (!KNOWN.has(name)) {
416
+ unsupported(context, `The type ${JSON.stringify(name)}`);
417
+ return { type: 'any' };
418
+ }
419
+ }
420
+ if (rest.length === 2 && rest.includes('object') && rest.includes('array')) type = 'json';
421
+ else if (rest.length === 1) type = rest[0];
422
+ else if (rest.length === 0) type = 'null';
423
+ else {
424
+ const def = { type: 'union', union: [] };
425
+ for (const name of rest) def.union.push(typed(context, node, name, used));
426
+ if (nullable) def.nullable = true;
427
+ return def;
428
+ }
429
+ }
430
+ if (type === undefined) {
431
+ if (isObject(node.properties)) type = 'object';
432
+ else if (node.items !== undefined || node.prefixItems !== undefined) type = 'array';
433
+ else if (
434
+ node.pattern !== undefined ||
435
+ node.minLength !== undefined ||
436
+ node.maxLength !== undefined
437
+ ) {
438
+ type = 'string';
439
+ } else if (node.minimum !== undefined || node.maximum !== undefined) type = 'number';
440
+ else type = 'any';
441
+ }
442
+ if (!KNOWN.has(type)) {
443
+ unsupported(context, `The type ${JSON.stringify(type)}`);
444
+ return { type: 'any' };
445
+ }
446
+ const def = type === 'json' ? { type: 'json' } : typed(context, node, type, used);
447
+ if (nullable) def.nullable = true;
448
+ return def;
449
+ };
450
+
451
+ // A node as a definition in the long form `{ type, ... }`: the type and its
452
+ // rules, null as `nullable`, the annotations, and the keywords left over
453
+ // reported. Every nested node comes through here, so this is where the
454
+ // nesting is counted.
455
+ const longOf = (context, node) => {
456
+ if (context.depth > MAX_DEPTH) {
457
+ const where = pointerOf(context.path);
458
+ const reason = `Nesting deeper than ${MAX_DEPTH} levels at "${where}"`;
459
+ throw new SchemaDefinitionError('ERR_UNSUPPORTED_SCHEMA', reason);
460
+ }
461
+ if (node === true || (isObject(node) && Object.keys(node).length === 0)) return { type: 'any' };
462
+ if (node === false) {
463
+ unsupported(context, 'The schema false');
464
+ return { type: 'any' };
465
+ }
466
+ if (!isObject(node)) {
467
+ unsupported(context, `A schema that is ${JSON.stringify(node)}`);
468
+ return { type: 'any' };
469
+ }
470
+ const used = new Set(ANNOTATIONS);
471
+ used.add('example');
472
+ context.depth += 1;
473
+ const def = nodeOf(context, node, used);
474
+ context.depth -= 1;
475
+ for (const key of Object.keys(node)) {
476
+ if (!used.has(key) && !IGNORED.has(key)) unsupported(context, `The keyword "${key}"`);
477
+ }
478
+ if (node.nullable === true) def.nullable = true;
479
+ return annotate(def, node);
480
+ };
481
+
482
+ // A definition as a field holds it: a nested struct as its fields (unless
483
+ // its first key would read as something else), a type with no other key as
484
+ // its name, an optional field as `?name` or `required: false`; an optional
485
+ // field accepts null anyway, so `nullable` is dropped from it.
486
+ const compactDef = (def, required) => {
487
+ if (def.nullable === true && !required) delete def.nullable;
488
+ if (def.type === 'schema' && Object.keys(def).length === 2) {
489
+ const { schema } = def;
490
+ if (readsAsStruct(schema)) return required ? schema : { schema, required: false };
491
+ return required ? { schema } : { schema, required: false };
492
+ }
493
+ return compact(def, required);
494
+ };
495
+
496
+ const convert = (context, node, required = true) => compactDef(longOf(context, node), required);
497
+
498
+ // The root: a struct with its kind, the unknown-keys policy
499
+ // (`additionalProperties: false` closes it, as the generator writes it) and
500
+ // its annotations as the metadata of the kind, or the definition of one type.
501
+ const fromJSONSchema = (document, options = {}) => {
502
+ const context = createContext(document, options);
503
+ if (!isObject(document) && document !== true) {
504
+ throw invalidTarget('A JSON Schema document (an object) is expected');
505
+ }
506
+ const def = longOf(context, document);
507
+ let definition;
508
+ if (def.type === 'schema') {
509
+ const { schema, type, nullable, ...rest } = def;
510
+ const meta = document.additionalProperties === false ? rest : { unknown: 'ignore', ...rest };
511
+ definition = { Struct: meta };
512
+ for (const key of Object.keys(schema)) define(definition, key, schema[key]);
513
+ } else definition = compact(def, true);
514
+ return context.as === 'schema' ? new Schema(context.name, definition) : definition;
515
+ };
516
+
517
+ module.exports = { fromJSONSchema };
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ FromJSONSchemaOptions,
2
3
  InterfaceOptions,
3
4
  JSONSchema,
4
5
  JSONSchemaOptions,
@@ -23,7 +24,23 @@ export function saveTypes(
23
24
  options?: InterfaceOptions,
24
25
  ): Promise<void>;
25
26
 
27
+ // A definition from a JSON Schema document (a Schema with `as: 'schema'`),
28
+ // for the subset a validation schema is made of; a keyword outside it is
29
+ // `ERR_UNSUPPORTED_SCHEMA` with its place in the document, or dropped with
30
+ // `unsupported: 'ignore'` (and told to `onUnsupported`). The document is
31
+ // untrusted input: a `$ref` is converted once per pointer, a pointer reads
32
+ // own keys only, and a nesting deeper than 128 levels is refused in both
33
+ // modes.
34
+ export function fromJSONSchema(
35
+ document: JSONSchema | true,
36
+ options: FromJSONSchemaOptions & { as: 'schema' },
37
+ ): Schema;
38
+ export function fromJSONSchema(
39
+ document: JSONSchema | true,
40
+ options?: FromJSONSchemaOptions,
41
+ ): object | string;
42
+
26
43
  // Installs `schema.toJSONSchema`, `schema.toInterface`, `model.toJSONSchema`,
27
- // `model.toTypeScript`, `model.dts` and `schema['~standard'].jsonSchema`.
28
- // Once per process; later calls do nothing.
44
+ // `model.toTypeScript`, `model.dts`, `Schema.fromJSONSchema` and
45
+ // `schema['~standard'].jsonSchema`. Once per process; later calls do nothing.
29
46
  export function register(): void;
@@ -1,19 +1,22 @@
1
1
  // The `./generators` subpath: what a schema or a model is rendered into
2
- // (JSON Schema, TypeScript), kept out of the core entry so that a program
3
- // that only validates does not carry it. The functions take a Schema or a
4
- // Model; `register()` installs them as methods, and the Standard JSON Schema
5
- // converter on `~standard`, for the programs that want the methods.
2
+ // (JSON Schema, TypeScript) and read from (a JSON Schema document), kept out
3
+ // of the core entry so that a program that only validates does not carry
4
+ // it. The functions take a Schema or a Model; `register()` installs them as
5
+ // methods, and the Standard JSON Schema converter on `~standard`, for the
6
+ // programs that want the methods.
6
7
  const { hasBrand } = require('../util.js');
8
+ const { invalidTarget } = require('../errors.js');
7
9
  const { Schema } = require('../schema.js');
8
10
  const { Model } = require('../model.js');
9
11
  const { writeFile } = require('../runtime/node.js');
10
12
  const generators = require('./jsonschema.js');
11
13
  const typescript = require('./typescript.js');
14
+ const { fromJSONSchema } = require('./fromjsonschema.js');
12
15
 
13
16
  const isModel = (target) => {
14
17
  if (hasBrand(target, 'Schema')) return false;
15
18
  if (hasBrand(target, 'Model')) return true;
16
- throw new TypeError('A Schema or a Model is expected');
19
+ throw invalidTarget('A Schema or a Model is expected');
17
20
  };
18
21
 
19
22
  // The JSON Schema document of a schema, or of a model (every entity as a
@@ -57,7 +60,8 @@ const modelMethods = {
57
60
  };
58
61
 
59
62
  // Installed like class members: not enumerable, so a loop over a schema
60
- // never sees them.
63
+ // never sees them. A copy per subpath rather than a helper of the core: the
64
+ // core is measured on its own, the subpaths on top of it.
61
65
  const install = (prototype, members) => {
62
66
  const descriptors = Object.getOwnPropertyDescriptors(members);
63
67
  for (const name in descriptors) {
@@ -69,14 +73,16 @@ const install = (prototype, members) => {
69
73
  let registered = false;
70
74
 
71
75
  // Adds `toJSONSchema` and `toInterface` to every schema, `toJSONSchema`,
72
- // `toTypeScript` and `dts` to every model, and the `jsonSchema` converter of
73
- // Standard JSON Schema to `schema['~standard']` (built once per schema, on
74
- // top of the props the core builds). Once per process.
76
+ // `toTypeScript` and `dts` to every model, `Schema.fromJSONSchema`, and the
77
+ // `jsonSchema` converter of Standard JSON Schema to `schema['~standard']`
78
+ // (built once per schema, on top of the props the core builds). Once per
79
+ // process.
75
80
  const register = () => {
76
81
  if (registered) return;
77
82
  registered = true;
78
83
  install(Schema.prototype, schemaMethods);
79
84
  install(Model.prototype, modelMethods);
85
+ install(Schema, { fromJSONSchema });
80
86
  const standard = Object.getOwnPropertyDescriptor(Schema.prototype, '~standard');
81
87
  const { get } = standard;
82
88
  standard.get = function withConverter() {
@@ -87,4 +93,4 @@ const register = () => {
87
93
  Object.defineProperty(Schema.prototype, '~standard', standard);
88
94
  };
89
95
 
90
- module.exports = { toJSONSchema, toTypeScript, saveTypes, register };
96
+ module.exports = { toJSONSchema, toTypeScript, saveTypes, fromJSONSchema, register };
@@ -332,6 +332,8 @@ const RENDER = Object.assign(Object.create(null), {
332
332
  if (context.strict) return json;
333
333
  bounds(json, field.length, 'minLength', 'maxLength');
334
334
  if (field.pattern !== undefined) json.pattern = field.pattern.source;
335
+ // The names are those of JSON Schema; a $jsonSchema has no `format`.
336
+ if (field.format !== undefined && !context.mongo) json.format = field.format;
335
337
  return json;
336
338
  },
337
339
  number: (field, context) => ranged(typed('number', context), field, context),