@alexify/metaschema 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/codec.js CHANGED
@@ -10,7 +10,7 @@
10
10
  const { hasBrand, define } = require('./util.js');
11
11
  const { EMPTY, NONE, issues, isThenable, abandon, pathOf, toDotPath } = require('./issues.js');
12
12
  const { createContext } = require('./context.js');
13
- const { STRUCT, isStruct } = require('./struct.js');
13
+ const { STRUCT, isStruct, aliasOf } = require('./struct.js');
14
14
  const { asyncReturn } = require('./errors.js');
15
15
  const collections = require('./prototypes/collections.js');
16
16
  const { schema: struct } = require('./prototypes/schema.js');
@@ -24,6 +24,9 @@ const DECODERS = 2;
24
24
  const ENCODERS = 4;
25
25
  const STRUCTS = 8;
26
26
  const ASYNC = 16;
27
+ // A field with aliases below: the pass after the check visits it only when
28
+ // the check read a field from an alias (`context.renamed`).
29
+ const ALIASES = 32;
27
30
 
28
31
  // The shape of a node: a Schema, a struct (the dictionary of its fields), or
29
32
  // a field by the identity of its prototype's compile, as the JIT tells them
@@ -124,7 +127,12 @@ const infoOf = (node) => {
124
127
  const defaulted = type.default !== undefined;
125
128
  if (defaulted) bits |= DEFAULTS;
126
129
  if (defaulted || (sub.bits & DEFAULTS) !== 0) parts[DEFAULTS].push(index);
127
- if ((sub.bits & DECODERS) !== 0) parts[DECODERS].push(index);
130
+ // A field with aliases, or with one below, is visited by the pass
131
+ // that decodes, which renames; whether that pass enters the subtree
132
+ // is decided by the bits and the context at the field.
133
+ const aliased = plan[index].aliases.length > 0;
134
+ if (aliased) bits |= ALIASES;
135
+ if (aliased || (sub.bits & (DECODERS | ALIASES)) !== 0) parts[DECODERS].push(index);
128
136
  if ((sub.bits & ENCODERS) !== 0) parts[ENCODERS].push(index);
129
137
  parts[STRUCTS].push(index);
130
138
  }
@@ -261,8 +269,8 @@ const decode = (info, node, value, context, key) => {
261
269
 
262
270
  const walkLeaf = (info, node, value) => value;
263
271
 
264
- const walkInner = (info, node, value, context, key, phase) =>
265
- apply(info.infos[0], info.children[0], value, context, key, phase);
272
+ const walkInner = (info, node, value, context, key, phase, want) =>
273
+ apply(info.infos[0], info.children[0], value, context, key, phase, want);
266
274
 
267
275
  // Before the check (the defaults, a serialization) a graph may loop through
268
276
  // its references; the records on the way down are kept in `seen`, which the
@@ -274,9 +282,9 @@ const LOOP = Symbol('loop');
274
282
 
275
283
  const looped = (context) => context.seen !== null && context.seen.has(LOOP);
276
284
 
277
- const walkSchema = (info, node, value, context, key, phase) => {
285
+ const walkSchema = (info, node, value, context, key, phase, want) => {
278
286
  if (phase === DECODERS || info.refs.length === 0 || typeof value !== 'object') {
279
- return walkInner(info, node, value, context, key, phase);
287
+ return walkInner(info, node, value, context, key, phase, want);
280
288
  }
281
289
  if (context.seen === null) context.seen = new Set();
282
290
  const { seen } = context;
@@ -285,14 +293,31 @@ const walkSchema = (info, node, value, context, key, phase) => {
285
293
  return value;
286
294
  }
287
295
  seen.add(value);
288
- const out = walkInner(info, node, value, context, key, phase);
296
+ const out = walkInner(info, node, value, context, key, phase, want);
289
297
  seen.delete(value);
290
298
  return out;
291
299
  };
292
300
 
301
+ // The copy of a struct with every renamed field in the place of its alias:
302
+ // `take` appended the field's key, and a key deleted from the copy would
303
+ // leave the copy in dictionary mode. `renames` is alias, field, alias, ...
304
+ const renameKeys = (out, renames) => {
305
+ const result = {};
306
+ for (const key in out) {
307
+ const found = renames.indexOf(key);
308
+ if (found === -1) putKey(result, key, out[key]);
309
+ else if (found % 2 === 0) putKey(result, renames[found + 1], out[renames[found + 1]]);
310
+ }
311
+ return result;
312
+ };
313
+
293
314
  // The fields of a struct: a default fills a missing key before the check, a
294
315
  // decoder replaces the value after it. Stripping rebuilds the object from
295
- // the known keys; otherwise the object is copied when a field changed.
316
+ // the known keys; otherwise the object is copied when a field changed. A
317
+ // value under an alias of a field is read from there (no default fills the
318
+ // field, and the check sees it there), and the pass after the check writes
319
+ // it under the field's own key, where the alias was; serialize reads the
320
+ // value of the program, which carries the field keys, and never looks.
296
321
  const walkFields = (info, fields, value, context, key, phase, want) => {
297
322
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
298
323
  const { plan, infos, extra } = info;
@@ -300,32 +325,48 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
300
325
  const parts = info.parts[strip ? STRUCTS : phase];
301
326
  const state = enter(context, key, value, copy, putKey);
302
327
  if (strip) state.out = {};
328
+ let renames = null;
303
329
  for (let position = 0; position < parts.length; position += 1) {
304
330
  const index = parts[position];
305
331
  const entry = plan[index];
306
332
  const name = entry.key;
333
+ let from = name;
307
334
  let item = entry.own && !Object.hasOwn(value, name) ? undefined : value[name];
308
- if (item === undefined && phase === DEFAULTS) {
309
- const fallback = entry.type.default;
310
- if (fallback === undefined) continue;
311
- item = typeof fallback === 'function' ? fallback() : fallback;
312
- take(state, name, item, phase);
335
+ if (item === undefined && phase !== ENCODERS) {
336
+ from = aliasOf(value, entry.aliases, name);
337
+ if (from !== name) item = value[from];
338
+ }
339
+ if (phase === DEFAULTS) {
340
+ if (item === undefined) {
341
+ const fallback = entry.type.default;
342
+ if (fallback === undefined) continue;
343
+ item = typeof fallback === 'function' ? fallback() : fallback;
344
+ take(state, from, item, phase);
345
+ }
346
+ const result = apply(infos[index], entry.type, item, context, from, phase, want);
347
+ if (result !== item) take(state, from, result, phase);
348
+ continue;
349
+ }
350
+ const result = apply(infos[index], entry.type, item, context, from, phase, want);
351
+ const renamed = from !== name;
352
+ if (strip ? result !== undefined : renamed || result !== item) take(state, name, result, phase);
353
+ if (renamed && !strip) {
354
+ if (renames === null) renames = [];
355
+ renames.push(from, name);
313
356
  }
314
- const result = apply(infos[index], entry.type, item, context, name, phase);
315
- if (strip ? result !== undefined : result !== item) take(state, name, result, phase);
316
357
  }
317
358
  if (strip) {
318
359
  for (let index = 0; index < extra.length; index += 1) {
319
360
  const name = extra[index];
320
361
  if (Object.hasOwn(value, name)) putKey(state.out, name, value[name]);
321
362
  }
322
- }
363
+ } else if (renames !== null) state.out = renameKeys(state.out, renames);
323
364
  return leave(state);
324
365
  };
325
366
 
326
367
  // The elements of an array, a Set or a tuple, by position; a Set comes back
327
368
  // as a Set.
328
- const walkItems = (children, infos, fixed, value, context, key, phase) => {
369
+ const walkItems = (children, infos, fixed, value, context, key, phase, want) => {
329
370
  const set = !Array.isArray(value);
330
371
  if (set && (fixed || value.constructor?.name !== 'Set')) return value;
331
372
  const state = enter(context, key, value, Array.from, putIndex);
@@ -333,18 +374,18 @@ const walkItems = (children, infos, fixed, value, context, key, phase) => {
333
374
  for (const item of value) {
334
375
  const slot = fixed ? index : 0;
335
376
  if (slot >= children.length) break;
336
- const result = apply(infos[slot], children[slot], item, context, index, phase);
377
+ const result = apply(infos[slot], children[slot], item, context, index, phase, want);
337
378
  if (result !== item) take(state, index, result, phase);
338
379
  index += 1;
339
380
  }
340
381
  return leave(state, set ? toSet : undefined);
341
382
  };
342
383
 
343
- const walkList = (info, node, value, context, key, phase) =>
344
- walkItems(info.children, info.infos, info.shape === TUPLE, value, context, key, phase);
384
+ const walkList = (info, node, value, context, key, phase, want) =>
385
+ walkItems(info.children, info.infos, info.shape === TUPLE, value, context, key, phase, want);
345
386
 
346
387
  // The values of an object or a Map, by key.
347
- const walkKeyed = (info, node, value, context, key, phase) => {
388
+ const walkKeyed = (info, node, value, context, key, phase, want) => {
348
389
  const map = value.constructor?.name === 'Map';
349
390
  if (!map && (typeof value !== 'object' || Array.isArray(value))) return value;
350
391
  const child = info.children[0];
@@ -354,7 +395,7 @@ const walkKeyed = (info, node, value, context, key, phase) => {
354
395
  for (const pair of value) {
355
396
  const name = pair[0];
356
397
  const item = pair[1];
357
- const result = apply(sub, child, item, context, name, phase);
398
+ const result = apply(sub, child, item, context, name, phase, want);
358
399
  if (result !== item) take(state, name, result, phase);
359
400
  }
360
401
  } else {
@@ -362,7 +403,7 @@ const walkKeyed = (info, node, value, context, key, phase) => {
362
403
  for (const name in value) {
363
404
  if (!Object.hasOwn(value, name)) continue;
364
405
  const item = value[name];
365
- const result = apply(sub, child, item, context, name, phase);
406
+ const result = apply(sub, child, item, context, name, phase, want);
366
407
  if (result !== item) take(state, name, result, phase);
367
408
  }
368
409
  }
@@ -406,21 +447,22 @@ const accepts = (branch, value, scratch, path, key) => {
406
447
  // first branch whose check records nothing, as the check picks it. Before
407
448
  // the check a branch is tried with its own defaults in place, and the value
408
449
  // with those defaults is what parse goes on with.
409
- const walkUnion = (info, node, value, context, key, phase) => {
450
+ const walkUnion = (info, node, value, context, key, phase, want) => {
410
451
  const { children, infos, table } = info;
411
452
  if (table !== null) {
412
453
  if (typeof value !== 'object') return value;
413
454
  const index = table.get(value[node.discriminator]);
414
455
  if (index === undefined) return value;
415
- return apply(infos[index], children[index], value, context, key, phase);
456
+ return apply(infos[index], children[index], value, context, key, phase, want);
416
457
  }
417
458
  const scratch = scratchOf(context);
418
459
  for (let index = 0; index < children.length; index += 1) {
419
460
  const branch = children[index];
420
461
  const sub = infos[index];
421
- const prepared = phase === DEFAULTS ? apply(sub, branch, value, context, key, phase) : value;
462
+ const prepared =
463
+ phase === DEFAULTS ? apply(sub, branch, value, context, key, phase, want) : value;
422
464
  if (!accepts(branch, prepared, scratch, context.path, key)) continue;
423
- return phase === DEFAULTS ? prepared : apply(sub, branch, value, context, key, phase);
465
+ return phase === DEFAULTS ? prepared : apply(sub, branch, value, context, key, phase, want);
424
466
  }
425
467
  return value;
426
468
  };
@@ -428,7 +470,7 @@ const walkUnion = (info, node, value, context, key, phase) => {
428
470
  // A reference resolved at parse time, as the check resolves it: an id stays
429
471
  // an id, a record goes through its entity, and a record deeper than the
430
472
  // check allows is left as it is for the check to report.
431
- const walkReference = (info, node, value, context, key, phase) => {
473
+ const walkReference = (info, node, value, context, key, phase, want) => {
432
474
  const { one, many, root, embed } = node;
433
475
  const target = root.findReference(one || many);
434
476
  if (target === null || !embeds(target, embed, context.references)) return value;
@@ -436,7 +478,7 @@ const walkReference = (info, node, value, context, key, phase) => {
436
478
  const sub = infoOf(target);
437
479
  context.depth += 1;
438
480
  let out = value;
439
- if (one) out = apply(sub, target, value, context, key, phase);
481
+ if (one) out = apply(sub, target, value, context, key, phase, want);
440
482
  else if (Array.isArray(value)) {
441
483
  // The target as the one child of the list, kept on the info from one
442
484
  // visit to the next (it changes only when the namespaces do).
@@ -444,7 +486,7 @@ const walkReference = (info, node, value, context, key, phase) => {
444
486
  info.children[0] = target;
445
487
  info.infos[0] = sub;
446
488
  }
447
- out = walkItems(info.children, info.infos, false, value, context, key, phase);
489
+ out = walkItems(info.children, info.infos, false, value, context, key, phase, want);
448
490
  }
449
491
  context.depth -= 1;
450
492
  return out;
@@ -462,13 +504,24 @@ const WALKERS = [
462
504
  walkReference,
463
505
  ];
464
506
 
507
+ // The bits a pass wants of a subtree, decided once per pass: its own, and
508
+ // for the pass after the check the structs (under `strip`) and the fields
509
+ // with aliases (after a check that read one).
510
+ const wantOf = (phase, context) => {
511
+ let want = phase;
512
+ if (phase === DECODERS) {
513
+ if (context.unknown === 'strip') want |= STRUCTS;
514
+ if (context.renamed) want |= ALIASES;
515
+ }
516
+ return want;
517
+ };
518
+
465
519
  // One pass over a value from a node whose info is known, by the shape of
466
520
  // each node. A serializer runs before the parts of its value, a decoder
467
- // after them; stripping concerns every struct, so under `strip` the pass
468
- // enters any subtree with one.
469
- const apply = (info, node, value, context, key, phase) => {
521
+ // after them; a subtree without the bits the pass wants is returned as it
522
+ // is, which is the one test a value nothing applies to costs.
523
+ const apply = (info, node, value, context, key, phase, want) => {
470
524
  if (value == null) return value;
471
- const want = phase === DECODERS && context.unknown === 'strip' ? DECODERS | STRUCTS : phase;
472
525
  if ((info.bits & want) === 0) return value;
473
526
  let input = value;
474
527
  if (phase === ENCODERS && info.encode !== undefined) {
@@ -485,6 +538,7 @@ module.exports = {
485
538
  SERIALIZE: ENCODERS,
486
539
  infoOf,
487
540
  apply,
541
+ wantOf,
488
542
  looped,
489
543
  hasAsync,
490
544
  };
@@ -309,6 +309,34 @@ const emitStruct = (fields, x, key, state) => {
309
309
  const { required, own } = entry;
310
310
  const name = quote(entry.key);
311
311
  const item = code.name('x');
312
+ if (entry.aliases.length > 0) {
313
+ // A field with aliases, when the value has nothing under its own key:
314
+ // the first alias the value carries, and the key the check reports
315
+ // under, as `aliasOf` in struct.js finds them.
316
+ const alias = code.name('k');
317
+ const inherited = own ? ` || !Object.hasOwn(${x}, ${name})` : '';
318
+ code.push(`let ${item} = ${prop(x, entry.key)}, ${alias} = ${name};`);
319
+ code.push(`if (${item} === undefined${inherited}) { ${item} = undefined;`);
320
+ // The first alias the value carries: once one is taken the rest are
321
+ // skipped, as the chain of the closure backend stops at it, and the
322
+ // context learns that a field was read from an alias, as there.
323
+ for (const other of entry.aliases) {
324
+ const taken = `${alias} = ${quote(other)}; ${item} = ${prop(x, other)}; c.renamed = true;`;
325
+ code.push(`if (${alias} === ${name} && Object.hasOwn(${x}, ${quote(other)})) { ${taken} }`);
326
+ }
327
+ code.push('}');
328
+ if (required) {
329
+ code.push(`if (${item} === undefined && !Object.hasOwn(${x}, ${alias})) {`);
330
+ record(children, issue(state, 'required', name));
331
+ code.push('} else {');
332
+ } else {
333
+ code.push(`if (${item} !== undefined) {`);
334
+ }
335
+ code.push(`${found} += 1;`);
336
+ emitField(entry.type, item, alias, children);
337
+ code.push('}');
338
+ continue;
339
+ }
312
340
  code.push(`const ${item} = ${prop(x, entry.key)};`);
313
341
  if (required) {
314
342
  const missing = own ? '' : `${item} === undefined && `;
@@ -8,7 +8,7 @@
8
8
  // in the default mode. Nothing happens on import.
9
9
  const { hasBrand, RUN, HOOK } = require('../util.js');
10
10
  const { Schema } = require('../schema.js');
11
- const { SchemaDefinitionError } = require('../errors.js');
11
+ const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
12
12
  const { Code } = require('./code.js');
13
13
  const { emitRoot } = require('./emit.js');
14
14
 
@@ -119,7 +119,7 @@ const install = (target, onFallback) => {
119
119
 
120
120
  const schemasOf = (target) => {
121
121
  if (hasBrand(target, 'Schema')) return [target];
122
- if (!hasBrand(target, 'Model')) throw new TypeError('A Schema or a Model is expected');
122
+ if (!hasBrand(target, 'Model')) throw invalidTarget('A Schema or a Model is expected');
123
123
  const schemas = [];
124
124
  for (const schema of target.entities.values()) schemas.push(schema);
125
125
  return schemas;
package/src/context.js CHANGED
@@ -133,6 +133,9 @@ const createContext = (options, name = '', unknown = 'reject', parsing = false)
133
133
  // The context parse tries the branches of a plain union in, made at the
134
134
  // first such union of a pass and reused for the rest; null in a check.
135
135
  scratch: null,
136
+ // Whether the check read a field from one of its aliases: the pass
137
+ // after it renames only when it did.
138
+ renamed: false,
136
139
  };
137
140
  if (options !== undefined) configure(context, options, parsing);
138
141
  return context;
package/src/errors.js CHANGED
@@ -34,4 +34,13 @@ const asyncReturn = (what, where, method) => {
34
34
  return error;
35
35
  };
36
36
 
37
- module.exports = { SchemaDefinitionError, asyncReturn };
37
+ // A function of a subpath was given something other than what it takes (a
38
+ // Schema, a Model, a snapshot, a list of changes): the call is wrong, not a
39
+ // definition, so a plain TypeError with a code of its own, like asyncReturn.
40
+ const invalidTarget = (message) => {
41
+ const error = new TypeError(message);
42
+ error.code = 'ERR_INVALID_TARGET';
43
+ return error;
44
+ };
45
+
46
+ module.exports = { SchemaDefinitionError, asyncReturn, invalidTarget };