@alexify/metaschema 3.3.0 → 3.4.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 (53) hide show
  1. package/CHANGELOG.md +186 -1
  2. package/README.md +24 -16
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +224 -28
  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 +15 -8
  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 +4 -1
  22. package/src/lint.js +15 -1
  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 +50 -10
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +10 -3
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +52 -7
  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 +1 -2
  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 +0 -26
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +105 -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 +24 -6
  52. package/src/util.js +43 -0
  53. package/src/validation.js +313 -0
package/src/schema.js CHANGED
@@ -1,101 +1,46 @@
1
- const { isFirstUpper } = require('./metautil.js');
2
-
3
- const { BRAND, INSPECT, RUN, HOOK, hasBrand } = require('./util.js');
4
- const { createContext } = require('./context.js');
1
+ const {
2
+ BRAND,
3
+ INSPECT,
4
+ RUN,
5
+ HOOK,
6
+ TRACKED,
7
+ COERCES,
8
+ CODEC,
9
+ STANDARD,
10
+ hasBrand,
11
+ } = require('./util.js');
5
12
  const { TYPES } = require('./types.js');
6
13
  const { Preprocessor } = require('./preprocessor.js');
7
14
  const { SchemaMetadata } = require('./metadata.js');
8
- const { ValidationResult } = require('./result.js');
9
- const { finalize, runValidate, settle, release } = require('./issues.js');
10
- const { SchemaDefinitionError } = require('./errors.js');
11
- const { createStruct, isStruct, checkOf } = require('./struct.js');
12
- const { warning, lintSchema } = require('./lint.js');
13
- const {
14
- PREPARE,
15
- FINISH,
16
- SERIALIZE,
17
- COERCE,
18
- infoOf,
19
- apply,
20
- looped,
21
- hasAsync,
22
- wantOf,
23
- } = require('./codec.js');
24
-
25
- // The validation of a schema inside an existing context: `check` starts one,
26
- // and a reference field checks its target entity within the context of the
27
- // outer check, so the error limit and the cycle detection span the whole
28
- // value. The schema-level validate runs last, and only on a value whose
29
- // fields all passed, so it can rely on their shape. Built once per schema,
30
- // as Schema[RUN].
31
- const compileSchema = (schema) => {
32
- const { fields, options } = schema;
33
- const run = isStruct(fields) ? checkOf(fields) : fields.check;
34
- return (value, context, key) => {
35
- const before = context.count;
36
- run(value, context, key);
37
- const { validate } = options;
38
- if (validate && context.count === before) {
39
- const nested = key !== undefined;
40
- if (nested) context.path.push(key);
41
- runValidate(schema, validate, value, context);
42
- if (nested) context.path.pop();
43
- }
15
+ const { SchemaDefinitionError, noValidation } = require('./errors.js');
16
+ const { createStruct } = require('./struct.js');
17
+ const { BUILD } = require('./prototypes/abstract.js');
18
+ const { schemaSnapshotOf } = require('./snapshot.js');
19
+
20
+ // The check of a schema until it is first used: it builds the closures
21
+ // (`BUILD.schema`, the validation half's), takes their place and runs them.
22
+ // A schema built to be read (rendered, written as a snapshot) never builds
23
+ // them; one the JIT replaced before its first use (`register()` of
24
+ // `./compile`) is not touched.
25
+ const lazyRun = (schema) => {
26
+ const run = (value, context, key) => {
27
+ const check = BUILD.schema(schema);
28
+ if (schema[RUN] === run) schema[RUN] = check;
29
+ return check(value, context, key);
44
30
  };
31
+ return run;
45
32
  };
46
33
 
47
- const resultOf = (context) => {
48
- finalize(context.issues, context.messages);
49
- return new ValidationResult(context);
50
- };
51
-
52
- // What parse returns: the output only for a valid value, the issues always.
53
- const parsed = (context, output) => {
54
- finalize(context.issues, context.messages);
55
- const valid = context.count === 0;
56
- return { valid, value: valid ? output : undefined, issues: context.issues };
57
- };
58
-
59
- // The result of parse read as Standard Schema does.
60
- const standardize = (result) =>
61
- result.valid ? { value: result.value } : { issues: result.issues };
62
-
63
- // The walk of an async check: a throw out of it (a getter of the value that
64
- // throws, the engine's limit on a pattern) leaves the promises the walk
65
- // queued observed, so that none of them rejects unhandled.
66
- const walkAsync = (schema, value, context) => {
67
- try {
68
- schema[RUN](value, context);
69
- } catch (error) {
70
- release(context.async, 0);
71
- throw error;
72
- }
73
- };
74
-
34
+ // The half of the core that builds a schema and reads it: its fields and
35
+ // metadata, its JSON and its snapshot. The validation half (`validation.js`,
36
+ // which the core entry loads) installs `check`, `parse`, `serialize` and
37
+ // their kin, `~standard` and the warnings of the lint on this class; until
38
+ // then they say so (`./definition` alone).
75
39
  class Schema extends SchemaMetadata {
76
40
  // The merged type table of the attached namespaces, rebuilt only when they
77
41
  // change.
78
42
  #types = null;
79
43
 
80
- // Whether the root value joins the cycle detection (`context.source`):
81
- // only a struct with references can reach it again.
82
- #tracked = false;
83
-
84
- // The lint of the definition, run on first use: a schema built in a hot
85
- // path never pays for it.
86
- #warnings = null;
87
-
88
- // The Standard Schema props, built on first use.
89
- #standard = null;
90
-
91
- // What the passes of parse and serialize know about the schema, on first use.
92
- #codec = null;
93
-
94
- // Whether parse coerces the input unless the call says otherwise: the
95
- // `coerce` of the kind metadata, read once (an own property would shadow
96
- // the method the `./coerce` subpath installs).
97
- #coerce = false;
98
-
99
44
  static from(source, namespaces) {
100
45
  return new Schema('', source, namespaces);
101
46
  }
@@ -134,44 +79,20 @@ class Schema extends SchemaMetadata {
134
79
  const combined = { ...fields, ...extras };
135
80
  this.fields = createStruct(combined, preprocessor);
136
81
  }
137
- this.#tracked = isSchemaType && this.relations.size > 0;
138
- this.#coerce = Object.hasOwn(this.custom, 'coerce') && this.custom.coerce === true;
139
- this[RUN] = compileSchema(this);
82
+ // What the validation half reads (util.js): whether the root value joins
83
+ // the cycle detection (only a struct with references can reach it
84
+ // again), whether parse coerces unless the call says otherwise (the
85
+ // `coerce` of the kind metadata, read once: an own property would shadow
86
+ // the method the `./coerce` subpath installs), and its caches.
87
+ this[TRACKED] = isSchemaType && this.relations.size > 0;
88
+ this[COERCES] = Object.hasOwn(this.custom, 'coerce') && this.custom.coerce === true;
89
+ this[CODEC] = null;
90
+ this[STANDARD] = null;
91
+ this[RUN] = lazyRun(this);
140
92
  const hook = Schema[HOOK];
141
93
  if (hook !== undefined) hook(this);
142
94
  }
143
95
 
144
- // What is not wrong enough to throw: `Warning [code]: text` strings.
145
- get warnings() {
146
- if (this.#warnings === null) this.#warnings = lintSchema(this);
147
- return this.#warnings;
148
- }
149
-
150
- // Standard Schema v1 (https://standardschema.dev): the interface tRPC,
151
- // TanStack Form, Hono and the other consumers of the specification validate
152
- // through. `validate` is `parse` with the policies of the schema: the value
153
- // that comes back has the defaults and the decoders applied (the value
154
- // itself when there was nothing to apply), and the issues of an invalid one
155
- // are the result's own (a message and a path of keys each). A schema with
156
- // an async validator or decoder validates through parseAsync, as the
157
- // specification allows. The vendor-specific `libraryOptions` of a call are
158
- // the options of `parse`. An accessor of the prototype stays out of toJSON,
159
- // inspect and Object.keys, and `validate` closes over the schema because a
160
- // consumer calls it unbound. The `./generators` subpath adds the
161
- // `jsonSchema` converter of Standard JSON Schema to the props.
162
- get '~standard'() {
163
- if (this.#standard === null) {
164
- const async = hasAsync(this);
165
- const validate = (value, options) => {
166
- const libraryOptions = options == null ? undefined : options.libraryOptions;
167
- if (async) return this.parseAsync(value, libraryOptions).then(standardize);
168
- return standardize(this.parse(value, libraryOptions));
169
- };
170
- this.#standard = { version: 1, vendor: 'alexify.metaschema', validate };
171
- }
172
- return this.#standard;
173
- }
174
-
175
96
  get types() {
176
97
  if (this.namespaces.size === 0) return TYPES;
177
98
  if (this.#types === null) {
@@ -182,121 +103,16 @@ class Schema extends SchemaMetadata {
182
103
  return this.#types;
183
104
  }
184
105
 
185
- // The warnings that need the namespaces: references and types that do
186
- // not resolve.
187
- checkConsistency() {
188
- const warn = [];
189
- const { name, references } = this;
190
- for (const ref of references) {
191
- if (isFirstUpper(ref)) {
192
- const entity = this.findReference(ref);
193
- if (!entity) {
194
- warn.push(warning('missing-reference', `"${ref}" referenced by "${name}" is not found`));
195
- }
196
- } else if (!this.types[ref]) {
197
- warn.push(warning('missing-type', `type "${ref}" is not found in "${name}"`));
198
- }
199
- }
200
- return warn;
201
- }
202
-
106
+ // An entity of the attached models, else the schema itself: a schema that
107
+ // names itself (`parent: '?Category'`) needs no model. The models come
108
+ // first, so a schema with the name of one of their entities (a schema
109
+ // derived from it keeps the name) still reaches that entity.
203
110
  findReference(name) {
204
111
  for (const ns of this.namespaces) {
205
112
  const entity = ns.entities.get(name);
206
113
  if (entity) return entity;
207
114
  }
208
- return null;
209
- }
210
-
211
- // Validates a value: every problem is collected as an issue, and the result
212
- // never throws because of the value. `options`: root (the label of the
213
- // error lines, the schema name by default), maxErrors, unknown ('reject'
214
- // or 'ignore' keys the schema does not have), references, messages (a
215
- // locale). A validator that returns a promise is an error here.
216
- // `createContext` is called directly in every method here, never through a
217
- // helper: V8 inlines the allocation into `check` that way (the context is
218
- // the one allocation of a valid check), and a method in between cost 7%.
219
- check(source, options) {
220
- const context = createContext(options, this.name, this.unknown);
221
- if (this.#tracked) context.source = source;
222
- this[RUN](source, context);
223
- return resultOf(context);
224
- }
225
-
226
- // The same check, with the validators that return a promise in flight
227
- // together and settled after the walk, in field order.
228
- async checkAsync(source, options) {
229
- const context = createContext(options, this.name, this.unknown);
230
- context.async = [];
231
- if (this.#tracked) context.source = source;
232
- walkAsync(this, source, context);
233
- if (context.async.length > 0) await settle(context);
234
- return resultOf(context);
235
- }
236
-
237
- #pass(phase, source, context, extra) {
238
- if (this.#codec === null) this.#codec = infoOf(this);
239
- const want = wantOf(phase, context) | extra;
240
- return apply(this.#codec, this, source, context, undefined, phase, want);
241
- }
242
-
243
- // Validates a value and builds the value of the program from it: the input
244
- // coerced (when the call, else the schema, asks for it) and the defaults
245
- // filled in, the check, and on a valid value `unknown: 'strip'`, the
246
- // decoders of its fields (the parts of a value before the value) and the
247
- // schema's own `parse`. `{ valid, value, issues }`: the value is undefined
248
- // when invalid, and the value given when there was nothing to apply; the
249
- // value given is never written to. The objects met before the check are
250
- // not the check's, and a value that loops through its references is
251
- // checked as it was given. The pass before the check is written out here
252
- // and in parseAsync, not in a method of its own: with coercion such a
253
- // method no longer fit the bytecode V8 inlines into parse, and the call
254
- // cost the JIT backend 13%.
255
- parse(source, options) {
256
- const context = createContext(options, this.name, this.unknown, true);
257
- const own = options === undefined ? undefined : options.coerce;
258
- const coerce = own === undefined ? this.#coerce : own;
259
- const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
260
- const value = looped(context) ? source : prepared;
261
- context.seen = null;
262
- if (this.#tracked) context.source = value;
263
- this[RUN](value, context);
264
- const output = context.count === 0 ? this.#pass(FINISH, value, context, 0) : undefined;
265
- return parsed(context, output);
266
- }
267
-
268
- async parseAsync(source, options) {
269
- const context = createContext(options, this.name, this.unknown, true);
270
- context.async = [];
271
- const own = options === undefined ? undefined : options.coerce;
272
- const coerce = own === undefined ? this.#coerce : own;
273
- const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
274
- const value = looped(context) ? source : prepared;
275
- context.seen = null;
276
- if (this.#tracked) context.source = value;
277
- walkAsync(this, value, context);
278
- if (context.async.length > 0) await settle(context);
279
- let output;
280
- if (context.count === 0) {
281
- // Only a promise of the pass is awaited: a thenable in the value is data.
282
- output = this.#pass(FINISH, value, context, 0);
283
- if (output instanceof Promise) output = (await output).value;
284
- }
285
- return parsed(context, output);
286
- }
287
-
288
- // The other direction: the schema's own `serialize`, then the serializers
289
- // of the fields, from the value down to its parts. `{ value }`, or with
290
- // `options.check` the verdict of `check` over the result as well.
291
- serialize(source, options) {
292
- const context = createContext(options, this.name, this.unknown);
293
- const value = this.#pass(SERIALIZE, source, context, 0);
294
- if (options === undefined || options.check !== true) return { value };
295
- context.seen = null;
296
- if (this.#tracked) context.source = value;
297
- this[RUN](value, context);
298
- finalize(context.issues, context.messages);
299
- return { valid: context.count === 0, value, issues: context.issues };
115
+ return name === this.name && name !== '' ? this : null;
300
116
  }
301
117
 
302
118
  // The types and the Standard Schema props depend on the namespaces (the
@@ -305,13 +121,13 @@ class Schema extends SchemaMetadata {
305
121
  attach(...namespaces) {
306
122
  for (const ns of namespaces) this.namespaces.add(ns);
307
123
  this.#types = null;
308
- this.#standard = null;
124
+ this[STANDARD] = null;
309
125
  }
310
126
 
311
127
  detach(...namespaces) {
312
128
  for (const ns of namespaces) this.namespaces.delete(ns);
313
129
  this.#types = null;
314
- this.#standard = null;
130
+ this[STANDARD] = null;
315
131
  }
316
132
 
317
133
  toString() {
@@ -323,12 +139,68 @@ class Schema extends SchemaMetadata {
323
139
  return hasBrand(fields, 'Struct') ? { ...fields } : fields.toJSON();
324
140
  }
325
141
 
142
+ // The schema as plain JSON: the snapshot of a model (format 1) holding the
143
+ // schema and every entity it reaches through its references, in
144
+ // dependency order, with the name of the schema as `root`.
145
+ toSnapshot() {
146
+ return schemaSnapshotOf(this);
147
+ }
148
+
326
149
  [INSPECT](depth, options, inspect) {
327
150
  const label = this.name ? `Schema(${this.name})` : 'Schema';
328
151
  return `${label} ${inspect(this.toJSON(), options)}`;
329
152
  }
330
153
  }
331
154
 
155
+ // Until the validation half is installed, a schema builds and reads, and a
156
+ // call that validates says what is missing. A stub looks the method up when
157
+ // it is called, so one a program took before the core was loaded (`const {
158
+ // check } = schema`, `check.bind(schema)`) calls the method installed since.
159
+ // Named as the methods are, for the stack.
160
+ const STUBS = {
161
+ checkConsistency(...args) {
162
+ return late(this, 'checkConsistency', args);
163
+ },
164
+ check(...args) {
165
+ return late(this, 'check', args);
166
+ },
167
+ async checkAsync(...args) {
168
+ return late(this, 'checkAsync', args);
169
+ },
170
+ parse(...args) {
171
+ return late(this, 'parse', args);
172
+ },
173
+ async parseAsync(...args) {
174
+ return late(this, 'parseAsync', args);
175
+ },
176
+ serialize(...args) {
177
+ return late(this, 'serialize', args);
178
+ },
179
+ validate(...args) {
180
+ return late(this, 'validate', args);
181
+ },
182
+ };
183
+
184
+ const late = (schema, name, args) => {
185
+ const method = Schema.prototype[name];
186
+ if (method === STUBS[name]) throw noValidation(name);
187
+ return method.apply(schema, args);
188
+ };
189
+
190
+ for (const name of Object.keys(STUBS)) {
191
+ Object.defineProperty(Schema.prototype, name, {
192
+ value: STUBS[name],
193
+ writable: true,
194
+ configurable: true,
195
+ });
196
+ }
197
+ Object.defineProperty(Schema.prototype, 'warnings', {
198
+ get() {
199
+ throw noValidation('warnings');
200
+ },
201
+ configurable: true,
202
+ });
203
+
332
204
  Schema.prototype[BRAND] = 'Schema';
333
205
 
334
206
  module.exports = { Schema };