@alexify/metaschema 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +314 -1
  2. package/README.md +535 -20
  3. package/SECURITY.md +26 -7
  4. package/index.d.ts +496 -2
  5. package/package.json +53 -5
  6. package/src/codec.js +239 -74
  7. package/src/coerce/index.d.ts +34 -0
  8. package/src/coerce/index.js +352 -0
  9. package/src/compile/code.js +1 -1
  10. package/src/compile/emit.js +32 -7
  11. package/src/compile/index.d.ts +6 -0
  12. package/src/compile/index.js +12 -1
  13. package/src/context.js +11 -10
  14. package/src/derive/index.d.ts +86 -0
  15. package/src/derive/index.js +266 -0
  16. package/src/errors.js +28 -1
  17. package/src/formats/index.d.ts +31 -0
  18. package/src/formats/index.js +557 -0
  19. package/src/generators/fromjsonschema.js +16 -14
  20. package/src/generators/index.js +2 -1
  21. package/src/generators/jsonschema.js +47 -13
  22. package/src/issues.js +37 -20
  23. package/src/kinds.js +11 -2
  24. package/src/lint.js +24 -0
  25. package/src/locales/en.js +11 -2
  26. package/src/locales/uk.js +10 -2
  27. package/src/metadata.js +7 -2
  28. package/src/model/data.js +17 -0
  29. package/src/model/diff.js +1 -0
  30. package/src/model/index.d.ts +14 -2
  31. package/src/model/index.js +13 -10
  32. package/src/model/infer.js +483 -0
  33. package/src/model/merge.js +10 -6
  34. package/src/model/restore.js +3 -3
  35. package/src/model/sample.js +8 -5
  36. package/src/model.js +34 -4
  37. package/src/mongodb/bson.js +118 -0
  38. package/src/mongodb/document.js +209 -0
  39. package/src/mongodb/index.d.ts +133 -0
  40. package/src/mongodb/index.js +24 -0
  41. package/src/mongodb/indexes.js +79 -0
  42. package/src/mongodb/update.js +258 -0
  43. package/src/preprocessor.js +1 -0
  44. package/src/prototypes/abstract.js +9 -3
  45. package/src/prototypes/collections.js +4 -3
  46. package/src/prototypes/scalars.js +4 -4
  47. package/src/prototypes/union.js +2 -2
  48. package/src/result.js +6 -0
  49. package/src/rules.js +53 -4
  50. package/src/schema.js +53 -28
  51. package/src/snapshot.js +1 -1
  52. package/src/stream/index.d.ts +68 -0
  53. package/src/stream/index.js +247 -0
  54. package/src/struct.js +1 -1
  55. package/src/types.js +33 -1
  56. package/src/util.js +18 -0
@@ -0,0 +1,266 @@
1
+ // The `./derive` subpath: schemas made from a schema. A subset of its fields
2
+ // (`pick`, `omit`), its fields optional or required (`partial`, `required`),
3
+ // fields of its own over the ones it has (`extend`), the names of its fields
4
+ // as an enum (`keyof`). The result is a new Schema built from the definition
5
+ // the source was built from (what `merge` of the `./model` subpath reads
6
+ // too), so the source is never touched and every rule of a field comes along.
7
+ // `register()` installs the functions as methods of Schema, so they chain.
8
+ const { hasBrand, define, formatters } = require('../util.js');
9
+ const { isFirstUpper, firstKey } = require('../metautil.js');
10
+ const { Schema } = require('../schema.js');
11
+ const { isStruct } = require('../struct.js');
12
+ const { idFieldOf } = require('../kinds.js');
13
+ const { SchemaDefinitionError, invalidTarget, invalidOption } = require('../errors.js');
14
+ const { structDefinitionOf, metadataOf, structDefinition, atSchema } = require('../model/data.js');
15
+
16
+ // The functions of a nested struct that are its own: written for the whole
17
+ // struct, they do not hold for a part of it.
18
+ const CODECS = ['validate', 'parse', 'serialize'];
19
+
20
+ const sourceOf = (schema) => {
21
+ if (!hasBrand(schema, 'Schema') || !isStruct(schema.fields)) {
22
+ throw invalidTarget('A Schema of a struct is expected');
23
+ }
24
+ return schema;
25
+ };
26
+
27
+ // The options of a call are the call's (ERR_INVALID_OPTION); the metadata
28
+ // among them is a definition, and a wrong one is a definition error.
29
+ const optionsOf = (options = {}) => {
30
+ if (options === null || typeof options !== 'object') {
31
+ throw invalidOption('options', 'an object', options);
32
+ }
33
+ const { metadata } = options;
34
+ if (metadata !== undefined && (metadata === null || typeof metadata !== 'object')) {
35
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Option "metadata" must be an object');
36
+ }
37
+ return options;
38
+ };
39
+
40
+ // The id field a stored kind adds, which goes with the kind unless a call
41
+ // names it.
42
+ const idOf = idFieldOf;
43
+
44
+ const isStored = (schema) => idFieldOf(schema) !== null;
45
+
46
+ // The names a call gives, each a field (or a calculated field) of the
47
+ // schema; one it does not have is located in it.
48
+ const namesOf = (schema, keys) => {
49
+ if (!Array.isArray(keys)) throw invalidOption('keys', 'a list of field names', keys);
50
+ const names = new Set();
51
+ for (const key of keys) {
52
+ if (typeof key !== 'string') throw invalidOption('keys', 'a list of field names', keys);
53
+ if (!(key in schema.fields)) {
54
+ throw new SchemaDefinitionError('ERR_UNKNOWN_FIELD', 'No such field').locate(
55
+ schema.name,
56
+ key,
57
+ );
58
+ }
59
+ names.add(key);
60
+ }
61
+ return names;
62
+ };
63
+
64
+ // A stored kind or a projection is a struct in what is derived from it: the
65
+ // first would add its id again and the second copy its parent's fields over
66
+ // the ones derived. A memory kind keeps its metadata.
67
+ const kindOf = (schema) => {
68
+ const { kind, unknown } = schema;
69
+ if (kind === 'projection' || isStored(schema)) return { kind: 'struct', unknown };
70
+ return metadataOf(schema);
71
+ };
72
+
73
+ // The definitions of the fields, fresh objects a call may change: the id of
74
+ // a stored kind is left out unless `names` has it.
75
+ const fieldsOf = (schema, names) => {
76
+ const fields = structDefinitionOf(schema.fields);
77
+ const id = idOf(schema);
78
+ if (id !== null && (names === null || !names.has(id))) delete fields[id];
79
+ return fields;
80
+ };
81
+
82
+ // The fields, then the indexes whose columns are all among them (a `many`
83
+ // entry is the field's own), then, with `functions`, the schema's own
84
+ // validate, parse, serialize and format.
85
+ const bodyOf = (schema, fields, functions) => {
86
+ for (const key in schema.indexes) {
87
+ const index = schema.indexes[key];
88
+ if (index.many !== undefined) continue;
89
+ let kept = true;
90
+ for (const column of index.index || index.primary || index.unique) {
91
+ if (!Object.hasOwn(fields, column)) kept = false;
92
+ }
93
+ if (kept) define(fields, key, index);
94
+ }
95
+ if (functions) {
96
+ for (const key in schema.options) {
97
+ const option = schema.options[key];
98
+ if (option !== null) define(fields, key, option);
99
+ }
100
+ }
101
+ return fields;
102
+ };
103
+
104
+ const build = (schema, options, body, namespaces) => {
105
+ const { name = schema.name, metadata } = options;
106
+ const definition = structDefinition(kindOf(schema), metadata, body);
107
+ return new Schema(name, definition, Array.from(namespaces));
108
+ };
109
+
110
+ const select = (schema, keys, options, keep) => {
111
+ sourceOf(schema);
112
+ const settings = optionsOf(options);
113
+ const names = namesOf(schema, keys);
114
+ const all = fieldsOf(schema, keep ? names : null);
115
+ const fields = {};
116
+ for (const key of Object.keys(all)) {
117
+ if (names.has(key) === keep) define(fields, key, all[key]);
118
+ }
119
+ return build(schema, settings, bodyOf(schema, fields, false), schema.namespaces);
120
+ };
121
+
122
+ // The fields named, in the order of the schema.
123
+ const pick = (schema, keys, options) => select(schema, keys, options, true);
124
+
125
+ // Every field but the ones named.
126
+ const omit = (schema, keys, options) => select(schema, keys, options, false);
127
+
128
+ const isNestedStruct = (def) => def.type === 'schema' && typeof def.schema.type !== 'string';
129
+
130
+ // A field made optional loses its default (a patch leaves a missing key as
131
+ // it is stored), unless `defaults`; `deep` goes on into the fields of a
132
+ // nested struct, whose own functions an optional struct loses.
133
+ const settle = (def, required, deep, defaults) => {
134
+ def.required = required;
135
+ if (!required && !defaults) delete def.default;
136
+ if (!deep || !isNestedStruct(def)) return;
137
+ const fields = def.schema;
138
+ for (const key of Object.keys(fields)) {
139
+ const nested = fields[key];
140
+ if (typeof nested !== 'function') settle(nested, required, deep, defaults);
141
+ }
142
+ if (required) return;
143
+ for (const key of CODECS) {
144
+ delete def[key];
145
+ delete fields[key];
146
+ }
147
+ };
148
+
149
+ const toggle = (schema, options, required) => {
150
+ sourceOf(schema);
151
+ const settings = optionsOf(options);
152
+ const { keys, deep = false, defaults = false } = settings;
153
+ const names = keys === undefined ? null : namesOf(schema, keys);
154
+ const fields = fieldsOf(schema, names);
155
+ for (const key of Object.keys(fields)) {
156
+ const def = fields[key];
157
+ if (typeof def === 'function') continue;
158
+ if (names === null || names.has(key)) settle(def, required, deep, defaults);
159
+ }
160
+ return build(schema, settings, bodyOf(schema, fields, required), schema.namespaces);
161
+ };
162
+
163
+ // Every field (or the ones in `options.keys`) optional. The schema's own
164
+ // functions, written for a whole value, do not come along.
165
+ const partial = (schema, options) => toggle(schema, options, false);
166
+
167
+ // Every field (or the ones in `options.keys`) required.
168
+ const required = (schema, options) => toggle(schema, options, true);
169
+
170
+ // The extension's fields over the schema's: one of the same name takes the
171
+ // place of the schema's (`'age?'` replaces `age`), the others come after.
172
+ // Not a unification: `merge` of the `./model` subpath is that.
173
+ const extend = (schema, extension, options) => {
174
+ sourceOf(schema);
175
+ const settings = optionsOf(options);
176
+ let additions = extension;
177
+ let namespaces = schema.namespaces;
178
+ if (hasBrand(extension, 'Schema')) {
179
+ sourceOf(extension);
180
+ additions = bodyOf(extension, fieldsOf(extension, null), true);
181
+ namespaces = new Set([...schema.namespaces, ...extension.namespaces]);
182
+ } else if (extension === null || typeof extension !== 'object' || Array.isArray(extension)) {
183
+ 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);
187
+ }
188
+ const keys = new Map();
189
+ for (const key of Object.keys(additions)) keys.set(formatters.key(key).field, key);
190
+ const base = bodyOf(schema, fieldsOf(schema, null), true);
191
+ const body = {};
192
+ const placed = new Set();
193
+ for (const key of Object.keys(base)) {
194
+ const own = keys.get(key);
195
+ if (own === undefined) define(body, key, base[key]);
196
+ else if (!placed.has(own)) {
197
+ define(body, own, additions[own]);
198
+ placed.add(own);
199
+ }
200
+ }
201
+ for (const key of Object.keys(additions)) {
202
+ if (!placed.has(key)) define(body, key, additions[key]);
203
+ }
204
+ return build(schema, settings, body, namespaces);
205
+ };
206
+
207
+ // The names of the fields a value carries, as a schema of an enum: the
208
+ // calculated fields and the id of a stored kind are not among them.
209
+ const keyof = (schema, options) => {
210
+ sourceOf(schema);
211
+ const { name = schema.name, metadata } = optionsOf(options);
212
+ if (metadata !== undefined) {
213
+ const reason = 'keyof takes a name only: a schema of an enum has no kind';
214
+ throw atSchema(new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason), schema.name);
215
+ }
216
+ const id = idOf(schema);
217
+ const names = [];
218
+ for (const key in schema.fields) {
219
+ if (key !== id && hasBrand(schema.fields[key], 'Type')) names.push(key);
220
+ }
221
+ return new Schema(name, { enum: names }, Array.from(schema.namespaces));
222
+ };
223
+
224
+ // Installed like class members: not enumerable. A copy per subpath rather
225
+ // than a helper of the core: the core is measured on its own, the subpaths
226
+ // on top of it.
227
+ const install = (target, members) => {
228
+ const descriptors = Object.getOwnPropertyDescriptors(members);
229
+ for (const name in descriptors) {
230
+ descriptors[name].enumerable = false;
231
+ Object.defineProperty(target, name, descriptors[name]);
232
+ }
233
+ };
234
+
235
+ let registered = false;
236
+
237
+ // Adds `schema.pick(keys, options)`, `schema.omit(keys, options)`,
238
+ // `schema.partial(options)`, `schema.required(options)`,
239
+ // `schema.extend(extension, options)` and `schema.keyof(options)`. Once per
240
+ // process.
241
+ const register = () => {
242
+ if (registered) return;
243
+ registered = true;
244
+ install(Schema.prototype, {
245
+ pick(keys, options) {
246
+ return pick(this, keys, options);
247
+ },
248
+ omit(keys, options) {
249
+ return omit(this, keys, options);
250
+ },
251
+ partial(options) {
252
+ return partial(this, options);
253
+ },
254
+ required(options) {
255
+ return required(this, options);
256
+ },
257
+ extend(extension, options) {
258
+ return extend(this, extension, options);
259
+ },
260
+ keyof(options) {
261
+ return keyof(this, options);
262
+ },
263
+ });
264
+ };
265
+
266
+ module.exports = { pick, omit, partial, required, extend, keyof, register };
package/src/errors.js CHANGED
@@ -43,4 +43,31 @@ const invalidTarget = (message) => {
43
43
  return error;
44
44
  };
45
45
 
46
- module.exports = { SchemaDefinitionError, asyncReturn, invalidTarget };
46
+ // A call that needs what `register()` of a subpath installs (the converters
47
+ // of coercion, the module of the mongodb driver) before that ran: the
48
+ // program is wired wrong, not a value or a definition.
49
+ const notRegistered = (what, where) => {
50
+ const error = new TypeError(`${what} needs register() of @alexify/metaschema/${where} first`);
51
+ error.code = 'ERR_NOT_REGISTERED';
52
+ return error;
53
+ };
54
+
55
+ const shown = (value) =>
56
+ typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
57
+
58
+ // An option of a call that is not what it must be (`maxErrors`, the options
59
+ // of the stream subpath): a TypeError naming it, with a code of its own, as
60
+ // invalidTarget is.
61
+ const invalidOption = (name, expected, value) => {
62
+ const error = new TypeError(`${name} must be ${expected}, got ${shown(value)}`);
63
+ error.code = 'ERR_INVALID_OPTION';
64
+ return error;
65
+ };
66
+
67
+ module.exports = {
68
+ SchemaDefinitionError,
69
+ asyncReturn,
70
+ invalidTarget,
71
+ notRegistered,
72
+ invalidOption,
73
+ };
@@ -0,0 +1,31 @@
1
+ // A format a string field may name: a test over the string, the examples
2
+ // `sample` draws, whether `infer` may read the format out of data (true
3
+ // unless said otherwise; a format ordinary words pass says false), and the
4
+ // pattern the JSON Schema export writes beside the name (a string that
5
+ // compiles in unicode mode, a shape that never rejects what `test` accepts).
6
+ export interface FormatDefinition {
7
+ test: (value: string) => boolean;
8
+ examples: readonly string[];
9
+ infer?: boolean;
10
+ pattern?: string;
11
+ }
12
+
13
+ // The formats registered so far, by name: empty until `register()` ran. Read
14
+ // it; `register()` writes it.
15
+ export const FORMATS: { readonly [name: string]: Readonly<FormatDefinition> | undefined };
16
+
17
+ // Registers the 35 built-in formats (the identifiers `uuid`, `ulid`, `jwt`,
18
+ // `nanoid`, `cuid2`; the dates and times `date-time`, `iso-date-time`,
19
+ // `date`, `time`, `iso-time`, `duration`; the network forms `email`,
20
+ // `ipv4`, `cidrv4`, `ipv6`, `cidrv6`, `mac`, `url`, `uri`, `hostname`; the
21
+ // formats of JSON Schema `uri-reference`, `uri-template`, `json-pointer`,
22
+ // `relative-json-pointer`, `regex`; and `e164`, `iban`, `hex-color`,
23
+ // `base64`, `base64url`, `hex`, `emoji`, `semver`, `slug`, `credit-card`)
24
+ // and the program's own, once per name and process-wide, like the type
25
+ // registry: a name registered again with the same test is nothing, with
26
+ // another test `ERR_FORMAT_REGISTERED`, and an entry that is not a format
27
+ // `ERR_INVALID_FORMAT`. The program's own format under the name of a
28
+ // built-in one takes its place, and the call returns the names of the
29
+ // built-in formats it replaced (an empty list otherwise); the schemas built
30
+ // before keep the built-in test.
31
+ export function register(custom?: Record<string, FormatDefinition>): string[];