@alexify/metaschema 3.3.0 → 3.4.1

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 (53) hide show
  1. package/CHANGELOG.md +251 -1
  2. package/README.md +31 -20
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +280 -48
  5. package/package.json +13 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +37 -13
  8. package/src/coerce/index.js +34 -1
  9. package/src/compile/emit.js +87 -28
  10. package/src/compile/index.js +9 -4
  11. package/src/definition/index.d.ts +19 -0
  12. package/src/definition/index.js +27 -0
  13. package/src/derive/index.js +23 -13
  14. package/src/errors.js +23 -0
  15. package/src/generators/fromjsonschema.js +14 -0
  16. package/src/generators/index.js +1 -1
  17. package/src/generators/jsonschema.js +44 -7
  18. package/src/generators/typescript.js +11 -0
  19. package/src/index.js +3 -2
  20. package/src/issues.js +9 -7
  21. package/src/kinds.js +24 -2
  22. package/src/lint.js +64 -2
  23. package/src/locales/en.js +6 -0
  24. package/src/locales/uk.js +6 -0
  25. package/src/metadata.js +2 -24
  26. package/src/model/data.js +68 -11
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +13 -6
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +60 -8
  32. package/src/model/sample.js +26 -1
  33. package/src/model.js +25 -53
  34. package/src/mongodb/bson.js +15 -3
  35. package/src/mongodb/document.js +10 -2
  36. package/src/preprocessor.js +14 -5
  37. package/src/prototypes/abstract.js +32 -64
  38. package/src/prototypes/collections.js +3 -90
  39. package/src/prototypes/flags.js +34 -0
  40. package/src/prototypes/json.js +0 -11
  41. package/src/prototypes/reference.js +0 -76
  42. package/src/prototypes/scalars.js +17 -96
  43. package/src/prototypes/schema.js +1 -10
  44. package/src/prototypes/tuple.js +5 -31
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +108 -233
  48. package/src/snapshot.js +216 -41
  49. package/src/stream/index.js +1 -1
  50. package/src/struct.js +6 -91
  51. package/src/types.js +31 -10
  52. package/src/util.js +48 -0
  53. package/src/validation.js +313 -0
package/src/codec.js CHANGED
@@ -20,13 +20,10 @@ const {
20
20
  toDotPath,
21
21
  } = require('./issues.js');
22
22
  const { createContext } = require('./context.js');
23
- const { STRUCT, isStruct, aliasOf } = require('./struct.js');
23
+ const { STRUCT, isStruct } = require('./struct.js');
24
+ const { COMPILE, aliasOf, tableOf } = require('./checks.js');
24
25
  const { asyncReturn, notRegistered } = require('./errors.js');
25
- const collections = require('./prototypes/collections.js');
26
- const { schema: struct } = require('./prototypes/schema.js');
27
- const { tuple } = require('./prototypes/tuple.js');
28
- const { union, tableOf } = require('./prototypes/union.js');
29
- const { reference, embeds } = require('./prototypes/reference.js');
26
+ const { embeds } = require('./prototypes/reference.js');
30
27
 
31
28
  // What a subtree carries, as bits; a phase is the bit it applies.
32
29
  const DEFAULTS = 1;
@@ -71,15 +68,17 @@ const KEYED = 5;
71
68
  const TUPLE = 6;
72
69
  const UNION = 7;
73
70
  const REFERENCE = 8;
71
+ const FLAGS = 9;
74
72
 
75
73
  const SHAPES = new Map([
76
- [struct.compile, NESTED],
77
- [collections.array.compile, LIST],
78
- [collections.object.compile, KEYED],
79
- [collections.map.compile, KEYED],
80
- [tuple.compile, TUPLE],
81
- [union.compile, UNION],
82
- [reference.compile, REFERENCE],
74
+ [COMPILE.schema, NESTED],
75
+ [COMPILE.array, LIST],
76
+ [COMPILE.object, KEYED],
77
+ [COMPILE.map, KEYED],
78
+ [COMPILE.tuple, TUPLE],
79
+ [COMPILE.union, UNION],
80
+ [COMPILE.reference, REFERENCE],
81
+ [COMPILE.flags, FLAGS],
83
82
  ]);
84
83
 
85
84
  const shapeOf = (node) => {
@@ -144,6 +143,9 @@ const infoOf = (node) => {
144
143
  } else if (shape === REFERENCE) {
145
144
  bits |= DEFAULTS | DECODERS | ENCODERS | STRUCTS;
146
145
  refs.push(node);
146
+ } else if (shape === FLAGS) {
147
+ bits |= STRUCTS;
148
+ table = new Set(node.flags);
147
149
  }
148
150
  if (plan === null) {
149
151
  for (let index = 0; index < children.length; index += 1) {
@@ -645,6 +647,27 @@ const walkReference = (info, node, value, context, key, phase, want) => {
645
647
  return out;
646
648
  };
647
649
 
650
+ // The names of a flags value: under strip the ones the field does not have
651
+ // are left out, the value copied only when it has one (a value of names of
652
+ // the list comes back as it is). The names are in a Set on the info; no
653
+ // name is `__proto__` (the type refuses it), so a plain object holds them.
654
+ const walkFlags = (info, node, given, context, key, phase, want) => {
655
+ const value = convert(want, given, node, info);
656
+ if ((want & STRUCTS) === 0 || value === null || typeof value !== 'object') return value;
657
+ const known = info.table;
658
+ let foreign = false;
659
+ for (const name in value) {
660
+ if (Object.hasOwn(value, name) && !known.has(name)) {
661
+ foreign = true;
662
+ break;
663
+ }
664
+ }
665
+ if (!foreign) return value;
666
+ const out = {};
667
+ for (const name of node.flags) if (Object.hasOwn(value, name)) out[name] = value[name];
668
+ return out;
669
+ };
670
+
648
671
  // A field's own `coerce` turns coercion on or off for its subtree, in the
649
672
  // pass before the check.
650
673
  const walkPolicy = (info, node, value, context, key, phase, want) => {
@@ -663,6 +686,7 @@ const WALKERS = [
663
686
  walkList,
664
687
  walkUnion,
665
688
  walkReference,
689
+ walkFlags,
666
690
  ];
667
691
 
668
692
  // The bits a pass wants of a subtree, decided once per pass: its own, and
@@ -8,7 +8,7 @@
8
8
  // the check reports it as given.
9
9
  const { hasBrand, isSet, isMap } = require('../util.js');
10
10
  const { isFirstLower } = require('../metautil.js');
11
- const { Schema } = require('../schema.js');
11
+ const { Schema } = require('../validation.js');
12
12
  const { createContext } = require('../context.js');
13
13
  const { COERCE, COERCION, PREPARE, infoOf, apply, wantOf, looped } = require('../codec.js');
14
14
  const { SchemaDefinitionError, invalidTarget, invalidOption } = require('../errors.js');
@@ -80,6 +80,38 @@ const toText = (value) => {
80
80
  return type === 'bigint' || type === 'boolean' ? String(value) : value;
81
81
  };
82
82
 
83
+ // Canonical base64 (RFC 4648 §4): padded, and with the bits the padding
84
+ // leaves unused at zero, so that one text is one value; what a decoder
85
+ // would forgive (whitespace, a missing `=`, the URL alphabet) is left to
86
+ // the check. A charset, a length and the last quantum rather than one
87
+ // expression of quanta, whose repetition grows the stack of the engine by a
88
+ // frame each and overflowed it on a valid text of a few megabytes (the
89
+ // formats subpath reads base64 the same way). `''` is the text of no bytes.
90
+ const ALPHABET = /^[A-Za-z0-9+/]*={0,2}$/;
91
+
92
+ const isBase64 = (text) => {
93
+ const { length } = text;
94
+ if (length % 4 !== 0 || !ALPHABET.test(text)) return false;
95
+ if (text[length - 1] !== '=') return true;
96
+ if (text[length - 2] === '=') return 'AQgw'.includes(text[length - 3]);
97
+ return 'AEIMQUYcgkosw048'.includes(text[length - 2]);
98
+ };
99
+
100
+ // A text whose bytes would be over `length.max` is not decoded: the check
101
+ // rejects it, and a converter runs before the check, so this is what bounds
102
+ // what it allocates.
103
+ const toBytes = (value, field) => {
104
+ if (typeof value !== 'string' || !isBase64(value)) return value;
105
+ const max = field.length?.max;
106
+ const pad = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
107
+ if (max !== undefined && (value.length / 4) * 3 - pad > max) return value;
108
+ if (Uint8Array.fromBase64 !== undefined) return Uint8Array.fromBase64(value);
109
+ const text = atob(value);
110
+ const bytes = new Uint8Array(text.length);
111
+ for (let index = 0; index < text.length; index += 1) bytes[index] = text.charCodeAt(index);
112
+ return bytes;
113
+ };
114
+
83
115
  const isPrimitive = (value) => {
84
116
  const type = typeof value;
85
117
  return type === 'number' || type === 'boolean' || type === 'bigint';
@@ -168,6 +200,7 @@ const BUILT_IN = {
168
200
  bigint: toBigint,
169
201
  boolean: toBoolean,
170
202
  date: toDate,
203
+ bytes: toBytes,
171
204
  enum: toEnum,
172
205
  array: toArray,
173
206
  set: toSet,
@@ -7,16 +7,21 @@
7
7
  //
8
8
  // Generated code names three things: `v` the value, `c` the context and `k`
9
9
  // the key the root was called with. Every other identifier is fresh.
10
- const { ENUM_SET_SIZE } = require('../util.js');
10
+ const { ENUM_SET_SIZE, isBytes } = require('../util.js');
11
11
  const { issues, runValidate, release } = require('../issues.js');
12
- const { FORMATS, codePoints, lengthOf, ruleNames, patternLimit } = require('../rules.js');
12
+ const { formatOf } = require('../rules.js');
13
13
  const { STRUCT, isStruct } = require('../struct.js');
14
- const scalars = require('../prototypes/scalars.js');
15
14
  const collections = require('../prototypes/collections.js');
16
- const { schema } = require('../prototypes/schema.js');
17
- const { tuple } = require('../prototypes/tuple.js');
18
- const { union, nameOf, tableOf } = require('../prototypes/union.js');
19
- const { json } = require('../prototypes/json.js');
15
+ const {
16
+ COMPILE,
17
+ decimalsOff,
18
+ codePoints,
19
+ lengthOf,
20
+ ruleNames,
21
+ patternLimit,
22
+ nameOf,
23
+ tableOf,
24
+ } = require('../checks.js');
20
25
  const { prop, quote, literal } = require('./code.js');
21
26
 
22
27
  // The key of the field under check, as source: a quoted name, an index, a
@@ -75,9 +80,8 @@ const emitLength = (type, x, key, state) => {
75
80
  if (min === undefined && max === undefined) return;
76
81
  const n = code.name('n');
77
82
  let measure = `${code.ref(lengthOf)}(${x})`;
78
- if (type.scalar === 'string') {
79
- measure = type.unicode === true ? `${code.ref(codePoints)}(${x})` : `${x}.length`;
80
- }
83
+ if (type.scalar === 'string' && type.unicode === true) measure = `${code.ref(codePoints)}(${x})`;
84
+ else if (type.scalar === 'string' || type.scalar === 'bytes') measure = `${x}.length`;
81
85
  code.push(`const ${n} = ${measure};`);
82
86
  code.push(`if (${outside(state, n, min, max)}) {`);
83
87
  const bounds = `${code.value(min)}, ${code.value(max)}, ${n}, ${keyOf(key)}`;
@@ -103,12 +107,23 @@ const emitPattern = (type, x, key, state) => {
103
107
  const emitFormat = (type, x, key, state) => {
104
108
  const { code } = state;
105
109
  const { format } = type;
106
- const { test } = FORMATS[format];
110
+ const { test } = formatOf(type);
107
111
  code.push(`if (${withinLength(type, x, code)}!${code.ref(test)}(${x})) {`);
108
112
  record(state, issue(state, 'format', `${quote(format)}, ${keyOf(key)}`));
109
113
  code.push('}');
110
114
  };
111
115
 
116
+ // The decimals of a number, by the test of checks.js (`decimalsOff`); the
117
+ // numbers of the rule reach the source as literals of `code.value`, never as
118
+ // the text of the field.
119
+ const emitDecimals = (type, x, key, state) => {
120
+ const { code } = state;
121
+ const { decimals } = type;
122
+ code.push(`if (${code.ref(decimalsOff)}(${x}, ${code.value(10 ** decimals)})) {`);
123
+ record(state, issue(state, 'decimals', `${code.value(decimals)}, ${x}, ${keyOf(key)}`));
124
+ code.push('}');
125
+ };
126
+
112
127
  const emitRange = (type, x, key, state) => {
113
128
  const { code } = state;
114
129
  const { min, max } = type;
@@ -122,6 +137,7 @@ const RULES = Object.assign(Object.create(null), {
122
137
  length: emitLength,
123
138
  pattern: emitPattern,
124
139
  format: emitFormat,
140
+ decimals: emitDecimals,
125
141
  range: emitRange,
126
142
  });
127
143
 
@@ -184,6 +200,16 @@ const emitDate = (type, x, key, state) => {
184
200
  typed(type, x, key, state, fails, typeIssue(state, 'date', x, key));
185
201
  };
186
202
 
203
+ const emitBytes = (type, x, key, state) =>
204
+ typed(
205
+ type,
206
+ x,
207
+ key,
208
+ state,
209
+ `!${state.code.ref(isBytes)}(${x})`,
210
+ typeIssue(state, 'bytes', x, key),
211
+ );
212
+
187
213
  const emitNull = (type, x, key, state) =>
188
214
  typed(type, x, key, state, `${x} !== null`, typeIssue(state, 'null', x, key));
189
215
 
@@ -250,6 +276,37 @@ const emitObject = (type, x, key, state) => {
250
276
  });
251
277
  };
252
278
 
279
+ // The own keys of a flags value: a name of the list holds a boolean, any
280
+ // other key is unexpected under the reject policy, as in the closure.
281
+ const emitFlags = (type, x, key, state) => {
282
+ const { code } = state;
283
+ const failure = typeIssue(state, type.type, x, key);
284
+ typed(type, x, key, state, notObject(x), failure, () => {
285
+ const children = inside(state, key);
286
+ const name = code.name('n');
287
+ const item = code.name('x');
288
+ const unexpected = code.name('u');
289
+ let cases = '';
290
+ for (const flag of type.flags) cases += `case ${quote(flag)}: `;
291
+ code.push(`let ${unexpected} = null;`);
292
+ code.push(`for (const ${name} in ${x}) {`);
293
+ code.push(`if (!Object.hasOwn(${x}, ${name})) continue;`);
294
+ code.push(`switch (${name}) { ${cases}{`);
295
+ code.push(`const ${item} = ${x}[${name}];`);
296
+ code.push(`if (typeof ${item} !== "boolean") {`);
297
+ record(children, typeIssue(state, 'boolean', item, name));
298
+ code.push('}');
299
+ code.push('continue; } }');
300
+ code.push(
301
+ `if (c.unknown === "reject") (${unexpected} === null ? (${unexpected} = []) : ${unexpected}).push(${name});`,
302
+ );
303
+ code.push('}');
304
+ code.push(`if (${unexpected} !== null) {`);
305
+ record(children, issue(state, 'unexpected', unexpected));
306
+ code.push('}');
307
+ });
308
+ };
309
+
253
310
  const emitMap = (type, x, key, state) => {
254
311
  const { code } = state;
255
312
  const failure = typeIssue(state, type.type, x, key);
@@ -337,7 +394,7 @@ const emitStruct = (fields, x, key, state) => {
337
394
  if (entry.aliases.length > 0) {
338
395
  // A field with aliases, when the value has nothing under its own key:
339
396
  // the first alias the value carries, and the key the check reports
340
- // under, as `aliasOf` in struct.js finds them.
397
+ // under, as `aliasOf` of checks.js finds them.
341
398
  const alias = code.name('k');
342
399
  const inherited = own ? ` || !Object.hasOwn(${x}, ${name})` : '';
343
400
  code.push(`let ${item} = ${prop(x, entry.key)}, ${alias} = ${name};`);
@@ -383,9 +440,9 @@ const emitStruct = (fields, x, key, state) => {
383
440
  code.push(`let ${total} = 0;`);
384
441
  code.push(`for (const ${name} in ${x}) ${total} += 1;`);
385
442
  code.push(`if (${total} !== ${found}) {`);
386
- // The scan of struct.js with the known keys as cases: a key for...in
387
- // yields is an internalized string, so a case is a pointer comparison
388
- // where a dictionary lookup would hash it.
443
+ // The scan of `checkOf` (checks.js) with the known keys as cases: a key
444
+ // for...in yields is an internalized string, so a case is a pointer
445
+ // comparison where a dictionary lookup would hash it.
389
446
  let cases = '';
390
447
  for (const field in known) cases += `case ${quote(field)}: `;
391
448
  code.push(`let ${unexpected} = null;`);
@@ -492,19 +549,21 @@ const emitUnion = (type, x, key, state) => {
492
549
  };
493
550
 
494
551
  const EMITTERS = new Map([
495
- [scalars.string.compile, emitScalar],
496
- [scalars.integer.compile, emitInteger],
497
- [scalars.date.compile, emitDate],
498
- [scalars.null.compile, emitNull],
499
- [scalars.any.compile, emitAny],
500
- [scalars.enum.compile, emitEnum],
501
- [json.compile, emitJson],
502
- [collections.object.compile, emitObject],
503
- [collections.map.compile, emitMap],
504
- [collections.array.compile, emitList],
505
- [tuple.compile, emitTuple],
506
- [union.compile, emitUnion],
507
- [schema.compile, emitSchema],
552
+ [COMPILE.string, emitScalar],
553
+ [COMPILE.integer, emitInteger],
554
+ [COMPILE.date, emitDate],
555
+ [COMPILE.bytes, emitBytes],
556
+ [COMPILE.flags, emitFlags],
557
+ [COMPILE.null, emitNull],
558
+ [COMPILE.any, emitAny],
559
+ [COMPILE.enum, emitEnum],
560
+ [COMPILE.json, emitJson],
561
+ [COMPILE.object, emitObject],
562
+ [COMPILE.map, emitMap],
563
+ [COMPILE.array, emitList],
564
+ [COMPILE.tuple, emitTuple],
565
+ [COMPILE.union, emitUnion],
566
+ [COMPILE.schema, emitSchema],
508
567
  ]);
509
568
 
510
569
  // The check of one field over the local `x`. A built-in prototype is
@@ -7,7 +7,7 @@
7
7
  // `node --disallow-code-generation-from-strings`) the closures stay, silently
8
8
  // in the default mode. Nothing happens on import.
9
9
  const { hasBrand, RUN, HOOK } = require('../util.js');
10
- const { Schema } = require('../schema.js');
10
+ const { Schema } = require('../validation.js');
11
11
  const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
12
12
  const { Code } = require('./code.js');
13
13
  const { emitRoot } = require('./emit.js');
@@ -71,12 +71,18 @@ const failure = (target, error) => {
71
71
  return wrapped;
72
72
  };
73
73
 
74
+ // The checks the subpath generated: the closures a schema runs instead may
75
+ // be the ones it was built with or ones compiled later, on first use.
76
+ const GENERATED = new WeakSet();
77
+
74
78
  const build = (target) => {
75
79
  const code = new Code();
76
80
  emitRoot(target, code);
77
81
  // oxlint-disable-next-line no-new-func
78
82
  const factory = new Function('scope', code.source(target.name));
79
- return factory(code.values);
83
+ const run = factory(code.values);
84
+ GENERATED.add(run);
85
+ return run;
80
86
  };
81
87
 
82
88
  // The generated check, or ERR_JIT_BUILD: the JIT was demanded.
@@ -158,8 +164,7 @@ const compile = (target, options = {}) => {
158
164
  const compiled = (target) => {
159
165
  const schemas = schemasOf(target);
160
166
  for (let index = 0; index < schemas.length; index += 1) {
161
- const schema = schemas[index];
162
- if (!ORIGINAL.has(schema) || schema[RUN] === ORIGINAL.get(schema)) return false;
167
+ if (!GENERATED.has(schemas[index][RUN])) return false;
163
168
  }
164
169
  return true;
165
170
  };
@@ -0,0 +1,19 @@
1
+ // The `@alexify/metaschema/definition` subpath: the core's own Schema and
2
+ // Model, built and read without the half that validates. Until the core
3
+ // entry is loaded as well, `check`, `checkAsync`, `parse`, `parseAsync`,
4
+ // `serialize`, `validate`, `checkConsistency`, `warnings`, the `check` of a
5
+ // field and `model.warnings` throw a `TypeError` with the code
6
+ // `ERR_NOT_REGISTERED`, and a schema has no `~standard`; the typings are the
7
+ // core's, since loading the core installs all of them into these classes.
8
+ export {
9
+ KIND,
10
+ KIND_STORED,
11
+ KIND_MEMORY,
12
+ SCOPE,
13
+ STORE,
14
+ ALLOW,
15
+ getKindMetadata,
16
+ Schema,
17
+ Model,
18
+ SchemaDefinitionError,
19
+ } from '../../index.js';
@@ -0,0 +1,27 @@
1
+ // The `./definition` subpath: the half of the core that builds schemas and
2
+ // models and reads them (their fields and metadata, the warnings of their
3
+ // definitions, `toJSON` and `toSnapshot`), without the half that validates.
4
+ // For a program that needs the definitions and their snapshots alone (the
5
+ // browser client of a codec built from them): `check`, `parse` and their
6
+ // kin say that the core entry is missing. The classes are the core's own,
7
+ // so a program that loads the core entry as well validates with these very
8
+ // schemas, and a bundle of both carries each module once.
9
+ const { constants, getKindMetadata } = require('../kinds.js');
10
+ const { Schema } = require('../schema.js');
11
+ const { Model } = require('../model.js');
12
+ const { SchemaDefinitionError } = require('../errors.js');
13
+
14
+ const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
15
+
16
+ module.exports = {
17
+ KIND,
18
+ KIND_STORED,
19
+ KIND_MEMORY,
20
+ SCOPE,
21
+ STORE,
22
+ ALLOW,
23
+ getKindMetadata,
24
+ Schema,
25
+ Model,
26
+ SchemaDefinitionError,
27
+ };
@@ -6,12 +6,18 @@
6
6
  // too), so the source is never touched and every rule of a field comes along.
7
7
  // `register()` installs the functions as methods of Schema, so they chain.
8
8
  const { hasBrand, define, formatters } = require('../util.js');
9
- const { isFirstUpper, firstKey } = require('../metautil.js');
9
+ const { firstKey } = require('../metautil.js');
10
10
  const { Schema } = require('../schema.js');
11
11
  const { isStruct } = require('../struct.js');
12
- const { idFieldOf } = require('../kinds.js');
12
+ const { idFieldOf, isKindKey } = require('../kinds.js');
13
13
  const { SchemaDefinitionError, invalidTarget, invalidOption } = require('../errors.js');
14
- const { structDefinitionOf, metadataOf, structDefinition, atSchema } = require('../model/data.js');
14
+ const {
15
+ structDefinitionOf,
16
+ metadataOf,
17
+ structDefinition,
18
+ atSchema,
19
+ namespacesOf,
20
+ } = require('../model/data.js');
15
21
 
16
22
  // The functions of a nested struct that are its own: written for the whole
17
23
  // struct, they do not hold for a part of it.
@@ -101,10 +107,11 @@ const bodyOf = (schema, fields, functions) => {
101
107
  return fields;
102
108
  };
103
109
 
104
- const build = (schema, options, body, namespaces) => {
110
+ // The schema derived, with the namespaces of the schemas it is derived from.
111
+ const build = (schema, options, body, sources) => {
105
112
  const { name = schema.name, metadata } = options;
106
113
  const definition = structDefinition(kindOf(schema), metadata, body);
107
- return new Schema(name, definition, Array.from(namespaces));
114
+ return new Schema(name, definition, namespacesOf(sources));
108
115
  };
109
116
 
110
117
  const select = (schema, keys, options, keep) => {
@@ -116,7 +123,7 @@ const select = (schema, keys, options, keep) => {
116
123
  for (const key of Object.keys(all)) {
117
124
  if (names.has(key) === keep) define(fields, key, all[key]);
118
125
  }
119
- return build(schema, settings, bodyOf(schema, fields, false), schema.namespaces);
126
+ return build(schema, settings, bodyOf(schema, fields, false), [schema]);
120
127
  };
121
128
 
122
129
  // The fields named, in the order of the schema.
@@ -157,7 +164,7 @@ const toggle = (schema, options, required) => {
157
164
  if (typeof def === 'function') continue;
158
165
  if (names === null || names.has(key)) settle(def, required, deep, defaults);
159
166
  }
160
- return build(schema, settings, bodyOf(schema, fields, required), schema.namespaces);
167
+ return build(schema, settings, bodyOf(schema, fields, required), [schema]);
161
168
  };
162
169
 
163
170
  // Every field (or the ones in `options.keys`) optional. The schema's own
@@ -174,16 +181,19 @@ const extend = (schema, extension, options) => {
174
181
  sourceOf(schema);
175
182
  const settings = optionsOf(options);
176
183
  let additions = extension;
177
- let namespaces = schema.namespaces;
184
+ const sources = [schema];
178
185
  if (hasBrand(extension, 'Schema')) {
179
186
  sourceOf(extension);
180
187
  additions = bodyOf(extension, fieldsOf(extension, null), true);
181
- namespaces = new Set([...schema.namespaces, ...extension.namespaces]);
188
+ sources.push(extension);
182
189
  } else if (extension === null || typeof extension !== 'object' || Array.isArray(extension)) {
183
190
  throw invalidTarget('An extension is a Schema of a struct or an object of fields');
184
- } else if (isFirstUpper(firstKey(extension))) {
185
- const reason = 'An extension has fields only; the kind is options.metadata';
186
- throw atSchema(new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason), schema.name);
191
+ } else {
192
+ const first = firstKey(extension);
193
+ if (isKindKey(first, extension[first])) {
194
+ const reason = 'An extension has fields only; the kind is options.metadata';
195
+ throw atSchema(new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason), schema.name);
196
+ }
187
197
  }
188
198
  const keys = new Map();
189
199
  for (const key of Object.keys(additions)) keys.set(formatters.key(key).field, key);
@@ -201,7 +211,7 @@ const extend = (schema, extension, options) => {
201
211
  for (const key of Object.keys(additions)) {
202
212
  if (!placed.has(key)) define(body, key, additions[key]);
203
213
  }
204
- return build(schema, settings, body, namespaces);
214
+ return build(schema, settings, body, sources);
205
215
  };
206
216
 
207
217
  // The names of the fields a value carries, as a schema of an enum: the
package/src/errors.js CHANGED
@@ -52,6 +52,27 @@ const notRegistered = (what, where) => {
52
52
  return error;
53
53
  };
54
54
 
55
+ // The mark the validation half leaves on the process when it is installed
56
+ // (`validation.js`): a schema whose classes have no validation where the
57
+ // mark is there is one of another copy of the package.
58
+ const VALIDATION = Symbol.for('alexify.metaschema.validation');
59
+
60
+ // A schema of `./definition` asked to validate before the core entry was
61
+ // loaded: the half of the core that validates is not installed into its
62
+ // classes, because the core is not loaded, or is loaded from another copy
63
+ // of the package (two versions installed side by side, a bundle with two).
64
+ const noValidation = (what) => {
65
+ const elsewhere = globalThis[VALIDATION] === true;
66
+ const reason = elsewhere
67
+ ? 'the core entry loaded is another copy of the package than the one that built the ' +
68
+ 'schema (deduplicate @alexify/metaschema)'
69
+ : './definition alone does not validate';
70
+ const error = new TypeError(`${what} needs the core entry @alexify/metaschema: ${reason}`);
71
+ error.code = 'ERR_NOT_REGISTERED';
72
+ error.method = what;
73
+ return error;
74
+ };
75
+
55
76
  const shown = (value) =>
56
77
  typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
57
78
 
@@ -69,5 +90,7 @@ module.exports = {
69
90
  asyncReturn,
70
91
  invalidTarget,
71
92
  notRegistered,
93
+ noValidation,
94
+ VALIDATION,
72
95
  invalidOption,
73
96
  };
@@ -55,6 +55,10 @@ const KNOWN = new Set([
55
55
  'json',
56
56
  ]);
57
57
 
58
+ // The steps `multipleOf` writes for a number of 0 to 15 decimals, by count.
59
+ const DECIMALS = [];
60
+ for (let count = 0; count <= 15; count += 1) DECIMALS.push(10 ** -count);
61
+
58
62
  // How deep a document may nest: past it the conversion stops whatever the
59
63
  // mode, since a lenient conversion must not recurse without end either.
60
64
  const MAX_DEPTH = 128;
@@ -265,6 +269,11 @@ const typed = (context, node, type, used) => {
265
269
  def.format = name;
266
270
  if (def.pattern === FORMATS[name].pattern) delete def.pattern;
267
271
  }
272
+ // Base64 text (what `bytes` exports as) is the base64 format when the
273
+ // formats are registered, as OpenAPI's `byte` is.
274
+ if (def.format === undefined && node.contentEncoding === 'base64' && FORMATS.base64) {
275
+ def.format = 'base64';
276
+ }
268
277
  return def;
269
278
  }
270
279
  if (type === 'number' || type === 'integer') {
@@ -272,6 +281,11 @@ const typed = (context, node, type, used) => {
272
281
  const max = take('maximum');
273
282
  if (min !== undefined) def.min = min;
274
283
  if (max !== undefined) def.max = max;
284
+ // A multiple of 10⁻ⁿ is a number of n decimals and 1 says nothing more
285
+ // of an integer; any other step is a keyword outside the subset.
286
+ const decimals = DECIMALS.indexOf(node.multipleOf);
287
+ if (type === 'integer' ? node.multipleOf === 1 : decimals !== -1) take('multipleOf');
288
+ if (type === 'number' && decimals !== -1) def.decimals = decimals;
275
289
  return def;
276
290
  }
277
291
  if (type === 'array') {
@@ -6,7 +6,7 @@
6
6
  // programs that want the methods.
7
7
  const { hasBrand } = require('../util.js');
8
8
  const { invalidTarget } = require('../errors.js');
9
- const { Schema } = require('../schema.js');
9
+ const { Schema } = require('../validation.js');
10
10
  const { Model } = require('../model.js');
11
11
  const { writeFile } = require('../runtime/node.js');
12
12
  const generators = require('./jsonschema.js');
@@ -248,6 +248,18 @@ const dictionary = (field, context) => {
248
248
  return json;
249
249
  };
250
250
 
251
+ // A flags value: a boolean per name, every one optional (all of them
252
+ // under the strict profile, which lists every property as required), no
253
+ // other key when the document is closed.
254
+ const flags = (field, context) => {
255
+ const properties = {};
256
+ for (const name of field.flags) define(properties, name, typed('boolean', context));
257
+ const json = { [context.key]: 'object', properties };
258
+ if (context.strict) json.required = field.flags.slice();
259
+ if (context.closed) json.additionalProperties = false;
260
+ return json;
261
+ };
262
+
251
263
  const isJSON = (value) =>
252
264
  value === null || (typeof value !== 'object' && typeof value !== 'bigint');
253
265
 
@@ -316,16 +328,17 @@ const reference = (field, context) => {
316
328
  } else if (!embeds(target, field.embed, context.references)) {
317
329
  json = id;
318
330
  } else {
319
- json = definition(target, context);
331
+ json = definition(target, name, context);
320
332
  }
321
333
  return field.many === undefined ? json : { [context.key]: 'array', items: json };
322
334
  };
323
335
 
324
- // A referenced entity: `#` for the root of the document, a `$ref` into the
325
- // definitions (rendered once) otherwise, and inline where the target has no
326
- // `$ref` (mongodb), where a cycle has no form.
327
- const definition = (schema, context) => {
328
- const { name } = schema;
336
+ // A referenced entity, under the name the reference reached it through (an
337
+ // anonymous schema of a model is the entity of the name the model gives
338
+ // it): `#` for the root of the document, a `$ref` into the definitions
339
+ // (rendered once) otherwise, and inline where the target has no `$ref`
340
+ // (mongodb), where a cycle has no form.
341
+ const definition = (schema, name, context) => {
329
342
  if (context.prefix === null) {
330
343
  if (context.stack.has(name)) return unrepresentable(context, `Recursive reference "${name}"`);
331
344
  context.stack.add(name);
@@ -358,7 +371,13 @@ const RENDER = Object.assign(Object.create(null), {
358
371
  }
359
372
  return json;
360
373
  },
361
- number: (field, context) => ranged(typed('number', context), field, context),
374
+ // A number of `n` decimals is a multiple of 10⁻ⁿ (a validator that
375
+ // divides may disagree with `check` on the last bit of a sum).
376
+ number: (field, context) => {
377
+ const json = ranged(typed('number', context), field, context);
378
+ if (field.decimals !== undefined && !context.strict) json.multipleOf = 10 ** -field.decimals;
379
+ return json;
380
+ },
362
381
  integer: (field, context) => ranged(typed('integer', context), field, context),
363
382
  bigint: (field, context) =>
364
383
  context.mongo ? typed('bigint', context) : unrepresentable(context, 'Type "bigint"'),
@@ -368,6 +387,24 @@ const RENDER = Object.assign(Object.create(null), {
368
387
  if (context.input) return { type: 'string', format: 'date-time' };
369
388
  return unrepresentable(context, 'Type "date" (output)');
370
389
  },
390
+ // Binary data is base64 text on a JSON wire (the input `./coerce` reads
391
+ // back) and binData in MongoDB; the Uint8Array parse gives is no JSON. The
392
+ // length of the text bounds the bytes: four characters for every three
393
+ // started (a text that long may decode to two bytes more than `max`).
394
+ bytes: (field, context) => {
395
+ if (context.mongo) return typed('binData', context);
396
+ if (!context.input) return unrepresentable(context, 'Type "bytes" (output)');
397
+ if (context.strict) return typed('string', context);
398
+ const json =
399
+ context.target.byte === true
400
+ ? { type: 'string', format: 'byte' }
401
+ : { type: 'string', contentEncoding: 'base64' };
402
+ const { length } = field;
403
+ if (length?.min !== undefined) json.minLength = 4 * Math.ceil(length.min / 3);
404
+ if (length?.max !== undefined) json.maxLength = 4 * Math.ceil(length.max / 3);
405
+ return json;
406
+ },
407
+ flags,
371
408
  null: (field, context) => typed('null', context),
372
409
  any: (field, context) => unconstrained(context, 'any') || {},
373
410
  unknown: (field, context) => unconstrained(context, 'unknown') || {},