@voxgig/struct 0.0.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.
package/dist/struct.js ADDED
@@ -0,0 +1,1453 @@
1
+ "use strict";
2
+ /* Copyright (c) 2025 Voxgig Ltd. MIT LICENSE. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.StructUtility = void 0;
5
+ exports.clone = clone;
6
+ exports.escre = escre;
7
+ exports.escurl = escurl;
8
+ exports.getelem = getelem;
9
+ exports.getpath = getpath;
10
+ exports.getprop = getprop;
11
+ exports.haskey = haskey;
12
+ exports.inject = inject;
13
+ exports.isempty = isempty;
14
+ exports.isfunc = isfunc;
15
+ exports.iskey = iskey;
16
+ exports.islist = islist;
17
+ exports.ismap = ismap;
18
+ exports.isnode = isnode;
19
+ exports.items = items;
20
+ exports.joinurl = joinurl;
21
+ exports.keysof = keysof;
22
+ exports.merge = merge;
23
+ exports.pad = pad;
24
+ exports.pathify = pathify;
25
+ exports.setprop = setprop;
26
+ exports.size = size;
27
+ exports.slice = slice;
28
+ exports.strkey = strkey;
29
+ exports.stringify = stringify;
30
+ exports.transform = transform;
31
+ exports.typify = typify;
32
+ exports.validate = validate;
33
+ exports.walk = walk;
34
+ /* Voxgig Struct
35
+ * =============
36
+ *
37
+ * Utility functions to manipulate in-memory JSON-like data
38
+ * structures. These structures assumed to be composed of nested
39
+ * "nodes", where a node is a list or map, and has named or indexed
40
+ * fields. The general design principle is "by-example". Transform
41
+ * specifications mirror the desired output. This implementation is
42
+ * designed for porting to multiple language, and to be tolerant of
43
+ * undefined values.
44
+ *
45
+ * Main utilities
46
+ * - getpath: get the value at a key path deep inside an object.
47
+ * - merge: merge multiple nodes, overriding values in earlier nodes.
48
+ * - walk: walk a node tree, applying a function at each node and leaf.
49
+ * - inject: inject values from a data store into a new data structure.
50
+ * - transform: transform a data structure to an example structure.
51
+ * - validate: valiate a data structure against a shape specification.
52
+ *
53
+ * Minor utilities
54
+ * - isnode, islist, ismap, iskey, isfunc: identify value kinds.
55
+ * - isempty: undefined values, or empty nodes.
56
+ * - keysof: sorted list of node keys (ascending).
57
+ * - haskey: true if key value is defined.
58
+ * - clone: create a copy of a JSON-like data structure.
59
+ * - items: list entries of a map or list as [key, value] pairs.
60
+ * - getprop: safely get a property value by key.
61
+ * - setprop: safely set a property value by key.
62
+ * - stringify: human-friendly string version of a value.
63
+ * - escre: escape a regular expresion string.
64
+ * - escurl: escape a url.
65
+ * - joinurl: join parts of a url, merging forward slashes.
66
+ *
67
+ * This set of functions and supporting utilities is designed to work
68
+ * uniformly across many languages, meaning that some code that may be
69
+ * functionally redundant in specific languages is still retained to
70
+ * keep the code human comparable.
71
+ *
72
+ * NOTE: In this code JSON nulls are in general *not* considered the
73
+ * same as the undefined value in the given language. However most
74
+ * JSON parsers do use the undefined value to represent JSON
75
+ * null. This is ambiguous as JSON null is a separate value, not an
76
+ * undefined value. You should convert such values to a special value
77
+ * to represent JSON null, if this ambiguity creates issues
78
+ * (thankfully in most APIs, JSON nulls are not used). For example,
79
+ * the unit tests use the string "__NULL__" where necessary.
80
+ *
81
+ */
82
+ // String constants are explicitly defined.
83
+ // Mode value for inject step.
84
+ const S_MKEYPRE = 'key:pre';
85
+ const S_MKEYPOST = 'key:post';
86
+ const S_MVAL = 'val';
87
+ const S_MKEY = 'key';
88
+ // Special keys.
89
+ const S_DKEY = '`$KEY`';
90
+ const S_DMETA = '`$META`';
91
+ const S_DTOP = '$TOP';
92
+ const S_DERRS = '$ERRS';
93
+ const S_DSPEC = '$SPEC';
94
+ // General strings.
95
+ const S_array = 'array';
96
+ const S_base = 'base';
97
+ const S_boolean = 'boolean';
98
+ const S_function = 'function';
99
+ const S_number = 'number';
100
+ const S_object = 'object';
101
+ const S_string = 'string';
102
+ const S_null = 'null';
103
+ const S_MT = '';
104
+ const S_BT = '`';
105
+ const S_DS = '$';
106
+ const S_DT = '.';
107
+ const S_CN = ':';
108
+ const S_FS = '/';
109
+ const S_KEY = 'KEY';
110
+ // The standard undefined value for this language.
111
+ const UNDEF = undefined;
112
+ // Injection state used for recursive injection into JSON - like data structures.
113
+ class Injection {
114
+ constructor(val, parent, modify, errs) {
115
+ this.val = val;
116
+ this.parent = parent;
117
+ this.mode = S_MVAL;
118
+ this.full = false;
119
+ this.keyI = 0;
120
+ this.keys = [S_DTOP];
121
+ this.key = S_DTOP;
122
+ this.path = [S_DTOP];
123
+ this.nodes = [parent];
124
+ this.handler = _injecthandler;
125
+ this.base = S_DTOP;
126
+ this.modify = modify;
127
+ this.errs = errs || [];
128
+ this.meta = {};
129
+ }
130
+ toString(prefix) {
131
+ return 'INJ' + (null == prefix ? '' : S_FS + prefix) + S_CN +
132
+ pad(pathify(this.path)) +
133
+ this.mode + (this.full ? '/full' : '') + S_CN +
134
+ 'key=' + this.keyI + S_FS + this.key + S_FS + this.keys +
135
+ ' p=' + stringify(this.parent, -1, 1) +
136
+ ' m=' + stringify(this.meta, -1, 1) +
137
+ ' r=' + stringify(this.nodes[0]?.[S_DTOP], -1, 1);
138
+ }
139
+ child(keyI, keys) {
140
+ const key = strkey(keys[keyI]);
141
+ const val = this.val;
142
+ const cinj = new Injection(getprop(val, key), val, this.modify, this.errs);
143
+ cinj.keyI = keyI;
144
+ cinj.keys = keys;
145
+ cinj.key = key;
146
+ cinj.path = [...(this.path || []), key];
147
+ cinj.nodes = [...(this.nodes || []), val];
148
+ cinj.mode = this.mode;
149
+ cinj.handler = this.handler;
150
+ cinj.base = this.base;
151
+ cinj.meta = this.meta;
152
+ cinj.prior = this;
153
+ return cinj;
154
+ }
155
+ setval(val, ancestor) {
156
+ if (null == ancestor || ancestor < 2) {
157
+ return setprop(this.parent, this.key, val);
158
+ }
159
+ else {
160
+ return setprop(getelem(this.nodes, 0 - ancestor), getelem(this.path, 0 - ancestor), val);
161
+ }
162
+ }
163
+ }
164
+ // Value is a node - defined, and a map (hash) or list (array).
165
+ function isnode(val) {
166
+ return null != val && S_object == typeof val;
167
+ }
168
+ // Value is a defined map (hash) with string keys.
169
+ function ismap(val) {
170
+ return null != val && S_object == typeof val && !Array.isArray(val);
171
+ }
172
+ // Value is a defined list (array) with integer keys (indexes).
173
+ function islist(val) {
174
+ return Array.isArray(val);
175
+ }
176
+ // Value is a defined string (non-empty) or integer key.
177
+ function iskey(key) {
178
+ const keytype = typeof key;
179
+ return (S_string === keytype && S_MT !== key) || S_number === keytype;
180
+ }
181
+ // Check for an "empty" value - undefined, empty string, array, object.
182
+ function isempty(val) {
183
+ return null == val || S_MT === val ||
184
+ (Array.isArray(val) && 0 === val.length) ||
185
+ (S_object === typeof val && 0 === Object.keys(val).length);
186
+ }
187
+ // Value is a function.
188
+ function isfunc(val) {
189
+ return S_function === typeof val;
190
+ }
191
+ function size(val) {
192
+ if (islist(val)) {
193
+ return val.length;
194
+ }
195
+ else if (ismap(val)) {
196
+ return Object.keys(val).length;
197
+ }
198
+ const valtype = typeof val;
199
+ if (S_string == valtype) {
200
+ return val.length;
201
+ }
202
+ else if (S_number == typeof val) {
203
+ return Math.floor(val);
204
+ }
205
+ else if (S_boolean == typeof val) {
206
+ return true === val ? 1 : 0;
207
+ }
208
+ else {
209
+ return 0;
210
+ }
211
+ }
212
+ function slice(val, start, end) {
213
+ if (islist(val)) {
214
+ const vlen = size(val);
215
+ if (null != start) {
216
+ if (start < 0) {
217
+ end = vlen + start;
218
+ if (end < 0) {
219
+ end = 0;
220
+ }
221
+ start = 0;
222
+ }
223
+ else if (null != end) {
224
+ if (end < 0) {
225
+ end = vlen + end;
226
+ if (end < 0) {
227
+ end = 0;
228
+ }
229
+ }
230
+ else if (vlen < end) {
231
+ end = val.length;
232
+ }
233
+ }
234
+ else {
235
+ end = val.length;
236
+ }
237
+ if (vlen < start) {
238
+ start = vlen;
239
+ }
240
+ if (-1 < start && start <= end && end <= vlen) {
241
+ return val.slice(start, end);
242
+ }
243
+ }
244
+ }
245
+ return val;
246
+ }
247
+ function pad(str, padding, padchar) {
248
+ str = stringify(str);
249
+ padding = null == padding ? 44 : padding;
250
+ padchar = null == padchar ? ' ' : ((padchar + ' ')[0]);
251
+ return -1 < padding ? str.padEnd(padding, padchar) : str.padStart(0 - padding, padchar);
252
+ }
253
+ // Determine the type of a value as a string.
254
+ // Returns one of: 'null', 'string', 'number', 'boolean', 'function', 'array', 'object'
255
+ // Normalizes and simplifies JavaScript's type system for consistency.
256
+ function typify(value) {
257
+ if (value === null || value === undefined) {
258
+ return S_null;
259
+ }
260
+ const type = typeof value;
261
+ if (Array.isArray(value)) {
262
+ return S_array;
263
+ }
264
+ if (type === 'object') {
265
+ return S_object;
266
+ }
267
+ return type;
268
+ }
269
+ // Get a list element. The key should be an integer, or a string
270
+ // that can parse to an integer only. Negative integers count from the end of the list.
271
+ function getelem(val, key, alt) {
272
+ let out = UNDEF;
273
+ if (UNDEF === val || UNDEF === key) {
274
+ return alt;
275
+ }
276
+ if (islist(val)) {
277
+ let nkey = parseInt(key);
278
+ if (Number.isInteger(nkey) && ('' + key).match(/^[-0-9]+$/)) {
279
+ if (nkey < 0) {
280
+ key = val.length + nkey;
281
+ }
282
+ out = val[key];
283
+ }
284
+ }
285
+ if (UNDEF === out) {
286
+ return alt;
287
+ }
288
+ return out;
289
+ }
290
+ // Safely get a property of a node. Undefined arguments return undefined.
291
+ // If the key is not found, return the alternative value, if any.
292
+ // TODO: for arrays. make -i work, such that -1 => last element
293
+ function getprop(val, key, alt) {
294
+ let out = alt;
295
+ if (UNDEF === val || UNDEF === key) {
296
+ return alt;
297
+ }
298
+ if (isnode(val)) {
299
+ out = val[key];
300
+ }
301
+ if (UNDEF === out) {
302
+ return alt;
303
+ }
304
+ return out;
305
+ }
306
+ // Convert different types of keys to string representation.
307
+ // String keys are returned as is.
308
+ // Number keys are converted to strings.
309
+ // Floats are truncated to integers.
310
+ // Booleans, objects, arrays, null, undefined all return empty string.
311
+ function strkey(key = UNDEF) {
312
+ if (UNDEF === key) {
313
+ return S_MT;
314
+ }
315
+ if (typeof key === S_string) {
316
+ return key;
317
+ }
318
+ if (typeof key === S_boolean) {
319
+ return S_MT;
320
+ }
321
+ if (typeof key === S_number) {
322
+ return key % 1 === 0 ? String(key) : String(Math.floor(key));
323
+ }
324
+ return S_MT;
325
+ }
326
+ // Sorted keys of a map, or indexes of a list.
327
+ function keysof(val) {
328
+ return !isnode(val) ? [] :
329
+ ismap(val) ? Object.keys(val).sort() : val.map((_n, i) => '' + i);
330
+ }
331
+ // Value of property with name key in node val is defined.
332
+ function haskey(val, key) {
333
+ return UNDEF !== getprop(val, key);
334
+ }
335
+ // List the sorted keys of a map or list as an array of tuples of the form [key, value].
336
+ // NOTE: Unlike keysof, list indexes are returned as numbers.
337
+ function items(val) {
338
+ return keysof(val).map((k) => [k, val[k]]);
339
+ }
340
+ // Escape regular expression.
341
+ function escre(s) {
342
+ s = null == s ? S_MT : s;
343
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
344
+ }
345
+ // Escape URLs.
346
+ function escurl(s) {
347
+ s = null == s ? S_MT : s;
348
+ return encodeURIComponent(s);
349
+ }
350
+ // Concatenate url part strings, merging forward slashes as needed.
351
+ function joinurl(sarr) {
352
+ return sarr
353
+ .filter(s => null != s && '' !== s)
354
+ .map((s, i) => 0 === i ? s.replace(/\/+$/, '') :
355
+ s.replace(/([^\/])\/+/, '$1/').replace(/^\/+/, '').replace(/\/+$/, ''))
356
+ .filter(s => '' !== s)
357
+ .join('/');
358
+ }
359
+ // Safely stringify a value for humans (NOT JSON!).
360
+ function stringify(val, maxlen, pretty) {
361
+ let valstr = S_MT;
362
+ pretty = !!pretty;
363
+ if (UNDEF === val) {
364
+ return pretty ? '<>' : valstr;
365
+ }
366
+ try {
367
+ valstr = JSON.stringify(val, function (_key, val) {
368
+ if (val !== null &&
369
+ typeof val === "object" &&
370
+ !Array.isArray(val)) {
371
+ const sortedObj = {};
372
+ for (const k of Object.keys(val).sort()) {
373
+ sortedObj[k] = val[k];
374
+ }
375
+ return sortedObj;
376
+ }
377
+ return val;
378
+ });
379
+ }
380
+ catch (err) {
381
+ valstr = S_MT + val;
382
+ }
383
+ valstr = S_string !== typeof valstr ? S_MT + valstr : valstr;
384
+ valstr = valstr.replace(/"/g, '');
385
+ if (null != maxlen && -1 < maxlen) {
386
+ let js = valstr.substring(0, maxlen);
387
+ valstr = maxlen < valstr.length ? (js.substring(0, maxlen - 3) + '...') : valstr;
388
+ }
389
+ if (pretty) {
390
+ let c = [81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69]
391
+ .map(n => `\x1b[38;5;${n}m`), r = '\x1b[0m', d = 0, o = c[0], t = o;
392
+ for (const ch of valstr) {
393
+ if (ch === '{' || ch === '[') {
394
+ d++;
395
+ o = c[d % c.length];
396
+ t += o + ch;
397
+ }
398
+ else if (ch === '}' || ch === ']') {
399
+ t += o + ch;
400
+ d--;
401
+ o = c[d % c.length];
402
+ }
403
+ else {
404
+ t += o + ch;
405
+ }
406
+ }
407
+ return t + r;
408
+ }
409
+ return valstr;
410
+ }
411
+ // Build a human friendly path string.
412
+ function pathify(val, startin, endin) {
413
+ let pathstr = UNDEF;
414
+ let path = islist(val) ? val :
415
+ S_string == typeof val ? [val] :
416
+ S_number == typeof val ? [val] :
417
+ UNDEF;
418
+ const start = null == startin ? 0 : -1 < startin ? startin : 0;
419
+ const end = null == endin ? 0 : -1 < endin ? endin : 0;
420
+ if (UNDEF != path && 0 <= start) {
421
+ path = slice(path, start, path.length - end);
422
+ if (0 === path.length) {
423
+ pathstr = '<root>';
424
+ }
425
+ else {
426
+ pathstr = path
427
+ // .filter((p: any, t: any) => (t = typeof p, S_string === t || S_number === t))
428
+ .filter((p) => iskey(p))
429
+ .map((p) => 'number' === typeof p ? S_MT + Math.floor(p) :
430
+ p.replace(/\./g, S_MT))
431
+ .join(S_DT);
432
+ }
433
+ }
434
+ if (UNDEF === pathstr) {
435
+ pathstr = '<unknown-path' + (UNDEF === val ? S_MT : S_CN + stringify(val, 47)) + '>';
436
+ }
437
+ return pathstr;
438
+ }
439
+ // Clone a JSON-like data structure.
440
+ // NOTE: function value references are copied, *not* cloned.
441
+ function clone(val) {
442
+ const refs = [];
443
+ const replacer = (_k, v) => S_function === typeof v ?
444
+ (refs.push(v), '`$FUNCTION:' + (refs.length - 1) + '`') : v;
445
+ const reviver = (_k, v, m) => S_string === typeof v ?
446
+ (m = v.match(/^`\$FUNCTION:([0-9]+)`$/), m ? refs[m[1]] : v) : v;
447
+ return UNDEF === val ? UNDEF : JSON.parse(JSON.stringify(val, replacer), reviver);
448
+ }
449
+ // Safely set a property. Undefined arguments and invalid keys are ignored.
450
+ // Returns the (possibly modified) parent.
451
+ // If the value is undefined the key will be deleted from the parent.
452
+ // If the parent is a list, and the key is negative, prepend the value.
453
+ // NOTE: If the key is above the list size, append the value; below, prepend.
454
+ // If the value is undefined, remove the list element at index key, and shift the
455
+ // remaining elements down. These rules avoid "holes" in the list.
456
+ function setprop(parent, key, val) {
457
+ if (!iskey(key)) {
458
+ return parent;
459
+ }
460
+ if (ismap(parent)) {
461
+ key = S_MT + key;
462
+ if (UNDEF === val) {
463
+ delete parent[key];
464
+ }
465
+ else {
466
+ parent[key] = val;
467
+ }
468
+ }
469
+ else if (islist(parent)) {
470
+ // Ensure key is an integer.
471
+ let keyI = +key;
472
+ if (isNaN(keyI)) {
473
+ return parent;
474
+ }
475
+ keyI = Math.floor(keyI);
476
+ // Delete list element at position keyI, shifting later elements down.
477
+ if (UNDEF === val) {
478
+ if (0 <= keyI && keyI < parent.length) {
479
+ for (let pI = keyI; pI < parent.length - 1; pI++) {
480
+ parent[pI] = parent[pI + 1];
481
+ }
482
+ parent.length = parent.length - 1;
483
+ }
484
+ }
485
+ // Set or append value at position keyI, or append if keyI out of bounds.
486
+ else if (0 <= keyI) {
487
+ parent[parent.length < keyI ? parent.length : keyI] = val;
488
+ }
489
+ // Prepend value if keyI is negative
490
+ else {
491
+ parent.unshift(val);
492
+ }
493
+ }
494
+ return parent;
495
+ }
496
+ // Walk a data structure depth first, applying a function to each value.
497
+ function walk(
498
+ // These arguments are the public interface.
499
+ val, apply,
500
+ // These areguments are used for recursive state.
501
+ key, parent, path) {
502
+ if (isnode(val)) {
503
+ for (let [ckey, child] of items(val)) {
504
+ setprop(val, ckey, walk(child, apply, ckey, val, [...(path || []), S_MT + ckey]));
505
+ }
506
+ }
507
+ // Nodes are applied *after* their children.
508
+ // For the root node, key and parent will be undefined.
509
+ return apply(key, val, parent, path || []);
510
+ }
511
+ // Merge a list of values into each other. Later values have
512
+ // precedence. Nodes override scalars. Node kinds (list or map)
513
+ // override each other, and do *not* merge. The first element is
514
+ // modified.
515
+ function merge(val) {
516
+ let out = UNDEF;
517
+ // Handle edge cases.
518
+ if (!islist(val)) {
519
+ return val;
520
+ }
521
+ const list = val;
522
+ const lenlist = list.length;
523
+ if (0 === lenlist) {
524
+ return UNDEF;
525
+ }
526
+ else if (1 === lenlist) {
527
+ return list[0];
528
+ }
529
+ // Merge a list of values.
530
+ out = getprop(list, 0, {});
531
+ for (let oI = 1; oI < lenlist; oI++) {
532
+ let obj = list[oI];
533
+ if (!isnode(obj)) {
534
+ // Nodes win.
535
+ out = obj;
536
+ }
537
+ else {
538
+ // Nodes win, also over nodes of a different kind.
539
+ if (!isnode(out) || (ismap(obj) && islist(out)) || (islist(obj) && ismap(out))) {
540
+ out = obj;
541
+ }
542
+ else {
543
+ // Node stack. walking down the current obj.
544
+ let cur = [out];
545
+ let cI = 0;
546
+ function merger(key, val, parent, path) {
547
+ if (null == key) {
548
+ return val;
549
+ }
550
+ // Get the curent value at the current path in obj.
551
+ // NOTE: this is not exactly efficient, and should be optimised.
552
+ let lenpath = path.length;
553
+ cI = lenpath - 1;
554
+ if (UNDEF === cur[cI]) {
555
+ cur[cI] = getpath(slice(path, 0, lenpath - 1), out);
556
+ }
557
+ // Create node if needed.
558
+ if (!isnode(cur[cI])) {
559
+ cur[cI] = islist(parent) ? [] : {};
560
+ }
561
+ // Node child is just ahead of us on the stack, since
562
+ // `walk` traverses leaves before nodes.
563
+ if (isnode(val) && !isempty(val)) {
564
+ setprop(cur[cI], key, cur[cI + 1]);
565
+ cur[cI + 1] = UNDEF;
566
+ }
567
+ // Scalar child.
568
+ else {
569
+ setprop(cur[cI], key, val);
570
+ }
571
+ return val;
572
+ }
573
+ // Walk overriding node, creating paths in output as needed.
574
+ walk(obj, merger);
575
+ }
576
+ }
577
+ }
578
+ return out;
579
+ }
580
+ // Get a value deep inside a node using a key path. For example the
581
+ // path `a.b` gets the value 1 from {a:{b:1}}. The path can specified
582
+ // as a dotted string, or a string array. If the path starts with a
583
+ // dot (or the first element is ''), the path is considered local, and
584
+ // resolved against the `current` argument, if defined. Integer path
585
+ // parts are used as array indexes. The inj argument allows for
586
+ // custom handling when called from `inject` or `transform`.
587
+ // TODO: change sig to be consistent with getprop
588
+ function getpath(path, store, current, inj) {
589
+ // Operate on a string array.
590
+ const parts = islist(path) ? path : S_string === typeof path ? path.split(S_DT) : UNDEF;
591
+ if (UNDEF === parts) {
592
+ return UNDEF;
593
+ }
594
+ let root = store;
595
+ let val = store;
596
+ const base = getprop(inj, S_base);
597
+ // An empty path (incl empty string) just finds the store.
598
+ if (null == path || null == store || (1 === parts.length && S_MT === parts[0])) {
599
+ // The actual store data may be in a store sub property, defined by inj.base.
600
+ val = getprop(store, base, store);
601
+ }
602
+ else if (0 < parts.length) {
603
+ let pI = 0;
604
+ // Relative path uses `current` argument.
605
+ if (S_MT === parts[0]) {
606
+ pI = 1;
607
+ root = current;
608
+ }
609
+ let part = pI < parts.length ? parts[pI] : UNDEF;
610
+ let first = S_MT === part ? current : getprop(root, part);
611
+ // At top level, check inj.base, if provided
612
+ val = (UNDEF === first && 0 === pI) ?
613
+ getprop(getprop(root, base), part) :
614
+ first;
615
+ // Move along the path, trying to descend into the store.
616
+ for (pI++; UNDEF !== val && pI < parts.length; pI++) {
617
+ part = parts[pI];
618
+ if (S_MT !== part) {
619
+ val = getprop(val, parts[pI]);
620
+ }
621
+ }
622
+ }
623
+ // Inj may provide a custom handler to modify found value.
624
+ if (null != inj && isfunc(inj.handler)) {
625
+ const ref = pathify(path);
626
+ val = inj.handler(inj, val, current, ref, store);
627
+ }
628
+ return val;
629
+ }
630
+ // let cI = 0
631
+ // Inject values from a data store into a node recursively, resolving
632
+ // paths against the store, or current if they are local. THe modify
633
+ // argument allows custom modification of the result. The inj
634
+ // (Injection) argument is used to maintain recursive state.
635
+ function inject(val, store, modify, current, inj) {
636
+ const valtype = typeof val;
637
+ // Create state if at root of injection. The input value is placed
638
+ // inside a virtual parent holder to simplify edge cases.
639
+ if (UNDEF === inj) {
640
+ // Set up state assuming we are starting in the virtual parent.
641
+ inj = new Injection(val, { [S_DTOP]: val }, modify, getprop(store, S_DERRS));
642
+ inj.meta.d = 0;
643
+ }
644
+ inj.meta.d++;
645
+ // Resolve current node in store for local paths.
646
+ if (UNDEF === current) {
647
+ // TODO: check store base prop ($TOP)
648
+ current = { $TOP: store };
649
+ }
650
+ else {
651
+ // A provided current is expected to be the containing node of the associated
652
+ // store value.
653
+ const parentkey = getelem(inj.path, -2);
654
+ current = null == parentkey ? current : getprop(current, parentkey);
655
+ }
656
+ // console.log('' + inj + ' c=' + stringify(current, -1, 1))
657
+ // Descend into node.
658
+ if (isnode(val)) {
659
+ // Keys are sorted alphanumerically to ensure determinism.
660
+ // Injection transforms ($FOO) are processed *after* other keys.
661
+ // NOTE: the optional digits suffix of the transform can thus be
662
+ // used to order the transforms.
663
+ let nodekeys = ismap(val) ? [
664
+ ...Object.keys(val).filter(k => !k.includes(S_DS)).sort(),
665
+ ...Object.keys(val).filter(k => k.includes(S_DS)).sort(),
666
+ ] : val.map((_n, i) => i);
667
+ // Each child key-value pair is processed in three injection phases:
668
+ // 1. inj.mode='key:pre' - Key string is injected, returning a possibly altered key.
669
+ // 2. inj.mode='val' - The child value is injected.
670
+ // 3. inj.mode='key:post' - Key string is injected again, allowing child mutation.
671
+ for (let nkI = 0; nkI < nodekeys.length; nkI++) {
672
+ const childinj = inj.child(nkI, nodekeys);
673
+ const nodekey = childinj.key;
674
+ childinj.mode = S_MKEYPRE;
675
+ // Peform the key:pre mode injection on the child key.
676
+ const prekey = _injectstr(nodekey, store, current, childinj);
677
+ // The injection may modify child processing.
678
+ nkI = childinj.keyI;
679
+ nodekeys = childinj.keys;
680
+ // Prevent further processing by returning an undefined prekey
681
+ if (UNDEF !== prekey) {
682
+ childinj.val = getprop(val, prekey);
683
+ childinj.mode = S_MVAL;
684
+ // Perform the val mode injection on the child value.
685
+ // NOTE: return value is not used.
686
+ inject(childinj.val, store, modify, current, childinj);
687
+ // The injection may modify child processing.
688
+ nkI = childinj.keyI;
689
+ nodekeys = childinj.keys;
690
+ // Peform the key:post mode injection on the child key.
691
+ childinj.mode = S_MKEYPOST;
692
+ _injectstr(nodekey, store, current, childinj);
693
+ // The injection may modify child processing.
694
+ nkI = childinj.keyI;
695
+ nodekeys = childinj.keys;
696
+ }
697
+ }
698
+ }
699
+ // Inject paths into string scalars.
700
+ else if (S_string === valtype) {
701
+ inj.mode = S_MVAL;
702
+ val = _injectstr(val, store, current, inj);
703
+ setprop(inj.parent, inj.key, val);
704
+ }
705
+ // Custom modification.
706
+ if (modify) {
707
+ let mkey = inj.key;
708
+ let mparent = inj.parent;
709
+ let mval = getprop(mparent, mkey);
710
+ modify(mval, mkey, mparent, inj, current, store);
711
+ }
712
+ inj.val = val;
713
+ // Original val reference may no longer be correct.
714
+ // This return value is only used as the top level result.
715
+ return getprop(inj.parent, S_DTOP);
716
+ }
717
+ // The transform_* functions are special command inject handlers (see Injector).
718
+ // Delete a key from a map or list.
719
+ const transform_DELETE = (inj) => {
720
+ // _setparentprop(inj, UNDEF)
721
+ inj.setval(UNDEF);
722
+ return UNDEF;
723
+ };
724
+ // Copy value from source data.
725
+ const transform_COPY = (inj, _val, current) => {
726
+ const { mode, key } = inj;
727
+ let out = key;
728
+ if (!mode.startsWith(S_MKEY)) {
729
+ out = getprop(current, key);
730
+ inj.setval(out);
731
+ }
732
+ return out;
733
+ };
734
+ // As a value, inject the key of the parent node.
735
+ // As a key, defined the name of the key property in the source object.
736
+ const transform_KEY = (inj, _val, current) => {
737
+ const { mode, path, parent } = inj;
738
+ // Do nothing in val mode.
739
+ if (S_MVAL !== mode) {
740
+ return UNDEF;
741
+ }
742
+ // Key is defined by $KEY meta property.
743
+ const keyspec = getprop(parent, S_DKEY);
744
+ if (UNDEF !== keyspec) {
745
+ setprop(parent, S_DKEY, UNDEF);
746
+ return getprop(current, keyspec);
747
+ }
748
+ // Key is defined within general purpose $META object.
749
+ return getprop(getprop(parent, S_DMETA), S_KEY, getprop(path, path.length - 2));
750
+ };
751
+ // Store meta data about a node. Does nothing itself, just used by
752
+ // other injectors, and is removed when called.
753
+ const transform_META = (inj) => {
754
+ const { parent } = inj;
755
+ setprop(parent, S_DMETA, UNDEF);
756
+ return UNDEF;
757
+ };
758
+ // Merge a list of objects into the current object.
759
+ // Must be a key in an object. The value is merged over the current object.
760
+ // If the value is an array, the elements are first merged using `merge`.
761
+ // If the value is the empty string, merge the top level store.
762
+ // Format: { '`$MERGE`': '`source-path`' | ['`source-paths`', ...] }
763
+ const transform_MERGE = (inj, _val, current) => {
764
+ const { mode, key, parent } = inj;
765
+ if (S_MKEYPRE === mode) {
766
+ return key;
767
+ }
768
+ // Operate after child values have been transformed.
769
+ if (S_MKEYPOST === mode) {
770
+ let args = getprop(parent, key);
771
+ args = S_MT === args ? [current.$TOP] : Array.isArray(args) ? args : [args];
772
+ // Remove the $MERGE command from a parent map.
773
+ inj.setval(UNDEF);
774
+ // Literals in the parent have precedence, but we still merge onto
775
+ // the parent object, so that node tree references are not changed.
776
+ const mergelist = [parent, ...args, clone(parent)];
777
+ merge(mergelist);
778
+ return key;
779
+ }
780
+ // Ensures $MERGE is removed from parent list.
781
+ return UNDEF;
782
+ };
783
+ // Convert a node to a list.
784
+ // Format: ['`$EACH`', '`source-path-of-node`', child-template]
785
+ const transform_EACH = (inj, _val, current, _ref, store) => {
786
+ // Remove arguments to avoid spurious processing.
787
+ if (null != inj.keys) {
788
+ inj.keys.length = 1;
789
+ }
790
+ if (S_MVAL !== inj.mode) {
791
+ return UNDEF;
792
+ }
793
+ // Get arguments: ['`$EACH`', 'source-path', child-template].
794
+ const srcpath = getprop(inj.parent, 1);
795
+ const child = clone(getprop(inj.parent, 2));
796
+ // Source data.
797
+ const srcstore = getprop(store, inj.base, store);
798
+ const src = getpath(srcpath, srcstore, current);
799
+ // Create parallel data structures:
800
+ // source entries :: child templates
801
+ let tcur = [];
802
+ let tval = [];
803
+ const tkey = inj.path[inj.path.length - 2];
804
+ const target = inj.nodes[inj.nodes.length - 2] || inj.nodes[inj.nodes.length - 1];
805
+ // Create clones of the child template for each value of the current soruce.
806
+ if (islist(src)) {
807
+ tval = src.map(() => clone(child));
808
+ }
809
+ else if (ismap(src)) {
810
+ tval = Object.entries(src).map(n => ({
811
+ ...clone(child),
812
+ // Make a note of the key for $KEY transforms.
813
+ [S_DMETA]: { KEY: n[0] }
814
+ }));
815
+ }
816
+ let rval = [];
817
+ if (0 < size(tval)) {
818
+ tcur = null == src ? UNDEF : Object.values(src);
819
+ const tpath = slice(inj.path, -1);
820
+ // Parent structure.
821
+ const ckey = getelem(inj.path, -2);
822
+ tcur = { [ckey]: tcur };
823
+ if (1 < tpath.length) {
824
+ const pkey = getelem(inj.path, -3, S_DTOP);
825
+ tcur = { [pkey]: tcur };
826
+ }
827
+ const tinj = inj.child(0, [ckey]);
828
+ tinj.path = tpath;
829
+ tinj.nodes = slice(inj.nodes, -1);
830
+ tinj.parent = tcur;
831
+ tinj.val = tval;
832
+ inject(tval, store, inj.modify, tcur, tinj);
833
+ rval = tinj.val;
834
+ }
835
+ _updateAncestors(inj, target, tkey, rval);
836
+ // Prevent callee from damaging first list entry (since we are in `val` mode).
837
+ return rval[0];
838
+ };
839
+ // Convert a node to a map.
840
+ // Format: { '`$PACK`':['`source-path`', child-template]}
841
+ const transform_PACK = (inj, _val, current, _ref, store) => {
842
+ const { mode, key, path, parent, nodes } = inj;
843
+ // Defensive context checks.
844
+ if (S_MKEYPRE !== mode || S_string !== typeof key || null == path || null == nodes) {
845
+ return UNDEF;
846
+ }
847
+ // Get arguments.
848
+ const args = parent[key];
849
+ const srcpath = args[0]; // Path to source data.
850
+ const child = clone(args[1]); // Child template.
851
+ // Find key and target node.
852
+ const keyprop = child[S_DKEY];
853
+ const tkey = getelem(path, -2);
854
+ const target = nodes[path.length - 2] || nodes[path.length - 1];
855
+ // Source data
856
+ const srcstore = getprop(store, inj.base, store);
857
+ let src = getpath(srcpath, srcstore, current);
858
+ // Prepare source as a list.
859
+ src = islist(src) ? src :
860
+ ismap(src) ? Object.entries(src)
861
+ .reduce((a, n) => (n[1][S_DMETA] = { KEY: n[0] }, a.push(n[1]), a), []) :
862
+ UNDEF;
863
+ if (null == src) {
864
+ return UNDEF;
865
+ }
866
+ // Get key if specified.
867
+ let childkey = getprop(child, S_DKEY);
868
+ let keyname = UNDEF === childkey ? keyprop : childkey;
869
+ setprop(child, S_DKEY, UNDEF);
870
+ // Build parallel target object.
871
+ let tval = {};
872
+ tval = src.reduce((a, n) => {
873
+ let kn = getprop(n, keyname);
874
+ setprop(a, kn, clone(child));
875
+ const nchild = getprop(a, kn);
876
+ setprop(nchild, S_DMETA, getprop(n, S_DMETA));
877
+ return a;
878
+ }, tval);
879
+ let rval = {};
880
+ if (0 < size(tval)) {
881
+ // Build parallel source object.
882
+ let tcur = {};
883
+ src.reduce((a, n) => {
884
+ let kn = getprop(n, keyname);
885
+ setprop(a, kn, n);
886
+ return a;
887
+ }, tcur);
888
+ const tpath = slice(inj.path, -1);
889
+ const ckey = getelem(inj.path, -2);
890
+ tcur = { [ckey]: tcur };
891
+ if (1 < tpath.length) {
892
+ const pkey = getelem(inj.path, -3, S_DTOP);
893
+ tcur = { [pkey]: tcur };
894
+ }
895
+ const tinj = inj.child(0, [ckey]);
896
+ tinj.path = tpath;
897
+ tinj.nodes = slice(inj.nodes, -1);
898
+ tinj.parent = tcur;
899
+ tinj.val = tval;
900
+ inject(tval, store, inj.modify, tcur, tinj);
901
+ rval = tinj.val;
902
+ }
903
+ _updateAncestors(inj, target, tkey, rval);
904
+ // Drop transform key.
905
+ return UNDEF;
906
+ };
907
+ // Reference original spec (enables recursice transformations)
908
+ // Format: ['`$REF`', '`spec-path`']
909
+ const transform_REF = (inj, val, _current, _ref, store) => {
910
+ const { nodes, modify } = inj;
911
+ if (S_MVAL !== inj.mode) {
912
+ return UNDEF;
913
+ }
914
+ // Get arguments: ['`$REF`', 'ref-path'].
915
+ const refpath = getprop(inj.parent, 1);
916
+ inj.keyI = inj.keys.length;
917
+ // Spec reference.
918
+ const spec = getprop(store, S_DSPEC)();
919
+ const ref = getpath(refpath, spec);
920
+ let hasSubRef = false;
921
+ if (isnode(ref)) {
922
+ walk(ref, (_k, v) => {
923
+ if ('`$REF`' === v) {
924
+ hasSubRef = true;
925
+ }
926
+ return v;
927
+ });
928
+ }
929
+ let tref = clone(ref);
930
+ const cpath = slice(inj.path, -3);
931
+ const tpath = slice(inj.path, -1);
932
+ let tcur = getpath(cpath, store);
933
+ let tval = getpath(tpath, store);
934
+ let rval = UNDEF;
935
+ if (!hasSubRef || UNDEF !== tval) {
936
+ const tinj = inj.child(0, [getelem(tpath, -1)]);
937
+ tinj.path = tpath;
938
+ tinj.nodes = slice(inj.nodes, -1);
939
+ tinj.parent = getelem(nodes, -2);
940
+ tinj.val = tref;
941
+ inject(tref, store, modify, tcur, tinj);
942
+ rval = tinj.val;
943
+ }
944
+ else {
945
+ rval = UNDEF;
946
+ }
947
+ const grandparent = inj.setval(rval, 2);
948
+ if (islist(grandparent) && inj.prior) {
949
+ inj.prior.keyI--;
950
+ }
951
+ return val;
952
+ };
953
+ // Transform data using spec.
954
+ // Only operates on static JSON-like data.
955
+ // Arrays are treated as if they are objects with indices as keys.
956
+ function transform(data, // Source data to transform into new data (original not mutated)
957
+ spec, // Transform specification; output follows this shape
958
+ extra, // Additional store of data and transforms.
959
+ modify // Optionally modify individual values.
960
+ ) {
961
+ // Clone the spec so that the clone can be modified in place as the transform result.
962
+ const origspec = spec;
963
+ spec = clone(origspec);
964
+ const extraTransforms = {};
965
+ const extraData = null == extra ? UNDEF : items(extra)
966
+ .reduce((a, n) => (n[0].startsWith(S_DS) ? extraTransforms[n[0]] = n[1] : (a[n[0]] = n[1]), a), {});
967
+ const dataClone = merge([
968
+ isempty(extraData) ? UNDEF : clone(extraData),
969
+ clone(data),
970
+ ]);
971
+ // Define a top level store that provides transform operations.
972
+ const store = {
973
+ // The inject function recognises this special location for the root of the source data.
974
+ // NOTE: to escape data that contains "`$FOO`" keys at the top level,
975
+ // place that data inside a holding map: { myholder: mydata }.
976
+ $TOP: dataClone,
977
+ $SPEC: () => origspec,
978
+ // Escape backtick (this also works inside backticks).
979
+ $BT: () => S_BT,
980
+ // Escape dollar sign (this also works inside backticks).
981
+ $DS: () => S_DS,
982
+ // Insert current date and time as an ISO string.
983
+ $WHEN: () => new Date().toISOString(),
984
+ $DELETE: transform_DELETE,
985
+ $COPY: transform_COPY,
986
+ $KEY: transform_KEY,
987
+ $META: transform_META,
988
+ $MERGE: transform_MERGE,
989
+ $EACH: transform_EACH,
990
+ $PACK: transform_PACK,
991
+ $REF: transform_REF,
992
+ // Custom extra transforms, if any.
993
+ ...extraTransforms,
994
+ };
995
+ const out = inject(spec, store, modify, store);
996
+ return out;
997
+ }
998
+ // A required string value. NOTE: Rejects empty strings.
999
+ const validate_STRING = (inj, _val, current) => {
1000
+ let out = getprop(current, inj.key);
1001
+ const t = typify(out);
1002
+ if (S_string !== t) {
1003
+ let msg = _invalidTypeMsg(inj.path, S_string, t, out, 'V1010');
1004
+ inj.errs.push(msg);
1005
+ return UNDEF;
1006
+ }
1007
+ if (S_MT === out) {
1008
+ let msg = 'Empty string at ' + pathify(inj.path, 1);
1009
+ inj.errs.push(msg);
1010
+ return UNDEF;
1011
+ }
1012
+ return out;
1013
+ };
1014
+ // A required number value (int or float).
1015
+ const validate_NUMBER = (inj, _val, current) => {
1016
+ let out = getprop(current, inj.key);
1017
+ const t = typify(out);
1018
+ if (S_number !== t) {
1019
+ inj.errs.push(_invalidTypeMsg(inj.path, S_number, t, out, 'V1020'));
1020
+ return UNDEF;
1021
+ }
1022
+ return out;
1023
+ };
1024
+ // A required boolean value.
1025
+ const validate_BOOLEAN = (inj, _val, current) => {
1026
+ let out = getprop(current, inj.key);
1027
+ const t = typify(out);
1028
+ if (S_boolean !== t) {
1029
+ inj.errs.push(_invalidTypeMsg(inj.path, S_boolean, t, out, 'V1030'));
1030
+ return UNDEF;
1031
+ }
1032
+ return out;
1033
+ };
1034
+ // A required object (map) value (contents not validated).
1035
+ const validate_OBJECT = (inj, _val, current) => {
1036
+ let out = getprop(current, inj.key);
1037
+ const t = typify(out);
1038
+ if (t !== S_object) {
1039
+ inj.errs.push(_invalidTypeMsg(inj.path, S_object, t, out, 'V1040'));
1040
+ return UNDEF;
1041
+ }
1042
+ return out;
1043
+ };
1044
+ // A required array (list) value (contents not validated).
1045
+ const validate_ARRAY = (inj, _val, current) => {
1046
+ let out = getprop(current, inj.key);
1047
+ const t = typify(out);
1048
+ if (t !== S_array) {
1049
+ inj.errs.push(_invalidTypeMsg(inj.path, S_array, t, out, 'V1050'));
1050
+ return UNDEF;
1051
+ }
1052
+ return out;
1053
+ };
1054
+ // A required function value.
1055
+ const validate_FUNCTION = (inj, _val, current) => {
1056
+ let out = getprop(current, inj.key);
1057
+ const t = typify(out);
1058
+ if (S_function !== t) {
1059
+ inj.errs.push(_invalidTypeMsg(inj.path, S_function, t, out, 'V1060'));
1060
+ return UNDEF;
1061
+ }
1062
+ return out;
1063
+ };
1064
+ // Allow any value.
1065
+ const validate_ANY = (inj, _val, current) => {
1066
+ return getprop(current, inj.key);
1067
+ };
1068
+ // Specify child values for map or list.
1069
+ // Map syntax: {'`$CHILD`': child-template }
1070
+ // List syntax: ['`$CHILD`', child-template ]
1071
+ const validate_CHILD = (inj, _val, current) => {
1072
+ const { mode, key, parent, keys, path } = inj;
1073
+ // Setup data structures for validation by cloning child template.
1074
+ // Map syntax.
1075
+ if (S_MKEYPRE === mode) {
1076
+ const childtm = getprop(parent, key);
1077
+ // Get corresponding current object.
1078
+ const pkey = getprop(path, path.length - 2);
1079
+ let tval = getprop(current, pkey);
1080
+ if (UNDEF == tval) {
1081
+ tval = {};
1082
+ }
1083
+ else if (!ismap(tval)) {
1084
+ inj.errs.push(_invalidTypeMsg(slice(inj.path, -1), S_object, typify(tval), tval), 'V0220');
1085
+ return UNDEF;
1086
+ }
1087
+ const ckeys = keysof(tval);
1088
+ for (let ckey of ckeys) {
1089
+ setprop(parent, ckey, clone(childtm));
1090
+ // NOTE: modifying inj! This extends the child value loop in inject.
1091
+ keys.push(ckey);
1092
+ }
1093
+ // Remove $CHILD to cleanup ouput.
1094
+ // _setparentprop(inj, UNDEF)
1095
+ inj.setval(UNDEF);
1096
+ return UNDEF;
1097
+ }
1098
+ // List syntax.
1099
+ if (S_MVAL === mode) {
1100
+ if (!islist(parent)) {
1101
+ // $CHILD was not inside a list.
1102
+ inj.errs.push('Invalid $CHILD as value');
1103
+ return UNDEF;
1104
+ }
1105
+ const childtm = getprop(parent, 1);
1106
+ if (UNDEF === current) {
1107
+ // Empty list as default.
1108
+ parent.length = 0;
1109
+ return UNDEF;
1110
+ }
1111
+ if (!islist(current)) {
1112
+ const msg = _invalidTypeMsg(slice(inj.path, -1), S_array, typify(current), current, 'V0230');
1113
+ inj.errs.push(msg);
1114
+ inj.keyI = parent.length;
1115
+ return current;
1116
+ }
1117
+ // Clone children abd reset inj key index.
1118
+ // The inject child loop will now iterate over the cloned children,
1119
+ // validating them againt the current list values.
1120
+ current.map((_n, i) => parent[i] = clone(childtm));
1121
+ parent.length = current.length;
1122
+ inj.keyI = 0;
1123
+ const out = getprop(current, 0);
1124
+ return out;
1125
+ }
1126
+ return UNDEF;
1127
+ };
1128
+ // Match at least one of the specified shapes.
1129
+ // Syntax: ['`$ONE`', alt0, alt1, ...]okI
1130
+ const validate_ONE = (inj, _val, current, _ref, store) => {
1131
+ const { mode, parent, path, keyI, nodes } = inj;
1132
+ // Only operate in val mode, since parent is a list.
1133
+ if (S_MVAL === mode) {
1134
+ if (!islist(parent) || 0 !== keyI) {
1135
+ inj.errs.push('The $ONE validator at field ' +
1136
+ pathify(inj.path, 1, 1) +
1137
+ ' must be the first element of an array.');
1138
+ return;
1139
+ }
1140
+ inj.keyI = inj.keys.length;
1141
+ // Clean up structure, replacing [$ONE, ...] with current
1142
+ const grandparent = inj.setval(current, 2);
1143
+ inj.path = slice(inj.path, -1);
1144
+ inj.key = getelem(inj.path, -1);
1145
+ let tvals = slice(parent, 1);
1146
+ if (0 === tvals.length) {
1147
+ inj.errs.push('The $ONE validator at field ' +
1148
+ pathify(inj.path, 1, 1) +
1149
+ ' must have at least one argument.');
1150
+ return;
1151
+ }
1152
+ // See if we can find a match.
1153
+ for (let tval of tvals) {
1154
+ // If match, then errs.length = 0
1155
+ let terrs = [];
1156
+ const vstore = { ...store };
1157
+ vstore.$TOP = current;
1158
+ const vcurrent = validate(current, tval, vstore, terrs);
1159
+ setprop(grandparent, getelem(path, -2), vcurrent);
1160
+ // Accept current value if there was a match
1161
+ if (0 === terrs.length) {
1162
+ return;
1163
+ }
1164
+ }
1165
+ // There was no match.
1166
+ const valdesc = tvals
1167
+ .map((v) => stringify(v))
1168
+ .join(', ')
1169
+ .replace(/`\$([A-Z]+)`/g, (_m, p1) => p1.toLowerCase());
1170
+ inj.errs.push(_invalidTypeMsg(inj.path, (1 < tvals.length ? 'one of ' : '') + valdesc, typify(current), current, 'V0210'));
1171
+ }
1172
+ };
1173
+ const validate_EXACT = (inj, _val, current, _ref, _store) => {
1174
+ const { mode, parent, key, keyI, path, nodes } = inj;
1175
+ // Only operate in val mode, since parent is a list.
1176
+ if (S_MVAL === mode) {
1177
+ if (!islist(parent) || 0 !== keyI) {
1178
+ inj.errs.push('The $EXACT validator at field ' +
1179
+ pathify(inj.path, 1, 1) +
1180
+ ' must be the first element of an array.');
1181
+ return;
1182
+ }
1183
+ inj.keyI = inj.keys.length;
1184
+ // Clean up structure, replacing [$EXACT, ...] with current
1185
+ inj.setval(current, 2);
1186
+ inj.path = slice(inj.path, 0, inj.path.length - 1);
1187
+ inj.key = getelem(inj.path, -1);
1188
+ let tvals = slice(parent, 1);
1189
+ if (0 === tvals.length) {
1190
+ inj.errs.push('The $EXACT validator at field ' +
1191
+ pathify(inj.path, 1, 1) +
1192
+ ' must have at least one argument.');
1193
+ return;
1194
+ }
1195
+ // See if we can find an exact value match.
1196
+ let currentstr = undefined;
1197
+ for (let tval of tvals) {
1198
+ let exactmatch = tval === current;
1199
+ if (!exactmatch && isnode(tval)) {
1200
+ currentstr = undefined === currentstr ? stringify(current) : currentstr;
1201
+ const tvalstr = stringify(tval);
1202
+ exactmatch = tvalstr === currentstr;
1203
+ }
1204
+ if (exactmatch) {
1205
+ return;
1206
+ }
1207
+ }
1208
+ const valdesc = tvals
1209
+ .map((v) => stringify(v))
1210
+ .join(', ')
1211
+ .replace(/`\$([A-Z]+)`/g, (_m, p1) => p1.toLowerCase());
1212
+ inj.errs.push(_invalidTypeMsg(inj.path, (1 < inj.path.length ? '' : 'value ') +
1213
+ 'exactly equal to ' + (1 === tvals.length ? '' : 'one of ') + valdesc, typify(current), current, 'V0110'));
1214
+ }
1215
+ else {
1216
+ setprop(parent, key, UNDEF);
1217
+ }
1218
+ };
1219
+ // This is the "modify" argument to inject. Use this to perform
1220
+ // generic validation. Runs *after* any special commands.
1221
+ const _validation = (pval, key, parent, inj, current, _store) => {
1222
+ if (UNDEF === inj) {
1223
+ return;
1224
+ }
1225
+ // Current val to verify.
1226
+ const cval = getprop(current, key);
1227
+ if (UNDEF === cval || UNDEF === inj) {
1228
+ return;
1229
+ }
1230
+ const ptype = typify(pval);
1231
+ // Delete any special commands remaining.
1232
+ if (S_string === ptype && pval.includes(S_DS)) {
1233
+ return;
1234
+ }
1235
+ const ctype = typify(cval);
1236
+ // Type mismatch.
1237
+ if (ptype !== ctype && UNDEF !== pval) {
1238
+ inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0010'));
1239
+ return;
1240
+ }
1241
+ if (ismap(cval)) {
1242
+ if (!ismap(pval)) {
1243
+ inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0020'));
1244
+ return;
1245
+ }
1246
+ const ckeys = keysof(cval);
1247
+ const pkeys = keysof(pval);
1248
+ // Empty spec object {} means object can be open (any keys).
1249
+ if (0 < pkeys.length && true !== getprop(pval, '`$OPEN`')) {
1250
+ const badkeys = [];
1251
+ for (let ckey of ckeys) {
1252
+ if (!haskey(pval, ckey)) {
1253
+ badkeys.push(ckey);
1254
+ }
1255
+ }
1256
+ // Closed object, so reject extra keys not in shape.
1257
+ if (0 < badkeys.length) {
1258
+ const msg = 'Unexpected keys at field ' + pathify(inj.path, 1) + ': ' + badkeys.join(', ');
1259
+ inj.errs.push(msg);
1260
+ }
1261
+ }
1262
+ else {
1263
+ // Object is open, so merge in extra keys.
1264
+ merge([pval, cval]);
1265
+ if (isnode(pval)) {
1266
+ setprop(pval, '`$OPEN`', UNDEF);
1267
+ }
1268
+ }
1269
+ }
1270
+ else if (islist(cval)) {
1271
+ if (!islist(pval)) {
1272
+ inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0030'));
1273
+ }
1274
+ }
1275
+ else {
1276
+ // Spec value was a default, copy over data
1277
+ setprop(parent, key, cval);
1278
+ }
1279
+ return;
1280
+ };
1281
+ // Validate a data structure against a shape specification. The shape
1282
+ // specification follows the "by example" principle. Plain data in
1283
+ // teh shape is treated as default values that also specify the
1284
+ // required type. Thus shape {a:1} validates {a:2}, since the types
1285
+ // (number) match, but not {a:'A'}. Shape {a;1} against data {}
1286
+ // returns {a:1} as a=1 is the default value of the a key. Special
1287
+ // validation commands (in the same syntax as transform ) are also
1288
+ // provided to specify required values. Thus shape {a:'`$STRING`'}
1289
+ // validates {a:'A'} but not {a:1}. Empty map or list means the node
1290
+ // is open, and if missing an empty default is inserted.
1291
+ function validate(data, // Source data to transform into new data (original not mutated)
1292
+ spec, // Transform specification; output follows this shape
1293
+ extra, // Additional custom checks
1294
+ // Optionally modify individual values.
1295
+ collecterrs) {
1296
+ const errs = null == collecterrs ? [] : collecterrs;
1297
+ const store = {
1298
+ // Remove the transform commands.
1299
+ $DELETE: null,
1300
+ $COPY: null,
1301
+ $KEY: null,
1302
+ $META: null,
1303
+ $MERGE: null,
1304
+ $EACH: null,
1305
+ $PACK: null,
1306
+ $STRING: validate_STRING,
1307
+ $NUMBER: validate_NUMBER,
1308
+ $BOOLEAN: validate_BOOLEAN,
1309
+ $OBJECT: validate_OBJECT,
1310
+ $ARRAY: validate_ARRAY,
1311
+ $FUNCTION: validate_FUNCTION,
1312
+ $ANY: validate_ANY,
1313
+ $CHILD: validate_CHILD,
1314
+ $ONE: validate_ONE,
1315
+ $EXACT: validate_EXACT,
1316
+ ...(extra || {}),
1317
+ // A special top level value to collect errors.
1318
+ // NOTE: collecterrs paramter always wins.
1319
+ $ERRS: errs,
1320
+ };
1321
+ const out = transform(data, spec, store, _validation);
1322
+ const generr = (0 < errs.length && null == collecterrs);
1323
+ if (generr) {
1324
+ throw new Error('Invalid data: ' + errs.join(' | '));
1325
+ }
1326
+ return out;
1327
+ }
1328
+ // Internal utilities
1329
+ // ==================
1330
+ // Set inj.key property of inj.parent node, ensuring reference consistency
1331
+ // when needed by implementation language.
1332
+ // function _setparentprop(inj: Injection, val: any) {
1333
+ // setprop(inj.parent, inj.key, val)
1334
+ // }
1335
+ // Update all references to target in inj.nodes.
1336
+ function _updateAncestors(_inj, target, tkey, tval) {
1337
+ // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
1338
+ setprop(target, tkey, tval);
1339
+ }
1340
+ // Build a type validation error message.
1341
+ function _invalidTypeMsg(path, needtype, vt, v, _whence) {
1342
+ let vs = null == v ? 'no value' : stringify(v);
1343
+ return 'Expected ' +
1344
+ (1 < path.length ? ('field ' + pathify(path, 1) + ' to be ') : '') +
1345
+ needtype + ', but found ' +
1346
+ (null != v ? vt + ': ' : '') + vs +
1347
+ // Uncomment to help debug validation errors.
1348
+ // ' [' + _whence + ']' +
1349
+ '.';
1350
+ }
1351
+ // Default inject handler for transforms. If the path resolves to a function,
1352
+ // call the function passing the injection inj. This is how transforms operate.
1353
+ const _injecthandler = (inj, val, current, ref, store) => {
1354
+ let out = val;
1355
+ const iscmd = isfunc(val) && (UNDEF === ref || ref.startsWith(S_DS));
1356
+ // Only call val function if it is a special command ($NAME format).
1357
+ if (iscmd) {
1358
+ out = val(inj, val, current, ref, store);
1359
+ }
1360
+ // Update parent with value. Ensures references remain in node tree.
1361
+ else if (S_MVAL === inj.mode && inj.full) {
1362
+ // _setparentprop(inj, val)
1363
+ inj.setval(val);
1364
+ }
1365
+ return out;
1366
+ };
1367
+ // Inject values from a data store into a string. Not a public utility - used by
1368
+ // `inject`. Inject are marked with `path` where path is resolved
1369
+ // with getpath against the store or current (if defined)
1370
+ // arguments. See `getpath`. Custom injection handling can be
1371
+ // provided by inj.handler (this is used for transform functions).
1372
+ // The path can also have the special syntax $NAME999 where NAME is
1373
+ // upper case letters only, and 999 is any digits, which are
1374
+ // discarded. This syntax specifies the name of a transform, and
1375
+ // optionally allows transforms to be ordered by alphanumeric sorting.
1376
+ function _injectstr(val, store, current, inj) {
1377
+ // Can't inject into non-strings
1378
+ if (S_string !== typeof val || S_MT === val) {
1379
+ return S_MT;
1380
+ }
1381
+ let out = val;
1382
+ // Pattern examples: "`a.b.c`", "`$NAME`", "`$NAME1`"
1383
+ const m = val.match(/^`(\$[A-Z]+|[^`]+)[0-9]*`$/);
1384
+ // Full string of the val is an injection.
1385
+ if (m) {
1386
+ if (null != inj) {
1387
+ inj.full = true;
1388
+ }
1389
+ let pathref = m[1];
1390
+ // Special escapes inside injection.
1391
+ pathref =
1392
+ 3 < pathref.length ? pathref.replace(/\$BT/g, S_BT).replace(/\$DS/g, S_DS) : pathref;
1393
+ // Get the extracted path reference.
1394
+ out = getpath(pathref, store, current, inj);
1395
+ }
1396
+ else {
1397
+ // Check for injections within the string.
1398
+ const partial = (_m, ref) => {
1399
+ // Special escapes inside injection.
1400
+ ref = 3 < ref.length ? ref.replace(/\$BT/g, S_BT).replace(/\$DS/g, S_DS) : ref;
1401
+ if (inj) {
1402
+ inj.full = false;
1403
+ }
1404
+ const found = getpath(ref, store, current, inj);
1405
+ // Ensure inject value is a string.
1406
+ return UNDEF === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found);
1407
+ };
1408
+ out = val.replace(/`([^`]+)`/g, partial);
1409
+ // Also call the inj handler on the entire string, providing the
1410
+ // option for custom injection.
1411
+ if (null != inj && isfunc(inj.handler)) {
1412
+ inj.full = true;
1413
+ out = inj.handler(inj, out, current, val, store);
1414
+ }
1415
+ }
1416
+ return out;
1417
+ }
1418
+ // Define a class to mirror the JavaScript implementation
1419
+ class StructUtility {
1420
+ constructor() {
1421
+ this.clone = clone;
1422
+ this.escre = escre;
1423
+ this.escurl = escurl;
1424
+ this.getelem = getelem;
1425
+ this.getpath = getpath;
1426
+ this.getprop = getprop;
1427
+ this.haskey = haskey;
1428
+ this.inject = inject;
1429
+ this.isempty = isempty;
1430
+ this.isfunc = isfunc;
1431
+ this.iskey = iskey;
1432
+ this.islist = islist;
1433
+ this.ismap = ismap;
1434
+ this.isnode = isnode;
1435
+ this.items = items;
1436
+ this.joinurl = joinurl;
1437
+ this.keysof = keysof;
1438
+ this.merge = merge;
1439
+ this.pad = pad;
1440
+ this.pathify = pathify;
1441
+ this.setprop = setprop;
1442
+ this.size = size;
1443
+ this.slice = slice;
1444
+ this.strkey = strkey;
1445
+ this.stringify = stringify;
1446
+ this.transform = transform;
1447
+ this.typify = typify;
1448
+ this.validate = validate;
1449
+ this.walk = walk;
1450
+ }
1451
+ }
1452
+ exports.StructUtility = StructUtility;
1453
+ //# sourceMappingURL=struct.js.map