@voxgig/struct 0.0.9 → 0.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.
@@ -1,6 +1,6 @@
1
- /* Copyright (c) 2025 Voxgig Ltd. MIT LICENSE. */
1
+ /* Copyright (c) 2025-2026 Voxgig Ltd. MIT LICENSE. */
2
2
 
3
- // VERSION: @voxgig/struct 0.0.9
3
+ // VERSION: @voxgig/struct 0.1.0
4
4
 
5
5
  /* Voxgig Struct
6
6
  * =============
@@ -33,13 +33,15 @@
33
33
  * - stringify: human-friendly string version of a value.
34
34
  * - escre: escape a regular expresion string.
35
35
  * - escurl: escape a url.
36
- * - joinurl: join parts of a url, merging forward slashes.
36
+ * - join: join parts of a url, merging forward slashes.
37
37
  *
38
38
  * This set of functions and supporting utilities is designed to work
39
39
  * uniformly across many languages, meaning that some code that may be
40
40
  * functionally redundant in specific languages is still retained to
41
41
  * keep the code human comparable.
42
42
  *
43
+ * NOTE: Lists are assumed to be mutable and reference stable.
44
+ *
43
45
  * NOTE: In this code JSON nulls are in general *not* considered the
44
46
  * same as the undefined value in the given language. However most
45
47
  * JSON parsers do use the undefined value to represent JSON
@@ -54,16 +56,16 @@
54
56
 
55
57
  // String constants are explicitly defined.
56
58
 
57
- // Mode value for inject step.
58
- const S_MKEYPRE = 'key:pre'
59
- const S_MKEYPOST = 'key:post'
60
- const S_MVAL = 'val'
61
- const S_MKEY = 'key'
59
+ // Mode value for inject step (bitfield).
60
+ const M_KEYPRE = 1
61
+ const M_KEYPOST = 2
62
+ const M_VAL = 4
62
63
 
63
- // Special keys.
64
+ // Special strings.
64
65
  const S_BKEY = '`$KEY`'
65
66
  const S_BANNO = '`$ANNO`'
66
67
  const S_BEXACT = '`$EXACT`'
68
+ const S_BVAL = '`$VAL`'
67
69
 
68
70
  const S_DKEY = '$KEY'
69
71
  const S_DTOP = '$TOP'
@@ -71,16 +73,26 @@ const S_DERRS = '$ERRS'
71
73
  const S_DSPEC = '$SPEC'
72
74
 
73
75
  // General strings.
74
- const S_array = 'array'
76
+ const S_list = 'list'
75
77
  const S_base = 'base'
76
78
  const S_boolean = 'boolean'
77
79
  const S_function = 'function'
80
+ const S_symbol = 'symbol'
78
81
  const S_instance = 'instance'
79
82
  const S_key = 'key'
83
+ const S_any = 'any'
84
+ const S_nil = 'nil'
80
85
  const S_null = 'null'
81
86
  const S_number = 'number'
82
87
  const S_object = 'object'
83
88
  const S_string = 'string'
89
+ const S_decimal = 'decimal'
90
+ const S_integer = 'integer'
91
+ const S_map = 'map'
92
+ const S_scalar = 'scalar'
93
+ const S_node = 'node'
94
+
95
+ // Character strings.
84
96
  const S_BT = '`'
85
97
  const S_CN = ':'
86
98
  const S_CS = ']'
@@ -91,14 +103,57 @@ const S_KEY = 'KEY'
91
103
  const S_MT = ''
92
104
  const S_OS = '['
93
105
  const S_SP = ' '
106
+ const S_CM = ','
94
107
  const S_VIZ = ': '
95
108
 
109
+ // Types
110
+ let t = 31
111
+ const T_any = (1 << t--) - 1
112
+ const T_noval = 1 << t-- // Means property absent, undefined. Also NOT a scalar!
113
+ const T_boolean = 1 << t--
114
+ const T_decimal = 1 << t--
115
+ const T_integer = 1 << t--
116
+ const T_number = 1 << t--
117
+ const T_string = 1 << t--
118
+ const T_function = 1 << t--
119
+ const T_symbol = 1 << t--
120
+ const T_null = 1 << t-- // The actual JSON null value.
121
+ t -= 7
122
+ const T_list = 1 << t--
123
+ const T_map = 1 << t--
124
+ const T_instance = 1 << t--
125
+ t -= 4
126
+ const T_scalar = 1 << t--
127
+ const T_node = 1 << t--
128
+
129
+ const TYPENAME = [
130
+ S_any,
131
+ S_nil,
132
+ S_boolean,
133
+ S_decimal,
134
+ S_integer,
135
+ S_number,
136
+ S_string,
137
+ S_function,
138
+ S_symbol,
139
+ S_null,
140
+ '', '', '',
141
+ '', '', '', '',
142
+ S_list,
143
+ S_map,
144
+ S_instance,
145
+ '', '', '', '',
146
+ S_scalar,
147
+ S_node,
148
+ ]
96
149
 
97
150
  // The standard undefined value for this language.
98
- const UNDEF = undefined
151
+ const NONE = undefined
99
152
 
100
- // Private marker to indicate a skippable value.
153
+ // Private markers
101
154
  const SKIP = { '`$SKIP`': true }
155
+ const DELETE = { '`$DELETE`': true }
156
+
102
157
 
103
158
  // Regular expression constants
104
159
  const R_INTEGER_KEY = /^[-0-9]+$/ // Match integer keys (including <0).
@@ -108,7 +163,7 @@ const R_LEADING_TRAILING_SLASH = /([^\/])\/+/ // Multiple slashes in UR
108
163
  const R_LEADING_SLASH = /^\/+/ // Leading slashes in URLs.
109
164
  const R_QUOTES = /"/g // Double quotes for removal.
110
165
  const R_DOT = /\./g // Dots in path strings.
111
- const R_FUNCTION_REF = /^`\$FUNCTION:([0-9]+)`$/ // Function reference in clone.
166
+ const R_CLONE_REF = /^`\$REF:([0-9]+)`$/ // Copy reference in cloning.
112
167
  const R_META_PATH = /^([^$]+)\$([=~])(.+)$/ // Meta path syntax.
113
168
  const R_DOUBLE_DOLLAR = /\$\$/g // Double dollar escape sequence.
114
169
  const R_TRANSFORM_NAME = /`\$([A-Z]+)`/g // Transform command names.
@@ -117,6 +172,8 @@ const R_BT_ESCAPE = /\$BT/g // Backtick escape sequen
117
172
  const R_DS_ESCAPE = /\$DS/g // Dollar sign escape sequence.
118
173
  const R_INJECTION_PARTIAL = /`([^`]+)`/g // Partial string injection pattern.
119
174
 
175
+ // Default max depth (for walk etc).
176
+ const MAXDEPTH = 32
120
177
 
121
178
  // Keys are strings for maps, or integers for lists.
122
179
  type PropKey = string | number
@@ -128,8 +185,7 @@ type Indexable = { [key: string]: any } & { [key: number]: any }
128
185
  // For each key in a node (map or list), perform value injections in
129
186
  // three phases: on key value, before child, and then on key value again.
130
187
  // This mode is passed via the Injection structure.
131
- type InjectMode = 'key:pre' | 'key:post' | 'val'
132
-
188
+ type InjectMode = number
133
189
 
134
190
  // Handle value injections using backtick escape sequences:
135
191
  // - `a.b.c`: insert value at {a:{b:{c:1}}}
@@ -141,7 +197,6 @@ type Injector = (
141
197
  store: any, // Current source root value.
142
198
  ) => any
143
199
 
144
-
145
200
  // Apply a custom modification to injections.
146
201
  type Modify = (
147
202
  val: any, // Value.
@@ -151,11 +206,14 @@ type Modify = (
151
206
  store?: any, // Store, if any
152
207
  ) => void
153
208
 
154
-
155
209
  // Function applied to each node and leaf when walking a node structure depth first.
156
210
  // For {a:{b:1}} the call sequence args will be: b, 1, {b:1}, [a,b].
211
+ // NOTE: the `path` array passed to the callback is reused across calls during
212
+ // a single walk (one shared array per depth). It is valid only for the
213
+ // duration of the callback invocation. If a callback needs to retain the
214
+ // path, it MUST clone it (e.g. `path.slice()`).
157
215
  type WalkApply = (
158
- // Map keys are strings, list keys are numbers, top key is UNDEF
216
+ // Map keys are strings, list keys are numbers, top key is NONE
159
217
  key: string | number | undefined,
160
218
  val: any,
161
219
  parent: any,
@@ -163,6 +221,20 @@ type WalkApply = (
163
221
  ) => any
164
222
 
165
223
 
224
+ // Return type string for narrowest type.
225
+ function typename(t: number) {
226
+ return getelem(TYPENAME, Math.clz32(t), TYPENAME[0])
227
+ }
228
+
229
+
230
+ // Get a defined value. Returns alt if val is undefined.
231
+ function getdef(val: any, alt: any) {
232
+ if (NONE === val) {
233
+ return alt
234
+ }
235
+ return val
236
+ }
237
+
166
238
 
167
239
  // Value is a node - defined, and a map (hash) or list (array).
168
240
  // NOTE: typescript
@@ -232,11 +304,14 @@ function size(val: any): number {
232
304
  }
233
305
 
234
306
 
235
- // Extract part of an array or string into a new value, from the start point to the end point.
236
- // If no end is specified, extract to the full length of the value. Negative arguments count
237
- // from the end of the value. For numbers, perform min and max bounding, where start is
238
- // inclusive, and end is *exclusive*.
239
- function slice<V extends any>(val: V, start?: number, end?: number): V {
307
+ // Extract part of an array or string into a new value, from the start
308
+ // point to the end point. If no end is specified, extract to the
309
+ // full length of the value. Negative arguments count from the end of
310
+ // the value. For numbers, perform min and max bounding, where start
311
+ // is inclusive, and end is *exclusive*.
312
+ // NOTE: input lists are not mutated by default. Use the mutate
313
+ // argument to mutate lists in place.
314
+ function slice<V extends any>(val: V, start?: number, end?: number, mutate?: boolean): V {
240
315
  if (S_number === typeof val) {
241
316
  start = null == start || S_number !== typeof start ? Number.MIN_SAFE_INTEGER : start
242
317
  end = (null == end || S_number !== typeof end ? Number.MAX_SAFE_INTEGER : end) - 1
@@ -280,7 +355,15 @@ function slice<V extends any>(val: V, start?: number, end?: number): V {
280
355
 
281
356
  if (-1 < start && start <= end && end <= vlen) {
282
357
  if (islist(val)) {
283
- val = val.slice(start, end) as V
358
+ if (mutate) {
359
+ for (let i = 0, j = start; j < end; i++, j++) {
360
+ val[i] = val[j]
361
+ }
362
+ val.length = (end - start)
363
+ }
364
+ else {
365
+ val = val.slice(start, end) as V
366
+ }
284
367
  }
285
368
  else if (S_string === typeof val) {
286
369
  val = (val as string).substring(start, end) as V
@@ -300,6 +383,7 @@ function slice<V extends any>(val: V, start?: number, end?: number): V {
300
383
  }
301
384
 
302
385
 
386
+ // String padding.
303
387
  function pad(str: any, padding?: number, padchar?: string): string {
304
388
  str = S_string === typeof str ? str : stringify(str)
305
389
  padding = null == padding ? 44 : padding
@@ -308,48 +392,71 @@ function pad(str: any, padding?: number, padchar?: string): string {
308
392
  }
309
393
 
310
394
 
311
- // Determine the type of a value as a string.
312
- // Returns one of:
313
- // 'null', 'string', 'number', 'boolean', 'function', 'array', 'object', 'instance'
314
- // where 'instance' is an instance of a class, and 'null' is undefined, null, or NaN.
315
- // Normalizes and simplifies JavaScript's type system for consistency.
316
- function typify(value: any): string {
317
- if (value === null || value === undefined) {
318
- return S_null
395
+ // Determine the type of a value as a bit code.
396
+ function typify(value: any): number {
397
+
398
+ if (undefined === value) {
399
+ return T_noval
319
400
  }
320
401
 
321
- const type = typeof value
402
+ const typestr = typeof value
403
+
404
+ if (null === value) {
405
+ return T_scalar | T_null
406
+ }
407
+ else if (S_number === typestr) {
408
+ if (Number.isInteger(value)) {
409
+ return T_scalar | T_number | T_integer
410
+ }
411
+ else if (isNaN(value)) {
412
+ return T_noval
413
+ }
414
+ else {
415
+ return T_scalar | T_number | T_decimal
416
+ }
417
+ }
418
+ else if (S_string === typestr) {
419
+ return T_scalar | T_string
420
+ }
421
+ else if (S_boolean === typestr) {
422
+ return T_scalar | T_boolean
423
+ }
424
+ else if (S_function === typestr) {
425
+ return T_scalar | T_function
426
+ }
322
427
 
323
- if (S_number === type && isNaN(value)) {
324
- return S_null
428
+ // For languages that have symbolic atoms.
429
+ else if (S_symbol === typestr) {
430
+ return T_scalar | T_symbol
325
431
  }
326
432
 
327
- if (Array.isArray(value)) {
328
- return S_array
433
+ else if (Array.isArray(value)) {
434
+ return T_node | T_list
329
435
  }
330
436
 
331
- if (type === 'object') {
437
+ else if (S_object === typestr) {
332
438
 
333
439
  if (value.constructor instanceof Function) {
334
440
  let cname = value.constructor.name
335
441
  if ('Object' !== cname && 'Array' !== cname) {
336
- return S_instance
442
+ return T_node | T_instance
337
443
  }
338
444
  }
339
445
 
340
- return S_object
446
+ return T_node | T_map
341
447
  }
342
448
 
343
- return type
449
+ // Anything else (e.g. bigint) is considered T_any
450
+ return T_any
344
451
  }
345
452
 
346
453
 
347
454
  // Get a list element. The key should be an integer, or a string
348
455
  // that can parse to an integer only. Negative integers count from the end of the list.
349
456
  function getelem(val: any, key: any, alt?: any) {
350
- let out = UNDEF
457
+ let out = NONE
351
458
 
352
- if (UNDEF === val || UNDEF === key) {
459
+ if (NONE === val || NONE === key) {
353
460
  return alt
354
461
  }
355
462
 
@@ -363,8 +470,8 @@ function getelem(val: any, key: any, alt?: any) {
363
470
  }
364
471
  }
365
472
 
366
- if (UNDEF === out) {
367
- return alt
473
+ if (NONE === out) {
474
+ return 0 < (T_function & typify(alt)) ? alt() : alt
368
475
  }
369
476
 
370
477
  return out
@@ -376,7 +483,7 @@ function getelem(val: any, key: any, alt?: any) {
376
483
  function getprop(val: any, key: any, alt?: any) {
377
484
  let out = alt
378
485
 
379
- if (UNDEF === val || UNDEF === key) {
486
+ if (NONE === val || NONE === key) {
380
487
  return alt
381
488
  }
382
489
 
@@ -384,7 +491,7 @@ function getprop(val: any, key: any, alt?: any) {
384
491
  out = val[key]
385
492
  }
386
493
 
387
- if (UNDEF === out) {
494
+ if (NONE === out) {
388
495
  return alt
389
496
  }
390
497
 
@@ -397,20 +504,20 @@ function getprop(val: any, key: any, alt?: any) {
397
504
  // Number keys are converted to strings.
398
505
  // Floats are truncated to integers.
399
506
  // Booleans, objects, arrays, null, undefined all return empty string.
400
- function strkey(key: any = UNDEF): string {
401
- if (UNDEF === key) {
507
+ function strkey(key: any = NONE): string {
508
+ if (NONE === key) {
402
509
  return S_MT
403
510
  }
404
511
 
405
- if (typeof key === S_string) {
512
+ const t = typify(key)
513
+
514
+ if (0 < (T_string & t)) {
406
515
  return key
407
516
  }
408
-
409
- if (typeof key === S_boolean) {
517
+ else if (0 < (T_boolean & t)) {
410
518
  return S_MT
411
519
  }
412
-
413
- if (typeof key === S_number) {
520
+ else if (0 < (T_number & t)) {
414
521
  return key % 1 === 0 ? String(key) : String(Math.floor(key))
415
522
  }
416
523
 
@@ -419,6 +526,7 @@ function strkey(key: any = UNDEF): string {
419
526
 
420
527
 
421
528
  // Sorted keys of a map, or indexes (as strings) of a list.
529
+ // Root utility - only uses language facilities.
422
530
  function keysof(val: any): string[] {
423
531
  return !isnode(val) ? [] :
424
532
  ismap(val) ? Object.keys(val).sort() : (val as any).map((_n: any, i: number) => S_MT + i)
@@ -426,22 +534,60 @@ function keysof(val: any): string[] {
426
534
 
427
535
 
428
536
  // Value of property with name key in node val is defined.
537
+ // Root utility - only uses language facilities.
429
538
  function haskey(val: any, key: any) {
430
- return UNDEF !== getprop(val, key)
539
+ return NONE !== getprop(val, key)
431
540
  }
432
541
 
433
542
 
434
543
  // List the sorted keys of a map or list as an array of tuples of the form [key, value].
435
544
  // As with keysof, list indexes are converted to strings.
436
- function items(val: any): [string, any][] {
437
- return keysof(val).map((k: any) => [k, val[k]])
545
+ // Root utility - only uses language facilities.
546
+ function items(val: any): [string, any][];
547
+ function items<T>(val: any, apply: (item: [string, any]) => T): T[];
548
+ function items(
549
+ val: any,
550
+ apply?: (item: [string, any]) => any
551
+ ): any[] {
552
+ let out: [string, any][] = keysof(val).map((k: any) => [k, val[k]])
553
+ if (null != apply) {
554
+ out = out.map(apply)
555
+ }
556
+ return out
557
+ }
558
+
559
+
560
+ // To replicate the array spread operator:
561
+ // a=1, b=[2,3], c=[4,5]
562
+ // [a,...b,c] -> [1,2,3,[4,5]]
563
+ // flatten([a,b,[c]]) -> [1,2,3,[4,5]]
564
+ // NOTE: [c] ensures c is not expanded
565
+ function flatten(list: any[], depth?: number) {
566
+ if (!islist(list)) {
567
+ return list
568
+ }
569
+ return list.flat(getdef(depth, 1))
570
+ }
571
+
572
+
573
+ // Filter item values using check function.
574
+ function filter(val: any, check: (item: [string, any]) => boolean): any[] {
575
+ let all = items(val)
576
+ let numall = size(all)
577
+ let out = []
578
+ for (let i = 0; i < numall; i++) {
579
+ if (check(all[i])) {
580
+ out.push(all[i][1])
581
+ }
582
+ }
583
+ return out
438
584
  }
439
585
 
440
586
 
441
587
  // Escape regular expression.
442
588
  function escre(s: string) {
443
- s = null == s ? S_MT : s
444
- return s.replace(R_ESCAPE_REGEXP, '\\$&')
589
+ // s = null == s ? S_MT : s
590
+ return replace(s, R_ESCAPE_REGEXP, '\\$&')
445
591
  }
446
592
 
447
593
 
@@ -452,16 +598,59 @@ function escurl(s: string) {
452
598
  }
453
599
 
454
600
 
455
- // Concatenate url part strings, merging forward slashes as needed.
456
- function joinurl(sarr: any[]) {
457
- return sarr
458
- .filter(s => null != s && S_MT !== s)
459
- .map((s, i) => 0 === i ? s.replace(R_TRAILING_SLASH, S_MT) :
460
- s.replace(R_LEADING_TRAILING_SLASH, '$1/')
461
- .replace(R_LEADING_SLASH, S_MT)
462
- .replace(R_TRAILING_SLASH, S_MT))
463
- .filter(s => S_MT !== s)
464
- .join(S_FS)
601
+ // Replace a search string (all), or a regexp, in a source string.
602
+ function replace(s: string, from: string | RegExp, to: any) {
603
+ let rs = s
604
+ let ts = typify(s)
605
+ if (0 === (T_string & ts)) {
606
+ rs = stringify(s)
607
+ }
608
+ else if (0 < ((T_noval | T_null) & ts)) {
609
+ rs = S_MT
610
+ }
611
+ else {
612
+ rs = stringify(s)
613
+ }
614
+ return rs.replace(from, to)
615
+ }
616
+
617
+
618
+ // Concatenate url part strings, merging sep char as needed.
619
+ function join(arr: any[], sep?: string, url?: boolean) {
620
+ const sarr = size(arr)
621
+ const sepdef = getdef(sep, S_CM)
622
+ const sepre = 1 === size(sepdef) ? escre(sepdef) : NONE
623
+ const out = filter(
624
+ items(
625
+ // filter(arr, (n) => null != n[1] && S_MT !== n[1]),
626
+ filter(arr, (n) => (0 < (T_string & typify(n[1]))) && S_MT !== n[1]),
627
+ (n) => {
628
+ let i = +n[0]
629
+ let s = n[1]
630
+
631
+ if (NONE !== sepre && S_MT !== sepre) {
632
+ if (url && 0 === i) {
633
+ s = replace(s, RegExp(sepre + '+$'), S_MT)
634
+ return s
635
+ }
636
+
637
+ if (0 < i) {
638
+ s = replace(s, RegExp('^' + sepre + '+'), S_MT)
639
+ }
640
+
641
+ if (i < sarr - 1 || !url) {
642
+ s = replace(s, RegExp(sepre + '+$'), S_MT)
643
+ }
644
+
645
+ s = replace(s, RegExp('([^' + sepre + '])' + sepre + '+([^' + sepre + '])'),
646
+ '$1' + sepdef + '$2')
647
+ }
648
+
649
+ return s
650
+ }), (n) => S_MT !== n[1])
651
+ .join(sepdef)
652
+
653
+ return out
465
654
  }
466
655
 
467
656
 
@@ -470,19 +659,27 @@ function joinurl(sarr: any[]) {
470
659
  // In general, the behaivor of of JavaScript's JSON.stringify(val,null,2) is followed.
471
660
  function jsonify(val: any, flags?: { indent?: number, offset?: number }) {
472
661
  let str = S_null
662
+
473
663
  if (null != val) {
474
- const indent = getprop(flags, 'indent', 2)
475
- str = JSON.stringify(val, null, indent)
476
- if (UNDEF === str) {
477
- str = S_null
664
+ try {
665
+ const indent = getprop(flags, 'indent', 2)
666
+ str = JSON.stringify(val, null, indent)
667
+ if (NONE === str) {
668
+ str = S_null
669
+ }
670
+ const offset = getprop(flags, 'offset', 0)
671
+ if (0 < offset) {
672
+ // Left offset entire indented JSON so that it aligns with surrounding code
673
+ // indented by offset. Assume first brace is on line with asignment, so not offset.
674
+ str = '{\n' +
675
+ join(
676
+ items(
677
+ slice(str.split('\n'), 1),
678
+ (n: any) => pad(n[1], 0 - offset - size(n[1]))), '\n')
679
+ }
478
680
  }
479
- const offset = getprop(flags, 'offset', 0)
480
- if (0 < offset) {
481
- // Left offset entire indented JSON so that it aligns with surrounding code
482
- // indented by offset.
483
- str = '{\n' + str.split('\n').slice(1)
484
- .map(n => pad(n, 0 - offset - size(n)))
485
- .join('\n')
681
+ catch (e: any) {
682
+ str = '__JSONIFY_FAILED__'
486
683
  }
487
684
  }
488
685
 
@@ -495,7 +692,7 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
495
692
  let valstr = S_MT
496
693
  pretty = !!pretty
497
694
 
498
- if (UNDEF === val) {
695
+ if (NONE === val) {
499
696
  return pretty ? '<>' : valstr
500
697
  }
501
698
 
@@ -511,9 +708,9 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
511
708
  !Array.isArray(val)
512
709
  ) {
513
710
  const sortedObj: any = {}
514
- for (const k of Object.keys(val).sort()) {
515
- sortedObj[k] = val[k]
516
- }
711
+ items(val, (n) => {
712
+ sortedObj[n[0]] = val[n[0]]
713
+ })
517
714
  return sortedObj
518
715
  }
519
716
  return val
@@ -521,7 +718,7 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
521
718
  valstr = valstr.replace(R_QUOTES, S_MT)
522
719
  }
523
720
  catch (err: any) {
524
- valstr = S_MT + val
721
+ valstr = '__STRINGIFY_FAILED__'
525
722
  }
526
723
  }
527
724
 
@@ -532,8 +729,9 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
532
729
 
533
730
  if (pretty) {
534
731
  // Indicate deeper JSON levels with different terminal colors (simplistic wrt strings).
535
- let c = [81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69]
536
- .map(n => `\x1b[38;5;${n}m`),
732
+ let c = items(
733
+ [81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69],
734
+ (n) => '\x1b[38;5;' + n[1] + 'm'),
537
735
  r = '\x1b[0m', d = 0, o = c[0], t = o
538
736
  for (const ch of valstr) {
539
737
  if (ch === '{' || ch === '[') {
@@ -554,34 +752,34 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
554
752
 
555
753
  // Build a human friendly path string.
556
754
  function pathify(val: any, startin?: number, endin?: number) {
557
- let pathstr: string | undefined = UNDEF
755
+ let pathstr: string | undefined = NONE
558
756
 
559
757
  let path: any[] | undefined = islist(val) ? val :
560
758
  S_string == typeof val ? [val] :
561
759
  S_number == typeof val ? [val] :
562
- UNDEF
760
+ NONE
563
761
 
564
762
  const start = null == startin ? 0 : -1 < startin ? startin : 0
565
763
  const end = null == endin ? 0 : -1 < endin ? endin : 0
566
764
 
567
- if (UNDEF != path && 0 <= start) {
765
+ if (NONE != path && 0 <= start) {
568
766
  path = slice(path, start, path.length - end)
569
767
  if (0 === path.length) {
570
768
  pathstr = '<root>'
571
769
  }
572
770
  else {
573
- pathstr = path
574
- // .filter((p: any, t: any) => (t = typeof p, S_string === t || S_number === t))
575
- .filter((p: any) => iskey(p))
576
- .map((p: any) =>
577
- S_number === typeof p ? S_MT + Math.floor(p) :
578
- p.replace(R_DOT, S_MT))
579
- .join(S_DT)
771
+ pathstr = join(
772
+ items(
773
+ filter(path, (n) => iskey(n[1])), (n) => {
774
+ let p = n[1]
775
+ return S_number === typeof p ? S_MT + Math.floor(p) :
776
+ p.replace(R_DOT, S_MT)
777
+ }), S_DT)
580
778
  }
581
779
  }
582
780
 
583
- if (UNDEF === pathstr) {
584
- pathstr = '<unknown-path' + (UNDEF === val ? S_MT : S_CN + stringify(val, 47)) + '>'
781
+ if (NONE === pathstr) {
782
+ pathstr = '<unknown-path' + (NONE === val ? S_MT : S_CN + stringify(val, 47)) + '>'
585
783
  }
586
784
 
587
785
  return pathstr
@@ -589,19 +787,21 @@ function pathify(val: any, startin?: number, endin?: number) {
589
787
 
590
788
 
591
789
  // Clone a JSON-like data structure.
592
- // NOTE: function value references are copied, *not* cloned.
790
+ // NOTE: function and instance values are copied, *not* cloned.
593
791
  function clone(val: any): any {
594
792
  const refs: any[] = []
595
- const replacer: any = (_k: any, v: any) => S_function === typeof v ?
596
- (refs.push(v), '`$FUNCTION:' + (refs.length - 1) + '`') : v
793
+ const reftype = T_function | T_instance
794
+ const replacer: any = (_k: any, v: any) => 0 < (reftype & typify(v)) ?
795
+ (refs.push(v), '`$REF:' + (refs.length - 1) + '`') : v
597
796
  const reviver: any = (_k: any, v: any, m: any) => S_string === typeof v ?
598
- (m = v.match(R_FUNCTION_REF), m ? refs[m[1]] : v) : v
599
- return UNDEF === val ? UNDEF : JSON.parse(JSON.stringify(val, replacer), reviver)
797
+ (m = v.match(R_CLONE_REF), m ? refs[m[1]] : v) : v
798
+ const out = NONE === val ? NONE : JSON.parse(JSON.stringify(val, replacer), reviver)
799
+ return out
600
800
  }
601
801
 
602
802
 
603
803
  // Define a JSON Object using function arguments.
604
- function jo(...kv: any[]): Record<string, any> {
804
+ function jm(...kv: any[]): Record<string, any> {
605
805
  const kvsize = size(kv)
606
806
  const o: any = {}
607
807
  for (let i = 0; i < kvsize; i += 2) {
@@ -614,7 +814,7 @@ function jo(...kv: any[]): Record<string, any> {
614
814
 
615
815
 
616
816
  // Define a JSON Array using function arguments.
617
- function ja(...v: any[]): any[] {
817
+ function jt(...v: any[]): any[] {
618
818
  const vsize = size(v)
619
819
  const a: any = new Array(vsize)
620
820
  for (let i = 0; i < vsize; i++) {
@@ -624,19 +824,18 @@ function ja(...v: any[]): any[] {
624
824
  }
625
825
 
626
826
 
627
-
628
827
  // Safely delete a property from an object or array element.
629
828
  // Undefined arguments and invalid keys are ignored.
630
829
  // Returns the (possibly modified) parent.
631
830
  // For objects, the property is deleted using the delete operator.
632
831
  // For arrays, the element at the index is removed and remaining elements are shifted down.
832
+ // NOTE: parent list may be new list, thus update references.
633
833
  function delprop<PARENT>(parent: PARENT, key: any): PARENT {
634
834
  if (!iskey(key)) {
635
835
  return parent
636
836
  }
637
837
 
638
838
  if (ismap(parent)) {
639
- // key = S_MT + key
640
839
  key = strkey(key)
641
840
  delete (parent as any)[key]
642
841
  }
@@ -651,10 +850,12 @@ function delprop<PARENT>(parent: PARENT, key: any): PARENT {
651
850
  keyI = Math.floor(keyI)
652
851
 
653
852
  // Delete list element at position keyI, shifting later elements down.
654
- if (0 <= keyI && keyI < parent.length) {
655
- for (let pI = keyI; pI < parent.length - 1; pI++) {
853
+ const psize = size(parent)
854
+ if (0 <= keyI && keyI < psize) {
855
+ for (let pI = keyI; pI < psize - 1; pI++) {
656
856
  parent[pI] = parent[pI + 1]
657
857
  }
858
+
658
859
  parent.length = parent.length - 1
659
860
  }
660
861
  }
@@ -667,6 +868,7 @@ function delprop<PARENT>(parent: PARENT, key: any): PARENT {
667
868
  // Returns the (possibly modified) parent.
668
869
  // If the parent is a list, and the key is negative, prepend the value.
669
870
  // NOTE: If the key is above the list size, append the value; below, prepend.
871
+ // NOTE: parent list may be new list, thus update references.
670
872
  function setprop<PARENT>(parent: PARENT, key: any, val: any): PARENT {
671
873
  if (!iskey(key)) {
672
874
  return parent
@@ -687,9 +889,11 @@ function setprop<PARENT>(parent: PARENT, key: any, val: any): PARENT {
687
889
 
688
890
  keyI = Math.floor(keyI)
689
891
 
892
+ // TODO: DELETE list element
893
+
690
894
  // Set or append value at position keyI, or append if keyI out of bounds.
691
895
  if (0 <= keyI) {
692
- parent[parent.length < keyI ? parent.length : keyI] = val
896
+ parent[slice(keyI, 0, size(parent) + 1)] = val
693
897
  }
694
898
 
695
899
  // Prepend value if keyI is negative
@@ -703,6 +907,11 @@ function setprop<PARENT>(parent: PARENT, key: any, val: any): PARENT {
703
907
 
704
908
 
705
909
  // Walk a data structure depth first, applying a function to each value.
910
+ // The `path` argument passed to the before/after callbacks is a single
911
+ // mutable array per depth, shared across all callback invocations for the
912
+ // lifetime of this top-level walk call. Callbacks that need to store the
913
+ // path MUST clone it (e.g. `path.slice()`); the contents will otherwise
914
+ // be overwritten by subsequent visits.
706
915
  function walk(
707
916
  // These arguments are the public interface.
708
917
  val: any,
@@ -719,23 +928,48 @@ function walk(
719
928
  // These areguments are used for recursive state.
720
929
  key?: string | number,
721
930
  parent?: any,
722
- path?: string[]
931
+ path?: string[],
932
+ pool?: string[][]
723
933
  ): any {
724
- let out = null == before ? val : before(key, val, parent, path || [])
934
+ if (NONE === pool) {
935
+ pool = [[]]
936
+ }
937
+ if (NONE === path) {
938
+ path = pool[0]
939
+ }
725
940
 
726
- maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : 32
727
- if (0 === maxdepth || (null != path && 0 < maxdepth && maxdepth <= path.length)) {
941
+ const depth = path.length
942
+
943
+ let out = null == before ? val : before(key, val, parent, path)
944
+
945
+ maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : MAXDEPTH
946
+ if (0 === maxdepth || (0 < maxdepth && maxdepth <= depth)) {
728
947
  return out
729
948
  }
730
949
 
731
950
  if (isnode(out)) {
951
+ const childDepth = depth + 1
952
+ let childPath = pool[childDepth]
953
+ if (NONE === childPath) {
954
+ childPath = new Array(childDepth)
955
+ pool[childDepth] = childPath
956
+ }
957
+ // Sync prefix [0..depth-1] from the current path. Only needed once per
958
+ // parent: siblings share the same prefix and will each overwrite slot
959
+ // [depth] below.
960
+ for (let i = 0; i < depth; i++) {
961
+ childPath[i] = path[i]
962
+ }
963
+
732
964
  for (let [ckey, child] of items(out)) {
965
+ childPath[depth] = S_MT + ckey
733
966
  setprop(out, ckey, walk(
734
- child, before, after, maxdepth, ckey, out, [...(path || []), S_MT + ckey]))
967
+ child, before, after, maxdepth, ckey, out, childPath, pool
968
+ ))
735
969
  }
736
970
  }
737
971
 
738
- out = null == after ? out : after(key, out, parent, path || [])
972
+ out = null == after ? out : after(key, out, parent, path)
739
973
 
740
974
  return out
741
975
  }
@@ -746,7 +980,9 @@ function walk(
746
980
  // override each other, and do *not* merge. The first element is
747
981
  // modified.
748
982
  function merge(val: any, maxdepth?: number): any {
749
- let out: any = UNDEF
983
+ // const md: number = null == maxdepth ? MAXDEPTH : maxdepth < 0 ? 0 : maxdepth
984
+ const md: number = slice(maxdepth ?? MAXDEPTH, 0)
985
+ let out: any = NONE
750
986
 
751
987
  // Handle edge cases.
752
988
  if (!islist(val)) {
@@ -757,7 +993,7 @@ function merge(val: any, maxdepth?: number): any {
757
993
  const lenlist = list.length
758
994
 
759
995
  if (0 === lenlist) {
760
- return UNDEF
996
+ return NONE
761
997
  }
762
998
  else if (1 === lenlist) {
763
999
  return list[0]
@@ -788,8 +1024,12 @@ function merge(val: any, maxdepth?: number): any {
788
1024
  ) {
789
1025
  const pI = size(path)
790
1026
 
1027
+ if (md <= pI) {
1028
+ setprop(cur[pI - 1], key, val)
1029
+ }
1030
+
791
1031
  // Scalars just override directly.
792
- if (!isnode(val)) {
1032
+ else if (!isnode(val)) {
793
1033
  cur[pI] = val
794
1034
  }
795
1035
 
@@ -801,7 +1041,7 @@ function merge(val: any, maxdepth?: number): any {
801
1041
  const tval = dst[pI]
802
1042
 
803
1043
  // Destination empty, so create node (unless override is class instance).
804
- if (UNDEF === tval && S_instance !== typify(val)) {
1044
+ if (NONE === tval && 0 === (T_instance & typify(val))) {
805
1045
  cur[pI] = islist(val) ? [] : {}
806
1046
  }
807
1047
 
@@ -815,7 +1055,7 @@ function merge(val: any, maxdepth?: number): any {
815
1055
  cur[pI] = val
816
1056
 
817
1057
  // No need to descend when override wins (destination is discarded).
818
- val = UNDEF
1058
+ val = NONE
819
1059
  }
820
1060
  }
821
1061
 
@@ -826,7 +1066,6 @@ function merge(val: any, maxdepth?: number): any {
826
1066
  return val
827
1067
  }
828
1068
 
829
-
830
1069
  function after(
831
1070
  key: string | number | undefined,
832
1071
  _val: any,
@@ -837,7 +1076,7 @@ function merge(val: any, maxdepth?: number): any {
837
1076
  const target = cur[cI - 1]
838
1077
  const value = cur[cI]
839
1078
 
840
- // console.log('AFTER-PREP', pathify(path), '@', cI,
1079
+ // console.log('AFTER-PREP', pathify(path), '@', cI, cur, '|',
841
1080
  // stringify(key, -1, 1), stringify(value, -1, 1), 'T=', stringify(target, -1, 1))
842
1081
 
843
1082
  setprop(target, key, value)
@@ -846,22 +1085,71 @@ function merge(val: any, maxdepth?: number): any {
846
1085
 
847
1086
  // Walk overriding node, creating paths in output as needed.
848
1087
  out = walk(obj, before, after, maxdepth)
1088
+ // console.log('WALK-DONE', out, obj)
849
1089
  }
850
1090
  }
851
1091
 
1092
+ if (0 === md) {
1093
+ out = getelem(list, -1)
1094
+ out = islist(out) ? [] : ismap(out) ? {} : out
1095
+ }
1096
+
852
1097
  return out
853
1098
  }
854
1099
 
855
1100
 
1101
+ // Set a value using a path. Missing path parts are created.
1102
+ // String paths create only maps. Use a string list to create list parts.
1103
+ function setpath(
1104
+ store: any,
1105
+ path: number | string | string[],
1106
+ val: any,
1107
+ injdef?: Partial<Injection>
1108
+ ) {
1109
+ const pathType = typify(path)
1110
+
1111
+ const parts = 0 < (T_list & pathType) ? path :
1112
+ 0 < (T_string & pathType) ? (path as string).split(S_DT) :
1113
+ 0 < (T_number & pathType) ? [path] : NONE
1114
+
1115
+ if (NONE === parts) {
1116
+ return NONE
1117
+ }
1118
+
1119
+ const base = getprop(injdef, S_base)
1120
+ const numparts = size(parts)
1121
+ let parent = getprop(store, base, store)
1122
+
1123
+ for (let pI = 0; pI < numparts - 1; pI++) {
1124
+ const partKey = getelem(parts, pI)
1125
+ let nextParent = getprop(parent, partKey)
1126
+ if (!isnode(nextParent)) {
1127
+ nextParent = 0 < (T_number & typify(getelem(parts, pI + 1))) ? [] : {}
1128
+ setprop(parent, partKey, nextParent)
1129
+ }
1130
+ parent = nextParent
1131
+ }
1132
+
1133
+ if (DELETE === val) {
1134
+ delprop(parent, getelem(parts, -1))
1135
+ }
1136
+ else {
1137
+ setprop(parent, getelem(parts, -1), val)
1138
+ }
1139
+
1140
+ return parent
1141
+ }
1142
+
1143
+
856
1144
  function getpath(store: any, path: number | string | string[], injdef?: Partial<Injection>) {
857
1145
 
858
1146
  // Operate on a string array.
859
1147
  const parts = islist(path) ? path :
860
1148
  'string' === typeof path ? path.split(S_DT) :
861
- 'number' === typeof path ? [strkey(path)] : UNDEF
1149
+ 'number' === typeof path ? [strkey(path)] : NONE
862
1150
 
863
- if (UNDEF === parts) {
864
- return UNDEF
1151
+ if (NONE === parts) {
1152
+ return NONE
865
1153
  }
866
1154
 
867
1155
  // let root = store
@@ -893,7 +1181,7 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
893
1181
 
894
1182
  const dpath = getprop(injdef, 'dpath')
895
1183
 
896
- for (let pI = 0; UNDEF !== val && pI < parts.length; pI++) {
1184
+ for (let pI = 0; NONE !== val && pI < numparts; pI++) {
897
1185
  let part = parts[pI]
898
1186
 
899
1187
  if (injdef && S_DKEY === part) {
@@ -901,15 +1189,15 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
901
1189
  }
902
1190
  else if (injdef && part.startsWith('$GET:')) {
903
1191
  // $GET:path$ -> get store value, use as path part (string)
904
- part = stringify(getpath(src, part.substring(5, part.length - 1)))
1192
+ part = stringify(getpath(src, slice(part, 5, -1)))
905
1193
  }
906
1194
  else if (injdef && part.startsWith('$REF:')) {
907
1195
  // $REF:refpath$ -> get spec value, use as path part (string)
908
- part = stringify(getpath(getprop(store, S_DSPEC), part.substring(5, part.length - 1)))
1196
+ part = stringify(getpath(getprop(store, S_DSPEC), slice(part, 5, -1)))
909
1197
  }
910
1198
  else if (injdef && part.startsWith('$META:')) {
911
1199
  // $META:metapath$ -> get meta value, use as path part (string)
912
- part = stringify(getpath(getprop(injdef, 'meta'), part.substring(6, part.length - 1)))
1200
+ part = stringify(getpath(getprop(injdef, 'meta'), slice(part, 6, -1)))
913
1201
  }
914
1202
 
915
1203
  // $$ escapes $
@@ -932,14 +1220,16 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
932
1220
  val = dparent
933
1221
  }
934
1222
  else {
935
- const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1))
1223
+ // const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1))
1224
+ const fullpath = flatten([slice(dpath, 0 - ascends), parts.slice(pI + 1)])
936
1225
 
937
1226
  if (ascends <= size(dpath)) {
938
1227
  val = getpath(store, fullpath)
939
1228
  }
940
1229
  else {
941
- val = UNDEF
1230
+ val = NONE
942
1231
  }
1232
+
943
1233
  break
944
1234
  }
945
1235
  }
@@ -961,13 +1251,14 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
961
1251
  val = handler(injdef, val, ref, store)
962
1252
  }
963
1253
 
1254
+ // console.log('GETPATH', path, val)
1255
+
964
1256
  return val
965
1257
  }
966
1258
 
967
1259
 
968
-
969
1260
  // Inject values from a data store into a node recursively, resolving
970
- // paths against the store, or current if they are local. THe modify
1261
+ // paths against the store, or current if they are local. The modify
971
1262
  // argument allows custom modification of the result. The inj
972
1263
  // (Injection) argument is used to maintain recursive state.
973
1264
  function inject(
@@ -980,14 +1271,14 @@ function inject(
980
1271
 
981
1272
  // Create state if at root of injection. The input value is placed
982
1273
  // inside a virtual parent holder to simplify edge cases.
983
- if (UNDEF === injdef || null == injdef.mode) {
1274
+ if (NONE === injdef || null == injdef.mode) {
984
1275
  // Set up state assuming we are starting in the virtual parent.
985
1276
  inj = new Injection(val, { [S_DTOP]: val })
986
1277
  inj.dparent = store
987
1278
  inj.errs = getprop(store, S_DERRS, [])
988
1279
  inj.meta.__d = 0
989
1280
 
990
- if (UNDEF !== injdef) {
1281
+ if (NONE !== injdef) {
991
1282
  inj.modify = null == injdef.modify ? inj.modify : injdef.modify
992
1283
  inj.extra = null == injdef.extra ? inj.extra : injdef.extra
993
1284
  inj.meta = null == injdef.meta ? inj.meta : injdef.meta
@@ -997,6 +1288,9 @@ function inject(
997
1288
 
998
1289
  inj.descend()
999
1290
 
1291
+ // console.log('INJ-START', val, inj.mode, inj.key, inj.val,
1292
+ // 't=', inj.path, 'P=', inj.parent, 'dp=', inj.dparent, 'ST=', store.$TOP)
1293
+
1000
1294
  // Descend into node.
1001
1295
  if (isnode(val)) {
1002
1296
 
@@ -1004,21 +1298,29 @@ function inject(
1004
1298
  // Injection transforms ($FOO) are processed *after* other keys.
1005
1299
  // NOTE: the optional digits suffix of the transform can thus be
1006
1300
  // used to order the transforms.
1007
- let nodekeys = ismap(val) ? [
1008
- ...Object.keys(val).filter(k => !k.includes(S_DS)).sort(),
1009
- ...Object.keys(val).filter(k => k.includes(S_DS)).sort(),
1010
- ] : (val as any).map((_n: any, i: number) => i)
1011
1301
 
1302
+ let nodekeys: any[]
1303
+ nodekeys = keysof(val)
1304
+
1305
+ if (ismap(val)) {
1306
+ nodekeys = flatten([
1307
+ filter(nodekeys, (n => !n[1].includes(S_DS))),
1308
+ filter(nodekeys, (n => n[1].includes(S_DS))),
1309
+ ])
1310
+ }
1311
+ else {
1312
+ nodekeys = keysof(val)
1313
+ }
1012
1314
 
1013
1315
  // Each child key-value pair is processed in three injection phases:
1014
- // 1. inj.mode='key:pre' - Key string is injected, returning a possibly altered key.
1015
- // 2. inj.mode='val' - The child value is injected.
1016
- // 3. inj.mode='key:post' - Key string is injected again, allowing child mutation.
1316
+ // 1. inj.mode=M_KEYPRE - Key string is injected, returning a possibly altered key.
1317
+ // 2. inj.mode=M_VAL - The child value is injected.
1318
+ // 3. inj.mode=M_KEYPOST - Key string is injected again, allowing child mutation.
1017
1319
  for (let nkI = 0; nkI < nodekeys.length; nkI++) {
1018
1320
 
1019
1321
  const childinj = inj.child(nkI, nodekeys)
1020
1322
  const nodekey = childinj.key
1021
- childinj.mode = S_MKEYPRE
1323
+ childinj.mode = M_KEYPRE
1022
1324
 
1023
1325
  // Peform the key:pre mode injection on the child key.
1024
1326
  const prekey = _injectstr(nodekey, store, childinj)
@@ -1028,9 +1330,9 @@ function inject(
1028
1330
  nodekeys = childinj.keys
1029
1331
 
1030
1332
  // Prevent further processing by returning an undefined prekey
1031
- if (UNDEF !== prekey) {
1333
+ if (NONE !== prekey) {
1032
1334
  childinj.val = getprop(val, prekey)
1033
- childinj.mode = S_MVAL as InjectMode
1335
+ childinj.mode = M_VAL
1034
1336
 
1035
1337
  // Perform the val mode injection on the child value.
1036
1338
  // NOTE: return value is not used.
@@ -1041,7 +1343,7 @@ function inject(
1041
1343
  nodekeys = childinj.keys
1042
1344
 
1043
1345
  // Peform the key:post mode injection on the child key.
1044
- childinj.mode = S_MKEYPOST as InjectMode
1346
+ childinj.mode = M_KEYPOST
1045
1347
  _injectstr(nodekey, store, childinj)
1046
1348
 
1047
1349
  // The injection may modify child processing.
@@ -1053,7 +1355,7 @@ function inject(
1053
1355
 
1054
1356
  // Inject paths into string scalars.
1055
1357
  else if (S_string === valtype) {
1056
- inj.mode = S_MVAL as InjectMode
1358
+ inj.mode = M_VAL
1057
1359
  val = _injectstr(val, store, inj)
1058
1360
  if (SKIP !== val) {
1059
1361
  inj.setval(val)
@@ -1075,6 +1377,8 @@ function inject(
1075
1377
  )
1076
1378
  }
1077
1379
 
1380
+ // console.log('INJ-VAL', val)
1381
+
1078
1382
  inj.val = val
1079
1383
 
1080
1384
  // Original val reference may no longer be correct.
@@ -1087,21 +1391,22 @@ function inject(
1087
1391
 
1088
1392
  // Delete a key from a map or list.
1089
1393
  const transform_DELETE: Injector = (inj: Injection) => {
1090
- inj.setval(UNDEF)
1091
- return UNDEF
1394
+ inj.setval(NONE)
1395
+ return NONE
1092
1396
  }
1093
1397
 
1094
1398
 
1095
1399
  // Copy value from source data.
1096
1400
  const transform_COPY: Injector = (inj: Injection, _val: any) => {
1097
- const { mode, key } = inj
1401
+ const ijname = 'COPY'
1098
1402
 
1099
- let out = key
1100
- if (!mode.startsWith(S_MKEY)) {
1101
- out = getprop(inj.dparent, key)
1102
- inj.setval(out)
1403
+ if (!checkPlacement(M_VAL, ijname, T_any, inj)) {
1404
+ return NONE
1103
1405
  }
1104
1406
 
1407
+ let out = getprop(inj.dparent, inj.key)
1408
+ inj.setval(out)
1409
+
1105
1410
  return out
1106
1411
  }
1107
1412
 
@@ -1111,29 +1416,30 @@ const transform_COPY: Injector = (inj: Injection, _val: any) => {
1111
1416
  const transform_KEY: Injector = (inj: Injection) => {
1112
1417
  const { mode, path, parent } = inj
1113
1418
 
1114
- // Do nothing in val mode.
1115
- if (S_MVAL !== mode) {
1116
- return UNDEF
1419
+ // Do nothing in val mode - not an error.
1420
+ if (M_VAL !== mode) {
1421
+ return NONE
1117
1422
  }
1118
1423
 
1119
1424
  // Key is defined by $KEY meta property.
1120
1425
  const keyspec = getprop(parent, S_BKEY)
1121
- if (UNDEF !== keyspec) {
1426
+ if (NONE !== keyspec) {
1122
1427
  delprop(parent, S_BKEY)
1123
1428
  return getprop(inj.dparent, keyspec)
1124
1429
  }
1125
1430
 
1126
1431
  // Key is defined within general purpose $META object.
1127
- return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2))
1432
+ // return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2))
1433
+ return getprop(getprop(parent, S_BANNO), S_KEY, getelem(path, -2))
1128
1434
  }
1129
1435
 
1130
1436
 
1131
- // Annotatea node. Does nothing itself, just used by
1437
+ // Annotate node. Does nothing itself, just used by
1132
1438
  // other injectors, and is removed when called.
1133
1439
  const transform_ANNO: Injector = (inj: Injection) => {
1134
1440
  const { parent } = inj
1135
1441
  delprop(parent, S_BANNO)
1136
- return UNDEF
1442
+ return NONE
1137
1443
  }
1138
1444
 
1139
1445
 
@@ -1146,29 +1452,27 @@ const transform_MERGE: Injector = (inj: Injection) => {
1146
1452
  const { mode, key, parent } = inj
1147
1453
 
1148
1454
  // Ensures $MERGE is removed from parent list (val mode).
1149
- let out: any = UNDEF
1455
+ let out: any = NONE
1150
1456
 
1151
- if (S_MKEYPRE === mode) {
1457
+ if (M_KEYPRE === mode) {
1152
1458
  out = key
1153
1459
  }
1154
1460
 
1155
1461
  // Operate after child values have been transformed.
1156
- else if (S_MKEYPOST === mode) {
1462
+ else if (M_KEYPOST === mode) {
1157
1463
  out = key
1158
1464
 
1159
1465
  let args = getprop(parent, key)
1160
1466
  args = Array.isArray(args) ? args : [args]
1161
1467
 
1162
1468
  // Remove the $MERGE command from a parent map.
1163
- inj.setval(UNDEF)
1469
+ inj.setval(NONE)
1164
1470
 
1165
1471
  // Literals in the parent have precedence, but we still merge onto
1166
1472
  // the parent object, so that node tree references are not changed.
1167
- const mergelist = [parent, ...args, clone(parent)]
1473
+ const mergelist = flatten([[parent], args, [clone(parent)]])
1168
1474
 
1169
1475
  merge(mergelist)
1170
-
1171
- // return key
1172
1476
  }
1173
1477
 
1174
1478
  return out
@@ -1183,65 +1487,63 @@ const transform_EACH: Injector = (
1183
1487
  _ref: string,
1184
1488
  store: any
1185
1489
  ) => {
1490
+ const ijname = 'EACH'
1186
1491
 
1187
- // Remove arguments to avoid spurious processing.
1188
- if (null != inj.keys) {
1189
- inj.keys.length = 1
1492
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1493
+ return NONE
1190
1494
  }
1191
1495
 
1192
- if (S_MVAL !== inj.mode) {
1193
- return UNDEF
1194
- }
1496
+ // Remove remaining keys to avoid spurious processing.
1497
+ slice(inj.keys, 0, 1, true)
1195
1498
 
1196
- // Get arguments: ['`$EACH`', 'source-path', child-template].
1197
- const srcpath = getprop(inj.parent, 1)
1198
- const child = clone(getprop(inj.parent, 2))
1499
+ // const [err, srcpath, child] = injectorArgs([T_string, T_any], inj)
1500
+ const [err, srcpath, child] = injectorArgs([T_string, T_any], slice(inj.parent, 1))
1501
+ if (NONE !== err) {
1502
+ inj.errs.push('$' + ijname + ': ' + err)
1503
+ return NONE
1504
+ }
1199
1505
 
1200
1506
  // Source data.
1201
1507
  const srcstore = getprop(store, inj.base, store)
1202
1508
 
1203
1509
  const src = getpath(srcstore, srcpath, inj)
1510
+ const srctype = typify(src)
1204
1511
 
1205
1512
  // Create parallel data structures:
1206
1513
  // source entries :: child templates
1207
1514
  let tcur: any = []
1208
1515
  let tval: any = []
1209
1516
 
1210
- const tkey = inj.path[inj.path.length - 2]
1211
- const target = inj.nodes[inj.nodes.length - 2] || inj.nodes[inj.nodes.length - 1]
1517
+ const tkey = getelem(inj.path, -2)
1518
+ const target = getelem(inj.nodes, - 2, () => getelem(inj.nodes, -1))
1212
1519
 
1213
1520
  // Create clones of the child template for each value of the current soruce.
1214
- if (islist(src)) {
1215
- tval = src.map(() => clone(child))
1521
+ if (0 < (T_list & srctype)) {
1522
+ tval = items(src, () => clone(child))
1216
1523
  }
1217
- else if (ismap(src)) {
1218
- tval = Object.entries(src).map(n => ({
1219
- ...clone(child),
1220
-
1524
+ else if (0 < (T_map & srctype)) {
1525
+ tval = items(src, (n => merge([
1526
+ clone(child),
1221
1527
  // Make a note of the key for $KEY transforms.
1222
- [S_BANNO]: { KEY: n[0] }
1223
- }))
1528
+ { [S_BANNO]: { KEY: n[0] } }
1529
+ ], 1)))
1224
1530
  }
1225
1531
 
1226
1532
  let rval = []
1227
1533
 
1228
1534
  if (0 < size(tval)) {
1229
- tcur = null == src ? UNDEF : Object.values(src)
1535
+ tcur = null == src ? NONE : items(src, (n: [string, any]) => n[1])
1230
1536
 
1231
1537
  const ckey = getelem(inj.path, -2)
1232
1538
 
1233
1539
  const tpath = slice(inj.path, -1)
1234
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey]
1235
-
1540
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey])
1236
1541
 
1237
1542
  // Parent structure.
1238
-
1239
- // const ckey = getelem(cpath, -1)
1240
1543
  tcur = { [ckey]: tcur }
1241
1544
 
1242
- if (1 < tpath.length) {
1545
+ if (1 < size(tpath)) {
1243
1546
  const pkey = getelem(inj.path, -3, S_DTOP)
1244
- // const pkey = getelem(cpath, -2, S_DTOP)
1245
1547
  tcur = { [pkey]: tcur }
1246
1548
  dpath.push('$:' + pkey)
1247
1549
  }
@@ -1261,7 +1563,8 @@ const transform_EACH: Injector = (
1261
1563
  rval = tinj.val
1262
1564
  }
1263
1565
 
1264
- _updateAncestors(inj, target, tkey, rval)
1566
+ // _updateAncestors(inj, target, tkey, rval)
1567
+ setprop(target, tkey, rval)
1265
1568
 
1266
1569
  // Prevent callee from damaging first list entry (since we are in `val` mode).
1267
1570
  return rval[0]
@@ -1269,7 +1572,7 @@ const transform_EACH: Injector = (
1269
1572
 
1270
1573
 
1271
1574
  // Convert a node to a map.
1272
- // Format: { '`$PACK`':['`source-path`', child-template]}
1575
+ // Format: { '`$PACK`':['source-path', child-template]}
1273
1576
  const transform_PACK: Injector = (
1274
1577
  inj: Injection,
1275
1578
  _val: any,
@@ -1278,78 +1581,105 @@ const transform_PACK: Injector = (
1278
1581
  ) => {
1279
1582
  const { mode, key, path, parent, nodes } = inj
1280
1583
 
1281
- // Defensive context checks.
1282
- if (S_MKEYPRE !== mode || S_string !== typeof key || null == path || null == nodes) {
1283
- return UNDEF
1584
+ const ijname = 'EACH'
1585
+
1586
+ if (!checkPlacement(M_KEYPRE, ijname, T_map, inj)) {
1587
+ return NONE
1284
1588
  }
1285
1589
 
1286
1590
  // Get arguments.
1287
- const args = parent[key]
1288
- const srcpath = args[0] // Path to source data.
1289
- const child = clone(args[1]) // Child template.
1591
+ const args = getprop(parent, key)
1592
+ const [err, srcpath, origchildspec] = injectorArgs([T_string, T_any], args)
1593
+ if (NONE !== err) {
1594
+ inj.errs.push('$' + ijname + ': ' + err)
1595
+ return NONE
1596
+ }
1290
1597
 
1291
1598
  // Find key and target node.
1292
- const keyprop = child[S_BKEY]
1293
1599
  const tkey = getelem(path, -2)
1294
- const target = nodes[path.length - 2] || nodes[path.length - 1]
1600
+ const pathsize = size(path)
1601
+ const target = getelem(nodes, pathsize - 2, () => getelem(nodes, pathsize - 1))
1295
1602
 
1296
1603
  // Source data
1297
1604
  const srcstore = getprop(store, inj.base, store)
1298
-
1299
1605
  let src = getpath(srcstore, srcpath, inj)
1300
1606
 
1301
1607
  // Prepare source as a list.
1302
- src = islist(src) ? src :
1303
- ismap(src) ? Object.entries(src)
1304
- .reduce((a: any[], n: any) =>
1305
- (n[1][S_BANNO] = { KEY: n[0] }, a.push(n[1]), a), []) :
1306
- UNDEF
1608
+ if (!islist(src)) {
1609
+ if (ismap(src)) {
1610
+ src = items(src, (item: [string, any]) => {
1611
+ setprop(item[1], S_BANNO, { KEY: item[0] })
1612
+ return item[1]
1613
+ })
1614
+ }
1615
+ else {
1616
+ src = NONE
1617
+ }
1618
+ }
1307
1619
 
1308
1620
  if (null == src) {
1309
- return UNDEF
1621
+ return NONE
1310
1622
  }
1311
1623
 
1312
- // Get key if specified.
1313
- let childkey: PropKey | undefined = getprop(child, S_BKEY)
1314
- let keyname = UNDEF === childkey ? keyprop : childkey
1315
- delprop(child, S_BKEY)
1624
+ // Get keypath.
1625
+ const keypath = getprop(origchildspec, S_BKEY)
1626
+ const childspec = delprop(origchildspec, S_BKEY)
1627
+
1628
+ const child = getprop(childspec, S_BVAL, childspec)
1316
1629
 
1317
1630
  // Build parallel target object.
1318
1631
  let tval: any = {}
1319
- tval = src.reduce((a: any, n: any) => {
1320
- let kn = getprop(n, keyname)
1321
- setprop(a, kn, clone(child))
1322
- const nchild = getprop(a, kn)
1323
- const mval = getprop(n, S_BANNO)
1324
- if (UNDEF === mval) {
1325
- delprop(nchild, S_BANNO)
1632
+
1633
+ items(src, (item: [string, any]) => {
1634
+ const srckey = item[0]
1635
+ const srcnode = item[1]
1636
+
1637
+ let key: string = srckey
1638
+ if (NONE !== keypath) {
1639
+ if (keypath.startsWith('`')) {
1640
+ key = inject(keypath, merge([{}, store, { $TOP: srcnode }], 1))
1641
+ }
1642
+ else {
1643
+ key = getpath(srcnode, keypath, inj)
1644
+ }
1645
+ }
1646
+
1647
+ const tchild = clone(child)
1648
+ setprop(tval, key, tchild)
1649
+
1650
+ const anno = getprop(srcnode, S_BANNO)
1651
+ if (NONE === anno) {
1652
+ delprop(tchild, S_BANNO)
1326
1653
  }
1327
1654
  else {
1328
- setprop(nchild, S_BANNO, mval)
1655
+ setprop(tchild, S_BANNO, anno)
1329
1656
  }
1330
- return a
1331
- }, tval)
1657
+ })
1332
1658
 
1333
1659
  let rval = {}
1334
1660
 
1335
- if (0 < size(tval)) {
1661
+ if (!isempty(tval)) {
1336
1662
 
1337
1663
  // Build parallel source object.
1338
- let tcur: any = {}
1339
- src.reduce((a: any, n: any) => {
1340
- let kn = getprop(n, keyname)
1664
+ let tsrc: any = {}
1665
+ src.reduce((a: any, n: any, i: any) => {
1666
+ let kn = null == keypath ? i :
1667
+ keypath.startsWith('`') ?
1668
+ inject(keypath, merge([{}, store, { $TOP: n }], 1)) :
1669
+ getpath(n, keypath, inj)
1670
+
1341
1671
  setprop(a, kn, n)
1342
1672
  return a
1343
- }, tcur)
1673
+ }, tsrc)
1344
1674
 
1345
1675
  const tpath = slice(inj.path, -1)
1346
1676
 
1347
1677
  const ckey = getelem(inj.path, -2)
1348
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey]
1678
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey])
1349
1679
 
1350
- tcur = { [ckey]: tcur }
1680
+ let tcur = { [ckey]: tsrc }
1351
1681
 
1352
- if (1 < tpath.length) {
1682
+ if (1 < size(tpath)) {
1353
1683
  const pkey = getelem(inj.path, -3, S_DTOP)
1354
1684
  tcur = { [pkey]: tcur }
1355
1685
  dpath.push('$:' + pkey)
@@ -1359,7 +1689,6 @@ const transform_PACK: Injector = (
1359
1689
  tinj.path = tpath
1360
1690
  tinj.nodes = slice(inj.nodes, -1)
1361
1691
 
1362
- // tinj.parent = tcur
1363
1692
  tinj.parent = getelem(tinj.nodes, -1)
1364
1693
  tinj.val = tval
1365
1694
 
@@ -1370,14 +1699,15 @@ const transform_PACK: Injector = (
1370
1699
  rval = tinj.val
1371
1700
  }
1372
1701
 
1373
- _updateAncestors(inj, target, tkey, rval)
1702
+ // _updateAncestors(inj, target, tkey, rval)
1703
+ setprop(target, tkey, rval)
1374
1704
 
1375
1705
  // Drop transform key.
1376
- return UNDEF
1706
+ return NONE
1377
1707
  }
1378
1708
 
1379
1709
 
1380
- // TODO: not found ref should removed key (setprop UNDEF)
1710
+ // TODO: not found ref should removed key (setprop NONE)
1381
1711
  // Reference original spec (enables recursice transformations)
1382
1712
  // Format: ['`$REF`', '`spec-path`']
1383
1713
  const transform_REF: Injector = (
@@ -1388,21 +1718,24 @@ const transform_REF: Injector = (
1388
1718
  ) => {
1389
1719
  const { nodes } = inj
1390
1720
 
1391
- if (S_MVAL !== inj.mode) {
1392
- return UNDEF
1721
+ if (M_VAL !== inj.mode) {
1722
+ return NONE
1393
1723
  }
1394
1724
 
1395
1725
  // Get arguments: ['`$REF`', 'ref-path'].
1396
1726
  const refpath = getprop(inj.parent, 1)
1397
- inj.keyI = inj.keys.length
1727
+ inj.keyI = size(inj.keys)
1398
1728
 
1399
1729
  // Spec reference.
1400
1730
  const spec = getprop(store, S_DSPEC)()
1401
1731
 
1732
+ const dpath = slice(inj.path, 1)
1402
1733
  const ref = getpath(spec, refpath, {
1403
1734
  // TODO: test relative refs
1404
- dpath: inj.path.slice(1),
1405
- dparent: getpath(spec, inj.path.slice(1))
1735
+ // dpath: inj.path.slice(1),
1736
+ dpath,
1737
+ // dparent: getpath(spec, inj.path.slice(1))
1738
+ dparent: getpath(spec, dpath),
1406
1739
  })
1407
1740
 
1408
1741
  let hasSubRef = false
@@ -1421,9 +1754,9 @@ const transform_REF: Injector = (
1421
1754
  const tpath = slice(inj.path, -1)
1422
1755
  let tcur = getpath(store, cpath)
1423
1756
  let tval = getpath(store, tpath)
1424
- let rval = UNDEF
1757
+ let rval = NONE
1425
1758
 
1426
- if (!hasSubRef || UNDEF !== tval) {
1759
+ if (!hasSubRef || NONE !== tval) {
1427
1760
  const tinj = inj.child(0, [getelem(tpath, -1)])
1428
1761
 
1429
1762
  tinj.path = tpath
@@ -1431,7 +1764,7 @@ const transform_REF: Injector = (
1431
1764
  tinj.parent = getelem(nodes, -2)
1432
1765
  tinj.val = tref
1433
1766
 
1434
- tinj.dpath = [...cpath]
1767
+ tinj.dpath = flatten([cpath])
1435
1768
  tinj.dparent = tcur
1436
1769
 
1437
1770
  inject(tref, store, tinj)
@@ -1439,7 +1772,7 @@ const transform_REF: Injector = (
1439
1772
  rval = tinj.val
1440
1773
  }
1441
1774
  else {
1442
- rval = UNDEF
1775
+ rval = NONE
1443
1776
  }
1444
1777
 
1445
1778
  const grandparent = inj.setval(rval, 2)
@@ -1452,6 +1785,117 @@ const transform_REF: Injector = (
1452
1785
  }
1453
1786
 
1454
1787
 
1788
+ const transform_FORMAT: Injector = (
1789
+ inj: Injection,
1790
+ _val: any,
1791
+ _ref: string,
1792
+ store: any
1793
+ ) => {
1794
+ // console.log('FORMAT-START', inj, _val)
1795
+
1796
+ // Remove remaining keys to avoid spurious processing.
1797
+ slice(inj.keys, 0, 1, true)
1798
+
1799
+ if (M_VAL !== inj.mode) {
1800
+ return NONE
1801
+ }
1802
+
1803
+ // Get arguments: ['`$FORMAT`', 'name', child].
1804
+ // TODO: EACH and PACK should accept customm functions too
1805
+ const name = getprop(inj.parent, 1)
1806
+ const child = getprop(inj.parent, 2)
1807
+
1808
+ // Source data.
1809
+ const tkey = getelem(inj.path, -2)
1810
+ const target = getelem(inj.nodes, - 2, () => getelem(inj.nodes, -1))
1811
+
1812
+ const cinj = injectChild(child, store, inj)
1813
+ const resolved = cinj.val
1814
+
1815
+ let formatter = 0 < (T_function & typify(name)) ? name : getprop(FORMATTER, name)
1816
+
1817
+ if (NONE === formatter) {
1818
+ inj.errs.push('$FORMAT: unknown format: ' + name + '.')
1819
+ return NONE
1820
+ }
1821
+
1822
+ let out = walk(resolved, formatter)
1823
+
1824
+ setprop(target, tkey, out)
1825
+ // _updateAncestors(inj, target, tkey, out)
1826
+
1827
+ return out
1828
+ }
1829
+
1830
+
1831
+ const FORMATTER: Record<string, WalkApply> = {
1832
+ identity: (_k: any, v: any) => v,
1833
+ upper: (_k: any, v: any) => isnode(v) ? v : ('' + v).toUpperCase(),
1834
+ lower: (_k: any, v: any) => isnode(v) ? v : ('' + v).toLowerCase(),
1835
+ string: (_k: any, v: any) => isnode(v) ? v : ('' + v),
1836
+ number: (_k: any, v: any) => {
1837
+ if (isnode(v)) {
1838
+ return v
1839
+ }
1840
+ else {
1841
+ let n = Number(v)
1842
+ if (isNaN(n)) {
1843
+ n = 0
1844
+ }
1845
+ return n
1846
+ }
1847
+ },
1848
+ integer: (_k: any, v: any) => {
1849
+ if (isnode(v)) {
1850
+ return v
1851
+ }
1852
+ else {
1853
+ let n = Number(v)
1854
+ if (isNaN(n)) {
1855
+ n = 0
1856
+ }
1857
+ return n | 0
1858
+ }
1859
+ },
1860
+ concat: (k: any, v: any) =>
1861
+ null == k && islist(v) ? join(items(v, (n => isnode(n[1]) ? S_MT : (S_MT + n[1]))), S_MT) : v
1862
+ }
1863
+
1864
+
1865
+
1866
+ const transform_APPLY: Injector = (
1867
+ inj: Injection,
1868
+ _val: any,
1869
+ _ref: string,
1870
+ store: any
1871
+ ) => {
1872
+ const ijname = 'APPLY'
1873
+
1874
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1875
+ return NONE
1876
+ }
1877
+
1878
+ // const [err, apply, child] = injectorArgs([T_function, T_any], inj)
1879
+ const [err, apply, child] = injectorArgs([T_function, T_any], slice(inj.parent, 1))
1880
+ if (NONE !== err) {
1881
+ inj.errs.push('$' + ijname + ': ' + err)
1882
+ return NONE
1883
+ }
1884
+
1885
+ const tkey = getelem(inj.path, -2)
1886
+ const target = getelem(inj.nodes, - 2, () => getelem(inj.nodes, -1))
1887
+
1888
+ const cinj = injectChild(child, store, inj)
1889
+ const resolved = cinj.val
1890
+
1891
+ const out = apply(resolved, store, cinj)
1892
+
1893
+ setprop(target, tkey, out)
1894
+
1895
+ return out
1896
+ }
1897
+
1898
+
1455
1899
  // Transform data using spec.
1456
1900
  // Only operates on static JSON-like data.
1457
1901
  // Arrays are treated as if they are objects with indices as keys.
@@ -1465,51 +1909,66 @@ function transform(
1465
1909
  spec = clone(origspec)
1466
1910
 
1467
1911
  const extra = injdef?.extra
1468
- // const modify = injdef?.modify
1912
+
1913
+ const collect = null != injdef?.errs
1914
+ const errs = injdef?.errs || []
1469
1915
 
1470
1916
  const extraTransforms: any = {}
1471
- const extraData = null == extra ? UNDEF : items(extra)
1917
+ const extraData = null == extra ? NONE : items(extra)
1472
1918
  .reduce((a: any, n: any[]) =>
1473
1919
  (n[0].startsWith(S_DS) ? extraTransforms[n[0]] = n[1] : (a[n[0]] = n[1]), a), {})
1474
1920
 
1475
1921
  const dataClone = merge([
1476
- isempty(extraData) ? UNDEF : clone(extraData),
1922
+ isempty(extraData) ? NONE : clone(extraData),
1477
1923
  clone(data),
1478
1924
  ])
1479
1925
 
1480
1926
  // Define a top level store that provides transform operations.
1481
- const store = {
1927
+ const store = merge([
1928
+ {
1929
+ // The inject function recognises this special location for the root of the source data.
1930
+ // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1931
+ // place that data inside a holding map: { myholder: mydata }.
1932
+ $TOP: dataClone,
1933
+
1934
+ $SPEC: () => origspec,
1935
+
1936
+ // Escape backtick (this also works inside backticks).
1937
+ $BT: () => S_BT,
1938
+
1939
+ // Escape dollar sign (this also works inside backticks).
1940
+ $DS: () => S_DS,
1941
+
1942
+ // Insert current date and time as an ISO string.
1943
+ $WHEN: () => new Date().toISOString(),
1944
+
1945
+ $DELETE: transform_DELETE,
1946
+ $COPY: transform_COPY,
1947
+ $KEY: transform_KEY,
1948
+ $ANNO: transform_ANNO,
1949
+ $MERGE: transform_MERGE,
1950
+ $EACH: transform_EACH,
1951
+ $PACK: transform_PACK,
1952
+ $REF: transform_REF,
1953
+ $FORMAT: transform_FORMAT,
1954
+ $APPLY: transform_APPLY,
1955
+ },
1482
1956
 
1483
- // The inject function recognises this special location for the root of the source data.
1484
- // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1485
- // place that data inside a holding map: { myholder: mydata }.
1486
- $TOP: dataClone,
1487
-
1488
- $SPEC: () => origspec,
1489
-
1490
- // Escape backtick (this also works inside backticks).
1491
- $BT: () => S_BT,
1492
-
1493
- // Escape dollar sign (this also works inside backticks).
1494
- $DS: () => S_DS,
1957
+ // Custom extra transforms, if any.
1958
+ extraTransforms,
1495
1959
 
1496
- // Insert current date and time as an ISO string.
1497
- $WHEN: () => new Date().toISOString(),
1960
+ {
1961
+ $ERRS: errs,
1962
+ }
1963
+ ], 1)
1498
1964
 
1499
- $DELETE: transform_DELETE,
1500
- $COPY: transform_COPY,
1501
- $KEY: transform_KEY,
1502
- $ANNO: transform_ANNO,
1503
- $MERGE: transform_MERGE,
1504
- $EACH: transform_EACH,
1505
- $PACK: transform_PACK,
1506
- $REF: transform_REF,
1965
+ const out = inject(spec, store, injdef)
1507
1966
 
1508
- // Custom extra transforms, if any.
1509
- ...extraTransforms,
1967
+ const generr = (0 < size(errs) && !collect)
1968
+ if (generr) {
1969
+ throw new Error(join(errs, ' | '))
1510
1970
  }
1511
1971
 
1512
- const out = inject(spec, store, injdef)
1513
1972
  return out
1514
1973
  }
1515
1974
 
@@ -1519,16 +1978,16 @@ const validate_STRING: Injector = (inj: Injection) => {
1519
1978
  let out = getprop(inj.dparent, inj.key)
1520
1979
 
1521
1980
  const t = typify(out)
1522
- if (S_string !== t) {
1981
+ if (0 === (T_string & t)) {
1523
1982
  let msg = _invalidTypeMsg(inj.path, S_string, t, out, 'V1010')
1524
1983
  inj.errs.push(msg)
1525
- return UNDEF
1984
+ return NONE
1526
1985
  }
1527
1986
 
1528
1987
  if (S_MT === out) {
1529
1988
  let msg = 'Empty string at ' + pathify(inj.path, 1)
1530
1989
  inj.errs.push(msg)
1531
- return UNDEF
1990
+ return NONE
1532
1991
  }
1533
1992
 
1534
1993
  return out
@@ -1538,13 +1997,17 @@ const validate_STRING: Injector = (inj: Injection) => {
1538
1997
 
1539
1998
 
1540
1999
  const validate_TYPE: Injector = (inj: Injection, _val: any, ref: string) => {
1541
- let tname = slice(ref, 1).toLowerCase()
2000
+ const tname = slice(ref, 1).toLowerCase()
2001
+ const typev = 1 << (31 - TYPENAME.indexOf(tname))
1542
2002
  let out = getprop(inj.dparent, inj.key)
1543
2003
 
1544
2004
  const t = typify(out)
1545
- if (t !== tname) {
2005
+
2006
+ // console.log('TYPE', tname, typev, tn(typev), 'O=', t, tn(t), out, 'C=', t & typev)
2007
+
2008
+ if (0 === (t & typev)) {
1546
2009
  inj.errs.push(_invalidTypeMsg(inj.path, tname, t, out, 'V1001'))
1547
- return UNDEF
2010
+ return NONE
1548
2011
  }
1549
2012
 
1550
2013
  return out
@@ -1568,20 +2031,20 @@ const validate_CHILD: Injector = (inj: Injection) => {
1568
2031
  // Setup data structures for validation by cloning child template.
1569
2032
 
1570
2033
  // Map syntax.
1571
- if (S_MKEYPRE === mode) {
2034
+ if (M_KEYPRE === mode) {
1572
2035
  const childtm = getprop(parent, key)
1573
2036
 
1574
2037
  // Get corresponding current object.
1575
- const pkey = getprop(path, path.length - 2)
2038
+ const pkey = getelem(path, -2)
1576
2039
  let tval = getprop(inj.dparent, pkey)
1577
2040
 
1578
- if (UNDEF == tval) {
2041
+ if (NONE == tval) {
1579
2042
  tval = {}
1580
2043
  }
1581
2044
  else if (!ismap(tval)) {
1582
2045
  inj.errs.push(_invalidTypeMsg(
1583
2046
  slice(inj.path, -1), S_object, typify(tval), tval), 'V0220')
1584
- return UNDEF
2047
+ return NONE
1585
2048
  }
1586
2049
 
1587
2050
  const ckeys = keysof(tval)
@@ -1593,52 +2056,56 @@ const validate_CHILD: Injector = (inj: Injection) => {
1593
2056
  }
1594
2057
 
1595
2058
  // Remove $CHILD to cleanup ouput.
1596
- inj.setval(UNDEF)
1597
- return UNDEF
2059
+ inj.setval(NONE)
2060
+ return NONE
1598
2061
  }
1599
2062
 
1600
2063
  // List syntax.
1601
- if (S_MVAL === mode) {
2064
+ if (M_VAL === mode) {
1602
2065
 
1603
2066
  if (!islist(parent)) {
1604
2067
  // $CHILD was not inside a list.
1605
2068
  inj.errs.push('Invalid $CHILD as value')
1606
- return UNDEF
2069
+ return NONE
1607
2070
  }
1608
2071
 
1609
2072
  const childtm = getprop(parent, 1)
1610
2073
 
1611
- if (UNDEF === inj.dparent) {
2074
+ if (NONE === inj.dparent) {
1612
2075
  // Empty list as default.
1613
- parent.length = 0
1614
- return UNDEF
2076
+ // parent.length = 0
2077
+ slice(parent, 0, 0, true)
2078
+ return NONE
1615
2079
  }
1616
2080
 
1617
2081
  if (!islist(inj.dparent)) {
1618
2082
  const msg = _invalidTypeMsg(
1619
- slice(inj.path, -1), S_array, typify(inj.dparent), inj.dparent, 'V0230')
2083
+ slice(inj.path, -1), S_list, typify(inj.dparent), inj.dparent, 'V0230')
1620
2084
  inj.errs.push(msg)
1621
- inj.keyI = parent.length
2085
+ inj.keyI = size(parent)
1622
2086
  return inj.dparent
1623
2087
  }
1624
2088
 
1625
2089
  // Clone children abd reset inj key index.
1626
2090
  // The inject child loop will now iterate over the cloned children,
1627
2091
  // validating them againt the current list values.
1628
-
1629
- inj.dparent.map((_n, i) => parent[i] = clone(childtm))
1630
- parent.length = inj.dparent.length
2092
+ items(inj.dparent, (n) => setprop(parent, n[0], clone(childtm)))
2093
+ slice(parent, 0, inj.dparent.length, true)
1631
2094
  inj.keyI = 0
2095
+
1632
2096
  const out = getprop(inj.dparent, 0)
1633
2097
  return out
1634
2098
  }
1635
2099
 
1636
- return UNDEF
2100
+ return NONE
1637
2101
  }
1638
2102
 
1639
2103
 
2104
+ // TODO: implement SOME, ALL
2105
+ // FIX: ONE should mean exactly one, not at least one (=SOME)
2106
+ // TODO: implement a generate validate_ALT to do all of these
1640
2107
  // Match at least one of the specified shapes.
1641
- // Syntax: ['`$ONE`', alt0, alt1, ...]okI
2108
+ // Syntax: ['`$ONE`', alt0, alt1, ...]
1642
2109
  const validate_ONE: Injector = (
1643
2110
  inj: Injection,
1644
2111
  _val: any,
@@ -1648,7 +2115,7 @@ const validate_ONE: Injector = (
1648
2115
  const { mode, parent, keyI } = inj
1649
2116
 
1650
2117
  // Only operate in val mode, since parent is a list.
1651
- if (S_MVAL === mode) {
2118
+ if (M_VAL === mode) {
1652
2119
  if (!islist(parent) || 0 !== keyI) {
1653
2120
  inj.errs.push('The $ONE validator at field ' +
1654
2121
  pathify(inj.path, 1, 1) +
@@ -1656,7 +2123,7 @@ const validate_ONE: Injector = (
1656
2123
  return
1657
2124
  }
1658
2125
 
1659
- inj.keyI = inj.keys.length
2126
+ inj.keyI = size(inj.keys)
1660
2127
 
1661
2128
  // Clean up structure, replacing [$ONE, ...] with current
1662
2129
  inj.setval(inj.dparent, 2)
@@ -1665,7 +2132,7 @@ const validate_ONE: Injector = (
1665
2132
  inj.key = getelem(inj.path, -1)
1666
2133
 
1667
2134
  let tvals = slice(parent, 1)
1668
- if (0 === tvals.length) {
2135
+ if (0 === size(tvals)) {
1669
2136
  inj.errs.push('The $ONE validator at field ' +
1670
2137
  pathify(inj.path, 1, 1) +
1671
2138
  ' must have at least one argument.')
@@ -1678,7 +2145,7 @@ const validate_ONE: Injector = (
1678
2145
  // If match, then errs.length = 0
1679
2146
  let terrs: any[] = []
1680
2147
 
1681
- const vstore = { ...store }
2148
+ const vstore = merge([{}, store], 1)
1682
2149
  vstore.$TOP = inj.dparent
1683
2150
 
1684
2151
  const vcurrent = validate(inj.dparent, tval, {
@@ -1690,21 +2157,19 @@ const validate_ONE: Injector = (
1690
2157
  inj.setval(vcurrent, -2)
1691
2158
 
1692
2159
  // Accept current value if there was a match
1693
- if (0 === terrs.length) {
2160
+ if (0 === size(terrs)) {
1694
2161
  return
1695
2162
  }
1696
2163
  }
1697
2164
 
1698
2165
  // There was no match.
1699
-
1700
- const valdesc = tvals
1701
- .map((v: any) => stringify(v))
1702
- .join(', ')
1703
- .replace(R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
2166
+ const valdesc =
2167
+ replace(join(items(tvals, (n) => stringify(n[1])), ', '),
2168
+ R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
1704
2169
 
1705
2170
  inj.errs.push(_invalidTypeMsg(
1706
2171
  inj.path,
1707
- (1 < tvals.length ? 'one of ' : '') + valdesc,
2172
+ (1 < size(tvals) ? 'one of ' : '') + valdesc,
1708
2173
  typify(inj.dparent), inj.dparent, 'V0210'))
1709
2174
  }
1710
2175
  }
@@ -1714,7 +2179,7 @@ const validate_EXACT: Injector = (inj: Injection) => {
1714
2179
  const { mode, parent, key, keyI } = inj
1715
2180
 
1716
2181
  // Only operate in val mode, since parent is a list.
1717
- if (S_MVAL === mode) {
2182
+ if (M_VAL === mode) {
1718
2183
  if (!islist(parent) || 0 !== keyI) {
1719
2184
  inj.errs.push('The $EXACT validator at field ' +
1720
2185
  pathify(inj.path, 1, 1) +
@@ -1722,16 +2187,17 @@ const validate_EXACT: Injector = (inj: Injection) => {
1722
2187
  return
1723
2188
  }
1724
2189
 
1725
- inj.keyI = inj.keys.length
2190
+ inj.keyI = size(inj.keys)
1726
2191
 
1727
2192
  // Clean up structure, replacing [$EXACT, ...] with current data parent
1728
2193
  inj.setval(inj.dparent, 2)
1729
2194
 
1730
- inj.path = slice(inj.path, 0, inj.path.length - 1)
2195
+ // inj.path = slice(inj.path, 0, size(inj.path) - 1)
2196
+ inj.path = slice(inj.path, 0, -1)
1731
2197
  inj.key = getelem(inj.path, -1)
1732
2198
 
1733
2199
  let tvals = slice(parent, 1)
1734
- if (0 === tvals.length) {
2200
+ if (0 === size(tvals)) {
1735
2201
  inj.errs.push('The $EXACT validator at field ' +
1736
2202
  pathify(inj.path, 1, 1) +
1737
2203
  ' must have at least one argument.')
@@ -1754,15 +2220,15 @@ const validate_EXACT: Injector = (inj: Injection) => {
1754
2220
  }
1755
2221
  }
1756
2222
 
1757
- const valdesc = tvals
1758
- .map((v: any) => stringify(v))
1759
- .join(', ')
1760
- .replace(R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
2223
+ // There was no match.
2224
+ const valdesc =
2225
+ replace(join(items(tvals, (n) => stringify(n[1])), ', '),
2226
+ R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
1761
2227
 
1762
2228
  inj.errs.push(_invalidTypeMsg(
1763
2229
  inj.path,
1764
- (1 < inj.path.length ? '' : 'value ') +
1765
- 'exactly equal to ' + (1 === tvals.length ? '' : 'one of ') + valdesc,
2230
+ (1 < size(inj.path) ? '' : 'value ') +
2231
+ 'exactly equal to ' + (1 === size(tvals) ? '' : 'one of ') + valdesc,
1766
2232
  typify(inj.dparent), inj.dparent, 'V0110'))
1767
2233
  }
1768
2234
  else {
@@ -1780,7 +2246,7 @@ const _validation: Modify = (
1780
2246
  inj?: Injection,
1781
2247
  ) => {
1782
2248
 
1783
- if (UNDEF === inj) {
2249
+ if (NONE === inj) {
1784
2250
  return
1785
2251
  }
1786
2252
 
@@ -1794,28 +2260,28 @@ const _validation: Modify = (
1794
2260
  // Current val to verify.
1795
2261
  const cval = getprop(inj.dparent, key)
1796
2262
 
1797
- if (UNDEF === inj || (!exact && UNDEF === cval)) {
2263
+ if (NONE === inj || (!exact && NONE === cval)) {
1798
2264
  return
1799
2265
  }
1800
2266
 
1801
2267
  const ptype = typify(pval)
1802
2268
 
1803
2269
  // Delete any special commands remaining.
1804
- if (S_string === ptype && pval.includes(S_DS)) {
2270
+ if (0 < (T_string & ptype) && pval.includes(S_DS)) {
1805
2271
  return
1806
2272
  }
1807
2273
 
1808
2274
  const ctype = typify(cval)
1809
2275
 
1810
2276
  // Type mismatch.
1811
- if (ptype !== ctype && UNDEF !== pval) {
1812
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0010'))
2277
+ if (ptype !== ctype && NONE !== pval) {
2278
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0010'))
1813
2279
  return
1814
2280
  }
1815
2281
 
1816
2282
  if (ismap(cval)) {
1817
2283
  if (!ismap(pval)) {
1818
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0020'))
2284
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0020'))
1819
2285
  return
1820
2286
  }
1821
2287
 
@@ -1823,7 +2289,7 @@ const _validation: Modify = (
1823
2289
  const pkeys = keysof(pval)
1824
2290
 
1825
2291
  // Empty spec object {} means object can be open (any keys).
1826
- if (0 < pkeys.length && true !== getprop(pval, '`$OPEN`')) {
2292
+ if (0 < size(pkeys) && true !== getprop(pval, '`$OPEN`')) {
1827
2293
  const badkeys = []
1828
2294
  for (let ckey of ckeys) {
1829
2295
  if (!haskey(pval, ckey)) {
@@ -1832,9 +2298,9 @@ const _validation: Modify = (
1832
2298
  }
1833
2299
 
1834
2300
  // Closed object, so reject extra keys not in shape.
1835
- if (0 < badkeys.length) {
2301
+ if (0 < size(badkeys)) {
1836
2302
  const msg =
1837
- 'Unexpected keys at field ' + pathify(inj.path, 1) + S_VIZ + badkeys.join(', ')
2303
+ 'Unexpected keys at field ' + pathify(inj.path, 1) + S_VIZ + join(badkeys, ', ')
1838
2304
  inj.errs.push(msg)
1839
2305
  }
1840
2306
  }
@@ -1848,7 +2314,7 @@ const _validation: Modify = (
1848
2314
  }
1849
2315
  else if (islist(cval)) {
1850
2316
  if (!islist(pval)) {
1851
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0030'))
2317
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0030'))
1852
2318
  }
1853
2319
  }
1854
2320
  else if (exact) {
@@ -1888,34 +2354,42 @@ function validate(
1888
2354
  const collect = null != injdef?.errs
1889
2355
  const errs = injdef?.errs || []
1890
2356
 
1891
- const store = {
1892
- // Remove the transform commands.
1893
- $DELETE: null,
1894
- $COPY: null,
1895
- $KEY: null,
1896
- $META: null,
1897
- $MERGE: null,
1898
- $EACH: null,
1899
- $PACK: null,
1900
-
1901
- $STRING: validate_STRING,
1902
- $NUMBER: validate_TYPE,
1903
- $BOOLEAN: validate_TYPE,
1904
- $OBJECT: validate_TYPE,
1905
- $ARRAY: validate_TYPE,
1906
- $FUNCTION: validate_TYPE,
1907
- $INSTANCE: validate_TYPE,
1908
- $ANY: validate_ANY,
1909
- $CHILD: validate_CHILD,
1910
- $ONE: validate_ONE,
1911
- $EXACT: validate_EXACT,
1912
-
1913
- ...(extra || {}),
2357
+ const store = merge([
2358
+ {
2359
+ // Remove the transform commands.
2360
+ $DELETE: null,
2361
+ $COPY: null,
2362
+ $KEY: null,
2363
+ $META: null,
2364
+ $MERGE: null,
2365
+ $EACH: null,
2366
+ $PACK: null,
2367
+
2368
+ $STRING: validate_STRING,
2369
+ $NUMBER: validate_TYPE,
2370
+ $INTEGER: validate_TYPE,
2371
+ $DECIMAL: validate_TYPE,
2372
+ $BOOLEAN: validate_TYPE,
2373
+ $NULL: validate_TYPE,
2374
+ $NIL: validate_TYPE,
2375
+ $MAP: validate_TYPE,
2376
+ $LIST: validate_TYPE,
2377
+ $FUNCTION: validate_TYPE,
2378
+ $INSTANCE: validate_TYPE,
2379
+ $ANY: validate_ANY,
2380
+ $CHILD: validate_CHILD,
2381
+ $ONE: validate_ONE,
2382
+ $EXACT: validate_EXACT,
2383
+ },
2384
+
2385
+ getdef(extra, {}),
1914
2386
 
1915
2387
  // A special top level value to collect errors.
1916
- // NOTE: collecterrs paramter always wins.
1917
- $ERRS: errs,
1918
- }
2388
+ // NOTE: collecterrs parameter always wins.
2389
+ {
2390
+ $ERRS: errs,
2391
+ }
2392
+ ], 1)
1919
2393
 
1920
2394
  let meta = getprop(injdef, 'meta', {})
1921
2395
  setprop(meta, S_BEXACT, getprop(meta, S_BEXACT, false))
@@ -1924,12 +2398,13 @@ function validate(
1924
2398
  meta,
1925
2399
  extra: store,
1926
2400
  modify: _validation,
1927
- handler: _validatehandler
2401
+ handler: _validatehandler,
2402
+ errs,
1928
2403
  })
1929
2404
 
1930
- const generr = (0 < errs.length && !collect)
2405
+ const generr = (0 < size(errs) && !collect)
1931
2406
  if (generr) {
1932
- throw new Error('Invalid data: ' + errs.join(' | '))
2407
+ throw new Error(join(errs, ' | '))
1933
2408
  }
1934
2409
 
1935
2410
  return out
@@ -1937,18 +2412,16 @@ function validate(
1937
2412
 
1938
2413
 
1939
2414
  const select_AND: Injector = (inj: Injection, _val: any, _ref: string, store: any) => {
1940
- if (S_MKEYPRE === inj.mode) {
2415
+ if (M_KEYPRE === inj.mode) {
1941
2416
  const terms = getprop(inj.parent, inj.key)
1942
2417
 
1943
2418
  const ppath = slice(inj.path, -1)
1944
2419
  const point = getpath(store, ppath)
1945
2420
 
1946
- const vstore = { ...store }
2421
+ const vstore = merge([{}, store], 1)
1947
2422
  vstore.$TOP = point
1948
2423
 
1949
2424
  for (let term of terms) {
1950
- // setprop(term, '`$OPEN`', getprop(term, '`$OPEN`', true))
1951
-
1952
2425
  let terrs: any[] = []
1953
2426
 
1954
2427
  validate(point, term, {
@@ -1957,7 +2430,7 @@ const select_AND: Injector = (inj: Injection, _val: any, _ref: string, store: an
1957
2430
  meta: inj.meta,
1958
2431
  })
1959
2432
 
1960
- if (0 != terrs.length) {
2433
+ if (0 != size(terrs)) {
1961
2434
  inj.errs.push(
1962
2435
  'AND:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(terms))
1963
2436
  }
@@ -1971,13 +2444,13 @@ const select_AND: Injector = (inj: Injection, _val: any, _ref: string, store: an
1971
2444
 
1972
2445
 
1973
2446
  const select_OR: Injector = (inj: Injection, _val: any, _ref: string, store: any) => {
1974
- if (S_MKEYPRE === inj.mode) {
2447
+ if (M_KEYPRE === inj.mode) {
1975
2448
  const terms = getprop(inj.parent, inj.key)
1976
2449
 
1977
2450
  const ppath = slice(inj.path, -1)
1978
2451
  const point = getpath(store, ppath)
1979
2452
 
1980
- const vstore = { ...store }
2453
+ const vstore = merge([{}, store], 1)
1981
2454
  vstore.$TOP = point
1982
2455
 
1983
2456
  for (let term of terms) {
@@ -1989,7 +2462,7 @@ const select_OR: Injector = (inj: Injection, _val: any, _ref: string, store: any
1989
2462
  meta: inj.meta,
1990
2463
  })
1991
2464
 
1992
- if (0 === terrs.length) {
2465
+ if (0 === size(terrs)) {
1993
2466
  const gkey = getelem(inj.path, -2)
1994
2467
  const gp = getelem(inj.nodes, -2)
1995
2468
  setprop(gp, gkey, point)
@@ -2005,13 +2478,13 @@ const select_OR: Injector = (inj: Injection, _val: any, _ref: string, store: any
2005
2478
 
2006
2479
 
2007
2480
  const select_NOT: Injector = (inj: Injection, _val: any, _ref: string, store: any) => {
2008
- if (S_MKEYPRE === inj.mode) {
2481
+ if (M_KEYPRE === inj.mode) {
2009
2482
  const term = getprop(inj.parent, inj.key)
2010
2483
 
2011
2484
  const ppath = slice(inj.path, -1)
2012
2485
  const point = getpath(store, ppath)
2013
2486
 
2014
- const vstore = { ...store }
2487
+ const vstore = merge([{}, store], 1)
2015
2488
  vstore.$TOP = point
2016
2489
 
2017
2490
  let terrs: any[] = []
@@ -2022,7 +2495,7 @@ const select_NOT: Injector = (inj: Injection, _val: any, _ref: string, store: an
2022
2495
  meta: inj.meta,
2023
2496
  })
2024
2497
 
2025
- if (0 == terrs.length) {
2498
+ if (0 == size(terrs)) {
2026
2499
  inj.errs.push(
2027
2500
  'NOT:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(term))
2028
2501
  }
@@ -2035,7 +2508,7 @@ const select_NOT: Injector = (inj: Injection, _val: any, _ref: string, store: an
2035
2508
 
2036
2509
 
2037
2510
  const select_CMP: Injector = (inj: Injection, _val: any, ref: string, store: any) => {
2038
- if (S_MKEYPRE === inj.mode) {
2511
+ if (M_KEYPRE === inj.mode) {
2039
2512
  const term = getprop(inj.parent, inj.key)
2040
2513
  // const src = getprop(store, inj.base, store)
2041
2514
  const gkey = getelem(inj.path, -2)
@@ -2074,7 +2547,7 @@ const select_CMP: Injector = (inj: Injection, _val: any, ref: string, store: any
2074
2547
  }
2075
2548
  }
2076
2549
 
2077
- return UNDEF
2550
+ return NONE
2078
2551
  }
2079
2552
 
2080
2553
 
@@ -2088,10 +2561,13 @@ function select(children: any, query: any): any[] {
2088
2561
  }
2089
2562
 
2090
2563
  if (ismap(children)) {
2091
- children = items(children).map(n => (n[1][S_DKEY] = n[0], n[1]))
2564
+ children = items(children, n => {
2565
+ setprop(n[1], S_DKEY, n[0])
2566
+ return n[1]
2567
+ })
2092
2568
  }
2093
2569
  else {
2094
- children = (children as any[]).map((n, i) => ((ismap(n) ? n[S_DKEY] = i : null), n))
2570
+ children = items(children, (n) => (setprop(n[1], S_DKEY, +n[0]), n[1]))
2095
2571
  }
2096
2572
 
2097
2573
  const results: any[] = []
@@ -2133,10 +2609,9 @@ function select(children: any, query: any): any[] {
2133
2609
  }
2134
2610
 
2135
2611
 
2136
-
2137
2612
  // Injection state used for recursive injection into JSON - like data structures.
2138
2613
  class Injection {
2139
- mode: InjectMode // Injection mode: key:pre, val, key:post.
2614
+ mode: InjectMode // Injection mode: M_KEYPRE, M_VAL, M_KEYPOST.
2140
2615
  full: boolean // Transform escape was full key name.
2141
2616
  keyI: number // Index of parent key in list of parent keys.
2142
2617
  keys: string[] // List of parent keys.
@@ -2160,10 +2635,10 @@ class Injection {
2160
2635
  this.parent = parent
2161
2636
  this.errs = []
2162
2637
 
2163
- this.dparent = UNDEF
2638
+ this.dparent = NONE
2164
2639
  this.dpath = [S_DTOP]
2165
2640
 
2166
- this.mode = S_MVAL as InjectMode
2641
+ this.mode = M_VAL
2167
2642
  this.full = false
2168
2643
  this.keyI = 0
2169
2644
  this.keys = [S_DTOP]
@@ -2179,7 +2654,7 @@ class Injection {
2179
2654
  toString(prefix?: string) {
2180
2655
  return 'INJ' + (null == prefix ? '' : S_FS + prefix) + S_CN +
2181
2656
  pad(pathify(this.path, 1)) +
2182
- this.mode + (this.full ? '/full' : '') + S_CN +
2657
+ MODENAME[this.mode] + (this.full ? '/full' : '') + S_CN +
2183
2658
  'key=' + this.keyI + S_FS + this.key + S_FS + S_OS + this.keys + S_CS +
2184
2659
  ' p=' + stringify(this.parent, -1, 1) +
2185
2660
  ' m=' + stringify(this.meta, -1, 1) +
@@ -2193,12 +2668,12 @@ class Injection {
2193
2668
  const parentkey = getelem(this.path, -2)
2194
2669
 
2195
2670
  // Resolve current node in store for local paths.
2196
- if (UNDEF === this.dparent) {
2671
+ if (NONE === this.dparent) {
2197
2672
 
2198
2673
  // Even if there's no data, dpath should continue to match path, so that
2199
2674
  // relative paths work properly.
2200
- if (1 < this.dpath.length) {
2201
- this.dpath = [...this.dpath, parentkey]
2675
+ if (1 < size(this.dpath)) {
2676
+ this.dpath = flatten([this.dpath, parentkey])
2202
2677
  }
2203
2678
  }
2204
2679
  else {
@@ -2211,7 +2686,7 @@ class Injection {
2211
2686
  this.dpath = slice(this.dpath, -1)
2212
2687
  }
2213
2688
  else {
2214
- this.dpath = [...this.dpath, parentkey]
2689
+ this.dpath = flatten([this.dpath, parentkey])
2215
2690
  }
2216
2691
  }
2217
2692
  }
@@ -2230,8 +2705,8 @@ class Injection {
2230
2705
  cinj.keys = keys
2231
2706
  cinj.key = key
2232
2707
 
2233
- cinj.path = [...(this.path || []), key]
2234
- cinj.nodes = [...(this.nodes || []), val]
2708
+ cinj.path = flatten([getdef(this.path, []), key])
2709
+ cinj.nodes = flatten([getdef(this.nodes, []), [val]])
2235
2710
 
2236
2711
  cinj.mode = this.mode
2237
2712
  cinj.handler = this.handler
@@ -2241,7 +2716,7 @@ class Injection {
2241
2716
  cinj.errs = this.errs
2242
2717
  cinj.prior = this
2243
2718
 
2244
- cinj.dpath = [...this.dpath]
2719
+ cinj.dpath = flatten([this.dpath])
2245
2720
  cinj.dparent = this.dparent
2246
2721
 
2247
2722
  return cinj
@@ -2249,18 +2724,22 @@ class Injection {
2249
2724
 
2250
2725
 
2251
2726
  setval(val: any, ancestor?: number) {
2727
+ let parent = NONE
2252
2728
  if (null == ancestor || ancestor < 2) {
2253
- return UNDEF === val ?
2254
- delprop(this.parent, this.key) :
2729
+ parent = NONE === val ?
2730
+ this.parent = delprop(this.parent, this.key) :
2255
2731
  setprop(this.parent, this.key, val)
2256
2732
  }
2257
2733
  else {
2258
2734
  const aval = getelem(this.nodes, 0 - ancestor)
2259
2735
  const akey = getelem(this.path, 0 - ancestor)
2260
- return UNDEF === val ?
2736
+ parent = NONE === val ?
2261
2737
  delprop(aval, akey) :
2262
2738
  setprop(aval, akey, val)
2263
2739
  }
2740
+
2741
+ // console.log('SETVAL', val, this.key, this.parent)
2742
+ return parent
2264
2743
  }
2265
2744
  }
2266
2745
 
@@ -2269,21 +2748,21 @@ class Injection {
2269
2748
  // ==================
2270
2749
 
2271
2750
 
2272
- // Update all references to target in inj.nodes.
2273
- function _updateAncestors(_inj: Injection, target: any, tkey: any, tval: any) {
2274
- // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
2275
- setprop(target, tkey, tval)
2276
- }
2751
+ // // Update all references to target in inj.nodes.
2752
+ // function _updateAncestors(_inj: Injection, target: any, tkey: any, tval: any) {
2753
+ // // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
2754
+ // setprop(target, tkey, tval)
2755
+ // }
2277
2756
 
2278
2757
 
2279
2758
  // Build a type validation error message.
2280
- function _invalidTypeMsg(path: any, needtype: string, vt: string, v: any, _whence?: string) {
2759
+ function _invalidTypeMsg(path: any, needtype: string, vt: number, v: any, _whence?: string) {
2281
2760
  let vs = null == v ? 'no value' : stringify(v)
2282
2761
 
2283
2762
  return 'Expected ' +
2284
- (1 < path.length ? ('field ' + pathify(path, 1) + ' to be ') : '') +
2763
+ (1 < size(path) ? ('field ' + pathify(path, 1) + ' to be ') : '') +
2285
2764
  needtype + ', but found ' +
2286
- (null != v ? vt + S_VIZ : '') + vs +
2765
+ (null != v ? typename(vt) + S_VIZ : '') + vs +
2287
2766
 
2288
2767
  // Uncomment to help debug validation errors.
2289
2768
  // ' [' + _whence + ']' +
@@ -2301,7 +2780,7 @@ const _injecthandler: Injector = (
2301
2780
  store: any
2302
2781
  ): any => {
2303
2782
  let out = val
2304
- const iscmd = isfunc(val) && (UNDEF === ref || ref.startsWith(S_DS))
2783
+ const iscmd = isfunc(val) && (NONE === ref || ref.startsWith(S_DS))
2305
2784
 
2306
2785
  // Only call val function if it is a special command ($NAME format).
2307
2786
  // TODO: OR if meta.'$CALL'
@@ -2311,7 +2790,7 @@ const _injecthandler: Injector = (
2311
2790
  }
2312
2791
 
2313
2792
  // Update parent with value. Ensures references remain in node tree.
2314
- else if (S_MVAL === inj.mode && inj.full) {
2793
+ else if (M_VAL === inj.mode && inj.full) {
2315
2794
  inj.setval(val)
2316
2795
  }
2317
2796
 
@@ -2381,9 +2860,9 @@ function _injectstr(
2381
2860
  let pathref = m[1]
2382
2861
 
2383
2862
  // Special escapes inside injection.
2384
- pathref = 3 < pathref.length ?
2385
- pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) :
2386
- pathref
2863
+ if (3 < size(pathref)) {
2864
+ pathref = pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS)
2865
+ }
2387
2866
 
2388
2867
  // Get the extracted path reference.
2389
2868
  out = getpath(store, pathref, inj)
@@ -2393,14 +2872,19 @@ function _injectstr(
2393
2872
  // Check for injections within the string.
2394
2873
  const partial = (_m: string, ref: string) => {
2395
2874
  // Special escapes inside injection.
2396
- ref = 3 < ref.length ? ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) : ref
2875
+
2876
+ if (3 < size(ref)) {
2877
+ ref = ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS)
2878
+ }
2879
+
2397
2880
  if (inj) {
2398
2881
  inj.full = false
2399
2882
  }
2883
+
2400
2884
  const found = getpath(store, ref, inj)
2401
2885
 
2402
2886
  // Ensure inject value is a string.
2403
- return UNDEF === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found)
2887
+ return NONE === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found)
2404
2888
  }
2405
2889
 
2406
2890
  out = val.replace(R_INJECTION_PARTIAL, partial)
@@ -2417,11 +2901,101 @@ function _injectstr(
2417
2901
  }
2418
2902
 
2419
2903
 
2904
+ // Handler Utilities
2905
+ // =================
2906
+
2907
+
2908
+ const MODENAME: any = {
2909
+ [M_VAL]: 'val',
2910
+ [M_KEYPRE]: 'key:pre',
2911
+ [M_KEYPOST]: 'key:post',
2912
+ }
2913
+
2914
+ const PLACEMENT: any = {
2915
+ [M_VAL]: 'value',
2916
+ [M_KEYPRE]: S_key,
2917
+ [M_KEYPOST]: S_key,
2918
+ }
2919
+
2920
+ function checkPlacement(
2921
+ modes: InjectMode,
2922
+ ijname: string,
2923
+ parentTypes: number,
2924
+ inj: Injection
2925
+ ): boolean {
2926
+ if (0 === (modes & inj.mode)) {
2927
+ inj.errs.push('$' + ijname + ': invalid placement as ' + PLACEMENT[inj.mode] +
2928
+ ', expected: ' + join(items(
2929
+ [M_KEYPRE, M_KEYPOST, M_VAL].filter(m => modes & m),
2930
+ (n: any) => PLACEMENT[n[1]]), ',') + '.')
2931
+ return false
2932
+ }
2933
+ if (!isempty(parentTypes)) {
2934
+ const ptype = typify(inj.parent)
2935
+ if (0 === (parentTypes & ptype)) {
2936
+ inj.errs.push('$' + ijname + ': invalid placement in parent ' + typename(ptype) +
2937
+ ', expected: ' + typename(parentTypes) + '.')
2938
+ return false
2939
+
2940
+ }
2941
+ }
2942
+ return true
2943
+ }
2944
+
2945
+
2946
+ // function injectorArgs(argTypes: number[], inj: Injection): any {
2947
+ function injectorArgs(argTypes: number[], args: any[]): any {
2948
+ const numargs = size(argTypes)
2949
+ const found = new Array(1 + numargs)
2950
+ found[0] = NONE
2951
+ for (let argI = 0; argI < numargs; argI++) {
2952
+ // const arg = inj.parent[1 + argI]
2953
+ const arg = args[argI]
2954
+ const argType = typify(arg)
2955
+ if (0 === (argTypes[argI] & argType)) {
2956
+ found[0] = 'invalid argument: ' + stringify(arg, 22) +
2957
+ ' (' + typename(argType) + ' at position ' + (1 + argI) +
2958
+ ') is not of type: ' + typename(argTypes[argI]) + '.'
2959
+ break
2960
+ }
2961
+ found[1 + argI] = arg
2962
+ }
2963
+ return found
2964
+ }
2965
+
2966
+
2967
+ function injectChild(child: any, store: any, inj: Injection): Injection {
2968
+ let cinj = inj
2969
+
2970
+ // Replace ['`$FORMAT`',...] with child
2971
+ if (null != inj.prior) {
2972
+ if (null != inj.prior.prior) {
2973
+ cinj = inj.prior.prior.child(inj.prior.keyI, inj.prior.keys)
2974
+ cinj.val = child
2975
+ setprop(cinj.parent, inj.prior.key, child)
2976
+ }
2977
+ else {
2978
+ cinj = inj.prior.child(inj.keyI, inj.keys)
2979
+ cinj.val = child
2980
+ setprop(cinj.parent, inj.key, child)
2981
+ }
2982
+ }
2983
+
2984
+ // console.log('FORMAT-INJECT-CHILD', child)
2985
+ inject(child, store, cinj)
2986
+
2987
+ return cinj
2988
+ }
2989
+
2990
+
2420
2991
  class StructUtility {
2421
2992
  clone = clone
2422
2993
  delprop = delprop
2423
2994
  escre = escre
2424
2995
  escurl = escurl
2996
+ filter = filter
2997
+ flatten = flatten
2998
+ getdef = getdef
2425
2999
  getelem = getelem
2426
3000
  getpath = getpath
2427
3001
  getprop = getprop
@@ -2434,13 +3008,14 @@ class StructUtility {
2434
3008
  ismap = ismap
2435
3009
  isnode = isnode
2436
3010
  items = items
2437
- joinurl = joinurl
3011
+ join = join
2438
3012
  jsonify = jsonify
2439
3013
  keysof = keysof
2440
3014
  merge = merge
2441
3015
  pad = pad
2442
3016
  pathify = pathify
2443
3017
  select = select
3018
+ setpath = setpath
2444
3019
  setprop = setprop
2445
3020
  size = size
2446
3021
  slice = slice
@@ -2448,11 +3023,36 @@ class StructUtility {
2448
3023
  stringify = stringify
2449
3024
  transform = transform
2450
3025
  typify = typify
3026
+ typename = typename
2451
3027
  validate = validate
2452
3028
  walk = walk
2453
3029
 
2454
- jo = jo
2455
- ja = ja
3030
+ SKIP = SKIP
3031
+ DELETE = DELETE
3032
+
3033
+ jm = jm
3034
+ jt = jt
3035
+ tn = typename
3036
+
3037
+ T_any = T_any
3038
+ T_noval = T_noval
3039
+ T_boolean = T_boolean
3040
+ T_decimal = T_decimal
3041
+ T_integer = T_integer
3042
+ T_number = T_number
3043
+ T_string = T_string
3044
+ T_function = T_function
3045
+ T_symbol = T_symbol
3046
+ T_null = T_null
3047
+ T_list = T_list
3048
+ T_map = T_map
3049
+ T_instance = T_instance
3050
+ T_scalar = T_scalar
3051
+ T_node = T_node
3052
+
3053
+ checkPlacement = checkPlacement
3054
+ injectorArgs = injectorArgs
3055
+ injectChild = injectChild
2456
3056
  }
2457
3057
 
2458
3058
  export {
@@ -2461,6 +3061,9 @@ export {
2461
3061
  delprop,
2462
3062
  escre,
2463
3063
  escurl,
3064
+ filter,
3065
+ flatten,
3066
+ getdef,
2464
3067
  getelem,
2465
3068
  getpath,
2466
3069
  getprop,
@@ -2473,13 +3076,14 @@ export {
2473
3076
  ismap,
2474
3077
  isnode,
2475
3078
  items,
2476
- joinurl,
3079
+ join,
2477
3080
  jsonify,
2478
3081
  keysof,
2479
3082
  merge,
2480
3083
  pad,
2481
3084
  pathify,
2482
3085
  select,
3086
+ setpath,
2483
3087
  setprop,
2484
3088
  size,
2485
3089
  slice,
@@ -2487,11 +3091,41 @@ export {
2487
3091
  stringify,
2488
3092
  transform,
2489
3093
  typify,
3094
+ typename,
2490
3095
  validate,
2491
3096
  walk,
2492
3097
 
2493
- jo,
2494
- ja,
3098
+ SKIP,
3099
+ DELETE,
3100
+
3101
+ jm,
3102
+ jt,
3103
+
3104
+ T_any,
3105
+ T_noval,
3106
+ T_boolean,
3107
+ T_decimal,
3108
+ T_integer,
3109
+ T_number,
3110
+ T_string,
3111
+ T_function,
3112
+ T_symbol,
3113
+ T_null,
3114
+ T_list,
3115
+ T_map,
3116
+ T_instance,
3117
+ T_scalar,
3118
+ T_node,
3119
+
3120
+ M_KEYPRE,
3121
+ M_KEYPOST,
3122
+ M_VAL,
3123
+
3124
+ MODENAME,
3125
+
3126
+ checkPlacement,
3127
+ injectorArgs,
3128
+ injectChild,
2495
3129
  }
2496
3130
 
2497
3131
  export type {