-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstruct.js
More file actions
2533 lines (2522 loc) · 73.7 KB
/
struct.js
File metadata and controls
2533 lines (2522 loc) · 73.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2025-2026 Voxgig Ltd. MIT LICENSE. */
// VERSION: @voxgig/struct 0.0.10
/* Voxgig Struct
* =============
*
* Utility functions to manipulate in-memory JSON-like data
* structures. These structures assumed to be composed of nested
* "nodes", where a node is a list or map, and has named or indexed
* fields. The general design principle is "by-example". Transform
* specifications mirror the desired output. This implementation is
* designed for porting to multiple language, and to be tolerant of
* undefined values.
*
* Main utilities
* - getpath: get the value at a key path deep inside an object.
* - merge: merge multiple nodes, overriding values in earlier nodes.
* - walk: walk a node tree, applying a function at each node and leaf.
* - inject: inject values from a data store into a new data structure.
* - transform: transform a data structure to an example structure.
* - validate: valiate a data structure against a shape specification.
*
* Minor utilities
* - isnode, islist, ismap, iskey, isfunc: identify value kinds.
* - isempty: undefined values, or empty nodes.
* - keysof: sorted list of node keys (ascending).
* - haskey: true if key value is defined.
* - clone: create a copy of a JSON-like data structure.
* - items: list entries of a map or list as [key, value] pairs.
* - getprop: safely get a property value by key.
* - setprop: safely set a property value by key.
* - stringify: human-friendly string version of a value.
* - escre: escape a regular expresion string.
* - escurl: escape a url.
* - join: join parts of a url, merging forward slashes.
*
* This set of functions and supporting utilities is designed to work
* uniformly across many languages, meaning that some code that may be
* functionally redundant in specific languages is still retained to
* keep the code human comparable.
*
* NOTE: Lists are assumed to be mutable and reference stable.
*
* NOTE: In this code JSON nulls are in general *not* considered the
* same as the undefined value in the given language. However most
* JSON parsers do use the undefined value to represent JSON
* null. This is ambiguous as JSON null is a separate value, not an
* undefined value. You should convert such values to a special value
* to represent JSON null, if this ambiguity creates issues
* (thankfully in most APIs, JSON nulls are not used). For example,
* the unit tests use the string "__NULL__" where necessary.
*
*/
// String constants are explicitly defined.
// Mode value for inject step (bitfield).
const M_KEYPRE = 1
const M_KEYPOST = 2
const M_VAL = 4
// Special strings.
const S_BKEY = '`$KEY`'
const S_BANNO = '`$ANNO`'
const S_BEXACT = '`$EXACT`'
const S_BVAL = '`$VAL`'
const S_DKEY = '$KEY'
const S_DTOP = '$TOP'
const S_DERRS = '$ERRS'
const S_DSPEC = '$SPEC'
// General strings.
const S_list = 'list'
const S_base = 'base'
const S_boolean = 'boolean'
const S_function = 'function'
const S_symbol = 'symbol'
const S_instance = 'instance'
const S_key = 'key'
const S_any = 'any'
const S_nil = 'nil'
const S_null = 'null'
const S_number = 'number'
const S_object = 'object'
const S_string = 'string'
const S_decimal = 'decimal'
const S_integer = 'integer'
const S_map = 'map'
const S_scalar = 'scalar'
const S_node = 'node'
// Character strings.
const S_BT = '`'
const S_CN = ':'
const S_CS = ']'
const S_DS = '$'
const S_DT = '.'
const S_FS = '/'
const S_KEY = 'KEY'
const S_MT = ''
const S_OS = '['
const S_SP = ' '
const S_CM = ','
const S_VIZ = ': '
// Types
let t = 31
const T_any = (1 << t--) - 1
const T_noval = 1 << t-- // Means property absent, undefined. Also NOT a scalar!
const T_boolean = 1 << t--
const T_decimal = 1 << t--
const T_integer = 1 << t--
const T_number = 1 << t--
const T_string = 1 << t--
const T_function = 1 << t--
const T_symbol = 1 << t--
const T_null = 1 << t-- // The actual JSON null value.
t -= 7
const T_list = 1 << t--
const T_map = 1 << t--
const T_instance = 1 << t--
t -= 4
const T_scalar = 1 << t--
const T_node = 1 << t--
const TYPENAME = [
S_any,
S_nil,
S_boolean,
S_decimal,
S_integer,
S_number,
S_string,
S_function,
S_symbol,
S_null,
'',
'',
'',
'',
'',
'',
'',
S_list,
S_map,
S_instance,
'',
'',
'',
'',
S_scalar,
S_node,
]
// The standard undefined value for this language.
const NONE = undefined
// Private markers
const SKIP = { '`$SKIP`': true }
const DELETE = { '`$DELETE`': true }
// Regular expression constants
const R_INTEGER_KEY = /^[-0-9]+$/ // Match integer keys (including <0).
const R_ESCAPE_REGEXP = /[.*+?^${}()|[\]\\]/g // Chars that need escaping in regexp.
const R_QUOTES = /"/g // Double quotes for removal.
const R_DOT = /\./g // Dots in path strings.
const R_CLONE_REF = /^`\$REF:([0-9]+)`$/ // Copy reference in cloning.
const R_META_PATH = /^([^$]+)\$([=~])(.+)$/ // Meta path syntax.
const R_DOUBLE_DOLLAR = /\$\$/g // Double dollar escape sequence.
const R_TRANSFORM_NAME = /`\$([A-Z]+)`/g // Transform command names.
const R_INJECTION_FULL = /^`(\$[A-Z]+|[^`]*)[0-9]*`$/ // Full string injection pattern.
const R_BT_ESCAPE = /\$BT/g // Backtick escape sequence.
const R_DS_ESCAPE = /\$DS/g // Dollar sign escape sequence.
const R_INJECTION_PARTIAL = /`([^`]+)`/g // Partial string injection pattern.
// Default max depth (for walk etc).
const MAXDEPTH = 32
// Return type string for narrowest type.
function typename(t) {
return getelem(TYPENAME, Math.clz32(t), TYPENAME[0])
}
// Get a defined value. Returns alt if val is undefined.
function getdef(val, alt) {
if (NONE === val) {
return alt
}
return val
}
// Value is a node - defined, and a map (hash) or list (array).
// NOTE: typescript
// things
function isnode(val) {
return null != val && S_object == typeof val
}
// Value is a defined map (hash) with string keys.
function ismap(val) {
return null != val && S_object == typeof val && !Array.isArray(val)
}
// Value is a defined list (array) with integer keys (indexes).
function islist(val) {
return Array.isArray(val)
}
// Value is a defined string (non-empty) or integer key.
function iskey(key) {
const keytype = typeof key
return (S_string === keytype && S_MT !== key) || S_number === keytype
}
// Check for an "empty" value - undefined, empty string, array, object.
function isempty(val) {
return (
null == val ||
S_MT === val ||
(Array.isArray(val) && 0 === val.length) ||
(S_object === typeof val && 0 === Object.keys(val).length)
)
}
// Value is a function.
function isfunc(val) {
return S_function === typeof val
}
// The integer size of the value. For arrays and strings, the length,
// for numbers, the integer part, for boolean, true is 1 and falso 0, for all other values, 0.
function size(val) {
if (islist(val)) {
return val.length
} else if (ismap(val)) {
return Object.keys(val).length
}
const valtype = typeof val
if (S_string == valtype) {
return val.length
} else if (S_number == typeof val) {
return Math.floor(val)
} else if (S_boolean == typeof val) {
return true === val ? 1 : 0
} else {
return 0
}
}
// Extract part of an array or string into a new value, from the start
// point to the end point. If no end is specified, extract to the
// full length of the value. Negative arguments count from the end of
// the value. For numbers, perform min and max bounding, where start
// is inclusive, and end is *exclusive*.
// NOTE: input lists are not mutated by default. Use the mutate
// argument to mutate lists in place.
function slice(val, start, end, mutate) {
if (S_number === typeof val) {
start = null == start || S_number !== typeof start ? Number.MIN_SAFE_INTEGER : start
end = (null == end || S_number !== typeof end ? Number.MAX_SAFE_INTEGER : end) - 1
return Math.min(Math.max(val, start), end)
}
const vlen = size(val)
if (null != end && null == start) {
start = 0
}
if (null != start) {
if (start < 0) {
end = vlen + start
if (end < 0) {
end = 0
}
start = 0
} else if (null != end) {
if (end < 0) {
end = vlen + end
if (end < 0) {
end = 0
}
} else if (vlen < end) {
end = vlen
}
} else {
end = vlen
}
if (vlen < start) {
start = vlen
}
if (-1 < start && start <= end && end <= vlen) {
if (islist(val)) {
if (mutate) {
for (let i = 0, j = start; j < end; i++, j++) {
val[i] = val[j]
}
val.length = end - start
} else {
val = val.slice(start, end)
}
} else if (S_string === typeof val) {
val = val.substring(start, end)
}
} else {
if (islist(val)) {
val = []
} else if (S_string === typeof val) {
val = S_MT
}
}
}
return val
}
// String padding.
function pad(str, padding, padchar) {
str = S_string === typeof str ? str : stringify(str)
padding = null == padding ? 44 : padding
padchar = null == padchar ? S_SP : (padchar + S_SP)[0]
return -1 < padding ? str.padEnd(padding, padchar) : str.padStart(0 - padding, padchar)
}
// Determine the type of a value as a bit code.
function typify(value) {
if (undefined === value) {
return T_noval
}
const typestr = typeof value
if (null === value) {
return T_scalar | T_null
} else if (S_number === typestr) {
if (Number.isInteger(value)) {
return T_scalar | T_number | T_integer
} else if (isNaN(value)) {
return T_noval
} else {
return T_scalar | T_number | T_decimal
}
} else if (S_string === typestr) {
return T_scalar | T_string
} else if (S_boolean === typestr) {
return T_scalar | T_boolean
} else if (S_function === typestr) {
return T_scalar | T_function
}
// For languages that have symbolic atoms.
else if (S_symbol === typestr) {
return T_scalar | T_symbol
} else if (Array.isArray(value)) {
return T_node | T_list
} else if (S_object === typestr) {
if (value.constructor instanceof Function) {
let cname = value.constructor.name
if ('Object' !== cname && 'Array' !== cname) {
return T_node | T_instance
}
}
return T_node | T_map
}
// Anything else (e.g. bigint) is considered T_any
return T_any
}
// Get a list element. The key should be an integer, or a string
// that can parse to an integer only. Negative integers count from the end of the list.
function getelem(val, key, alt) {
let out = NONE
if (NONE === val || NONE === key) {
return alt
}
if (islist(val)) {
let nkey = parseInt(key)
if (Number.isInteger(nkey) && ('' + key).match(R_INTEGER_KEY)) {
if (nkey < 0) {
key = val.length + nkey
}
out = val[key]
}
}
// Group A: a stored JSON null is treated as "no value".
if (null == out) {
return 0 < (T_function & typify(alt)) ? alt() : alt
}
return out
}
// Safely get a property of a node. Group A semantics (UNDEF_SPEC.md):
// a stored null is treated as "no value" and returns alt.
function getprop(val, key, alt) {
let out = alt
if (NONE === val || NONE === key) {
return alt
}
if (isnode(val)) {
out = val[key]
}
if (null == out) {
return alt
}
return out
}
// Internal raw read: returns the literally-stored value (including null),
// or NONE when absent. Group B callers use this to distinguish null from
// absent. Group A's getprop conflates them.
function _lookup(val, key) {
if (NONE === val || NONE === key) return NONE
if (isnode(val)) return val[key]
return NONE
}
// Convert different types of keys to string representation.
// String keys are returned as is.
// Number keys are converted to strings.
// Floats are truncated to integers.
// Booleans, objects, arrays, null, undefined all return empty string.
function strkey(key = NONE) {
if (NONE === key) {
return S_MT
}
const t = typify(key)
if (0 < (T_string & t)) {
return key
} else if (0 < (T_boolean & t)) {
return S_MT
} else if (0 < (T_number & t)) {
return key % 1 === 0 ? String(key) : String(Math.floor(key))
}
return S_MT
}
// Sorted keys of a map, or indexes (as strings) of a list.
// Root utility - only uses language facilities.
function keysof(val) {
return !isnode(val) ? [] : ismap(val) ? Object.keys(val).sort() : val.map((_n, i) => S_MT + i)
}
// Value of property with name key in node val is defined.
// Root utility - only uses language facilities.
function haskey(val, key) {
return null != getprop(val, key)
}
function items(val, apply) {
let out = keysof(val).map((k) => [k, val[k]])
if (null != apply) {
out = out.map(apply)
}
return out
}
// To replicate the array spread operator:
// a=1, b=[2,3], c=[4,5]
// [a,...b,c] -> [1,2,3,[4,5]]
// flatten([a,b,[c]]) -> [1,2,3,[4,5]]
// NOTE: [c] ensures c is not expanded
function flatten(list, depth) {
if (!islist(list)) {
return list
}
return list.flat(getdef(depth, 1))
}
// Filter item values using check function.
function filter(val, check) {
let all = items(val)
let numall = size(all)
let out = []
for (let i = 0; i < numall; i++) {
if (check(all[i])) {
out.push(all[i][1])
}
}
return out
}
// Escape regular expression.
function escre(s) {
return re_replace(R_ESCAPE_REGEXP, s, '\\$&')
}
// Regex utility — uniform re_* API. See /REGEX_API.md.
// The JS port wraps the built-in RegExp; the dialect is the RE2 subset.
function re_compile(pattern, flags) {
if (pattern instanceof RegExp) return pattern
return new RegExp(pattern, flags)
}
function re_find(pattern, input) {
const re = pattern instanceof RegExp ? pattern : new RegExp(pattern)
return input.match(re)
}
function re_find_all(pattern, input) {
let re
if (pattern instanceof RegExp) {
re = pattern.global ? pattern : new RegExp(pattern.source, pattern.flags + 'g')
} else {
re = new RegExp(pattern, 'g')
}
const out = []
let m
while ((m = re.exec(input)) !== null) {
out.push(m)
if (m[0] === '') re.lastIndex++
}
return out
}
function re_replace(pattern, input, replacement) {
let re
if (pattern instanceof RegExp) {
re = pattern.global ? pattern : new RegExp(pattern.source, pattern.flags + 'g')
} else {
re = new RegExp(pattern, 'g')
}
if (typeof replacement === 'function') {
return input.replace(re, (...args) => replacement(args.slice(0, -2)))
}
return input.replace(re, replacement)
}
function re_test(pattern, input) {
const re = pattern instanceof RegExp ? pattern : new RegExp(pattern)
return re.test(input)
}
function re_escape(s) {
return escre(s)
}
// Escape URLs.
function escurl(s) {
s = null == s ? S_MT : s
return encodeURIComponent(s)
}
// Replace a search string (all), or a regexp, in a source string.
function replace(s, from, to) {
let rs = s
let ts = typify(s)
if (0 === (T_string & ts)) {
rs = stringify(s)
} else if (0 < ((T_noval | T_null) & ts)) {
rs = S_MT
} else {
rs = stringify(s)
}
return rs.replace(from, to)
}
// Concatenate url part strings, merging sep char as needed.
function join(arr, sep, url) {
const sarr = size(arr)
const sepdef = getdef(sep, S_CM)
const sepre = 1 === size(sepdef) ? escre(sepdef) : NONE
const out = filter(
items(
// filter(arr, (n) => null != n[1] && S_MT !== n[1]),
filter(arr, (n) => 0 < (T_string & typify(n[1])) && S_MT !== n[1]),
(n) => {
let i = +n[0]
let s = n[1]
if (NONE !== sepre && S_MT !== sepre) {
if (url && 0 === i) {
s = replace(s, RegExp(sepre + '+$'), S_MT)
return s
}
if (0 < i) {
s = replace(s, RegExp('^' + sepre + '+'), S_MT)
}
if (i < sarr - 1 || !url) {
s = replace(s, RegExp(sepre + '+$'), S_MT)
}
s = replace(
s,
RegExp('([^' + sepre + '])' + sepre + '+([^' + sepre + '])'),
'$1' + sepdef + '$2',
)
}
return s
},
),
(n) => S_MT !== n[1],
).join(sepdef)
return out
}
// Output JSON in a "standard" format, with 2 space indents, each property on a new line,
// and spaces after {[: and before ]}. Any "wierd" values (NaN, etc) are output as null.
// In general, the behaivor of of JavaScript's JSON.stringify(val,null,2) is followed.
function jsonify(val, flags) {
let str = S_null
if (null != val) {
try {
const indent = getprop(flags, 'indent', 2)
str = JSON.stringify(val, null, indent)
if (NONE === str) {
str = S_null
}
const offset = getprop(flags, 'offset', 0)
if (0 < offset) {
// Left offset entire indented JSON so that it aligns with surrounding code
// indented by offset. Assume first brace is on line with asignment, so not offset.
str =
'{\n' +
join(
items(slice(str.split('\n'), 1), (n) => pad(n[1], 0 - offset - size(n[1]))),
'\n',
)
}
} catch {
str = '__JSONIFY_FAILED__'
}
}
return str
}
// Safely stringify a value for humans (NOT JSON!).
function stringify(val, maxlen, pretty) {
let valstr = S_MT
pretty = !!pretty
if (NONE === val) {
return pretty ? '<>' : valstr
}
if (S_string === typeof val) {
valstr = val
} else {
try {
valstr = JSON.stringify(val, function (_key, val) {
if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
const sortedObj = {}
items(val, (n) => {
sortedObj[n[0]] = val[n[0]]
})
return sortedObj
}
return val
})
valstr = valstr.replace(R_QUOTES, S_MT)
} catch {
valstr = '__STRINGIFY_FAILED__'
}
}
if (null != maxlen && -1 < maxlen) {
let js = valstr.substring(0, maxlen)
valstr = maxlen < valstr.length ? js.substring(0, maxlen - 3) + '...' : valstr
}
if (pretty) {
// Indicate deeper JSON levels with different terminal colors (simplistic wrt strings).
let c = items(
[81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69],
(n) => '\x1b[38;5;' + n[1] + 'm',
),
r = '\x1b[0m',
d = 0,
o = c[0],
t = o
for (const ch of valstr) {
if (ch === '{' || ch === '[') {
d++
o = c[d % c.length]
t += o + ch
} else if (ch === '}' || ch === ']') {
t += o + ch
d--
o = c[d % c.length]
} else {
t += o + ch
}
}
return t + r
}
return valstr
}
// Build a human friendly path string.
function pathify(val, startin, endin) {
let pathstr = NONE
let path = islist(val)
? val
: S_string == typeof val
? [val]
: S_number == typeof val
? [val]
: NONE
const start = null == startin ? 0 : -1 < startin ? startin : 0
const end = null == endin ? 0 : -1 < endin ? endin : 0
if (NONE != path && 0 <= start) {
path = slice(path, start, path.length - end)
if (0 === path.length) {
pathstr = '<root>'
} else {
pathstr = join(
items(
filter(path, (n) => iskey(n[1])),
(n) => {
let p = n[1]
return S_number === typeof p ? S_MT + Math.floor(p) : p.replace(R_DOT, S_MT)
},
),
S_DT,
)
}
}
if (NONE === pathstr) {
pathstr = '<unknown-path' + (NONE === val ? S_MT : S_CN + stringify(val, 47)) + '>'
}
return pathstr
}
// Clone a JSON-like data structure.
// NOTE: function and instance values are copied, *not* cloned.
function clone(val) {
const refs = []
const reftype = T_function | T_instance
const replacer = (_k, v) =>
0 < (reftype & typify(v)) ? (refs.push(v), '`$REF:' + (refs.length - 1) + '`') : v
const reviver = (_k, v, m) =>
S_string === typeof v ? ((m = v.match(R_CLONE_REF)), m ? refs[m[1]] : v) : v
const out = NONE === val ? NONE : JSON.parse(JSON.stringify(val, replacer), reviver)
return out
}
// Define a JSON Object using function arguments.
function jm(...kv) {
const kvsize = size(kv)
const o = {}
for (let i = 0; i < kvsize; i += 2) {
// Builders are Group B (value processing): preserve literal stored
// values, including null. Direct array index distinguishes "slot exists
// with value null" from "slot beyond end of kv".
let k = i < kv.length ? kv[i] : '$KEY' + i
k = 'string' === typeof k ? k : stringify(k)
o[k] = i + 1 < kv.length ? kv[i + 1] : null
}
return o
}
// Define a JSON Array using function arguments.
function jt(...v) {
const vsize = size(v)
const a = new Array(vsize)
for (let i = 0; i < vsize; i++) {
a[i] = getprop(v, i, null)
}
return a
}
// Safely delete a property from an object or array element.
// Undefined arguments and invalid keys are ignored.
// Returns the (possibly modified) parent.
// For objects, the property is deleted using the delete operator.
// For arrays, the element at the index is removed and remaining elements are shifted down.
// NOTE: parent list may be new list, thus update references.
function delprop(parent, key) {
if (!iskey(key)) {
return parent
}
if (ismap(parent)) {
key = strkey(key)
delete parent[key]
} else if (islist(parent)) {
// Ensure key is an integer.
let keyI = +key
if (isNaN(keyI)) {
return parent
}
keyI = Math.floor(keyI)
// Delete list element at position keyI, shifting later elements down.
const psize = size(parent)
if (0 <= keyI && keyI < psize) {
for (let pI = keyI; pI < psize - 1; pI++) {
parent[pI] = parent[pI + 1]
}
parent.length = parent.length - 1
}
}
return parent
}
// Safely set a property. Undefined arguments and invalid keys are ignored.
// Returns the (possibly modified) parent.
// If the parent is a list, and the key is negative, prepend the value.
// NOTE: If the key is above the list size, append the value; below, prepend.
// NOTE: parent list may be new list, thus update references.
function setprop(parent, key, val) {
if (!iskey(key)) {
return parent
}
if (ismap(parent)) {
key = S_MT + key
const pany = parent
pany[key] = val
} else if (islist(parent)) {
// Ensure key is an integer.
let keyI = +key
if (isNaN(keyI)) {
return parent
}
keyI = Math.floor(keyI)
// TODO: DELETE list element
// Set or append value at position keyI, or append if keyI out of bounds.
if (0 <= keyI) {
parent[slice(keyI, 0, size(parent) + 1)] = val
}
// Prepend value if keyI is negative
else {
parent.unshift(val)
}
}
return parent
}
// Walk a data structure depth first, applying a function to each value.
// The `path` argument passed to the before/after callbacks is a single
// mutable array per depth, shared across all callback invocations for the
// lifetime of this top-level walk call. Callbacks that need to store the
// path MUST clone it (e.g. `path.slice()`); the contents will otherwise
// be overwritten by subsequent visits.
function walk(
// These arguments are the public interface.
val,
// Before descending into a node.
before,
// After descending into a node.
after,
// Maximum recursive depth, default: 32. Use null for infinite depth.
maxdepth,
// These areguments are used for recursive state.
key,
parent,
path,
pool,
) {
if (NONE === pool) {
pool = [[]]
}
if (NONE === path) {
path = pool[0]
}
const depth = path.length
let out = null == before ? val : before(key, val, parent, path)
maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : MAXDEPTH
if (0 === maxdepth || (0 < maxdepth && maxdepth <= depth)) {
return out
}
if (isnode(out)) {
const childDepth = depth + 1
let childPath = pool[childDepth]
if (NONE === childPath) {
childPath = new Array(childDepth)
pool[childDepth] = childPath
}
// Sync prefix [0..depth-1] from the current path. Only needed once per
// parent: siblings share the same prefix and will each overwrite slot
// [depth] below.
for (let i = 0; i < depth; i++) {
childPath[i] = path[i]
}
for (let [ckey, child] of items(out)) {
childPath[depth] = S_MT + ckey
setprop(out, ckey, walk(child, before, after, maxdepth, ckey, out, childPath, pool))
}
}
out = null == after ? out : after(key, out, parent, path)
return out
}
// Merge a list of values into each other. Later values have
// precedence. Nodes override scalars. Node kinds (list or map)
// override each other, and do *not* merge. The first element is
// modified.
function merge(val, maxdepth) {
// const md: number = null == maxdepth ? MAXDEPTH : maxdepth < 0 ? 0 : maxdepth
const md = slice(maxdepth ?? MAXDEPTH, 0)
let out = NONE
// Handle edge cases.
if (!islist(val)) {
return val
}
const list = val
const lenlist = list.length
if (0 === lenlist) {
return NONE
} else if (1 === lenlist) {
return list[0]
}
// Merge a list of values.
out = getprop(list, 0, {})
for (let oI = 1; oI < lenlist; oI++) {
let obj = list[oI]
if (!isnode(obj)) {
// Nodes win.
out = obj
} else {
// Current value at path end in overriding node.
let cur = [out]
// Current value at path end in destination node.
let dst = [out]
function before(key, val, _parent, path) {
const pI = size(path)
if (md <= pI) {
setprop(cur[pI - 1], key, val)
}
// Scalars just override directly.
else if (!isnode(val)) {
cur[pI] = val
}
// Descend into override node - Set up correct target in `after` function.
else {
// Descend into destination node using same key.
dst[pI] = 0 < pI ? getprop(dst[pI - 1], key) : dst[pI]
const tval = dst[pI]
// Destination empty, so create node (unless override is class instance).
if (NONE === tval && 0 === (T_instance & typify(val))) {
cur[pI] = islist(val) ? [] : {}
}
// Matching override and destination so continue with their values.
else if (typify(val) === typify(tval)) {
cur[pI] = tval
}
// Override wins.
else {
cur[pI] = val
// No need to descend when override wins (destination is discarded).
val = NONE
}
}
// console.log('BEFORE-END', pathify(path), '@', pI, key,
// stringify(val, -1, 1), stringify(parent, -1, 1),
// 'CUR=', stringify(cur, -1, 1), 'DST=', stringify(dst, -1, 1))
return val
}
function after(key, _val, _parent, path) {
const cI = size(path)
const target = cur[cI - 1]
const value = cur[cI]
// console.log('AFTER-PREP', pathify(path), '@', cI, cur, '|',
// stringify(key, -1, 1), stringify(value, -1, 1), 'T=', stringify(target, -1, 1))
setprop(target, key, value)
return value
}
// Walk overriding node, creating paths in output as needed.
out = walk(obj, before, after, maxdepth)
// console.log('WALK-DONE', out, obj)
}
}
if (0 === md) {
out = getelem(list, -1)
out = islist(out) ? [] : ismap(out) ? {} : out
}
return out
}
// Set a value using a path. Missing path parts are created.
// String paths create only maps. Use a string list to create list parts.
function setpath(store, path, val, injdef) {
const pathType = typify(path)
const parts =
0 < (T_list & pathType)
? path
: 0 < (T_string & pathType)
? path.split(S_DT)
: 0 < (T_number & pathType)
? [path]
: NONE
if (NONE === parts) {
return NONE
}
const base = getprop(injdef, S_base)
const numparts = size(parts)
let parent = getprop(store, base, store)
for (let pI = 0; pI < numparts - 1; pI++) {
const partKey = getelem(parts, pI)
let nextParent = getprop(parent, partKey)
if (!isnode(nextParent)) {
nextParent = 0 < (T_number & typify(getelem(parts, pI + 1))) ? [] : {}
setprop(parent, partKey, nextParent)
}
parent = nextParent
}
if (DELETE === val) {
delprop(parent, getelem(parts, -1))
} else {
setprop(parent, getelem(parts, -1), val)
}
return parent
}
function getpath(store, path, injdef) {
// Operate on a string array.
const parts = islist(path)
? path
: 'string' === typeof path
? path.split(S_DT)
: 'number' === typeof path
? [strkey(path)]
: NONE
if (NONE === parts) {
return NONE
}
// let root = store
let val = store
const base = getprop(injdef, S_base)
const src = getprop(store, base, store)
const numparts = size(parts)
const dparent = getprop(injdef, 'dparent')
// An empty path (incl empty string) just finds the store.
if (null == path || null == store || (1 === numparts && S_MT === parts[0])) {
val = src
} else if (0 < numparts) {
// Check for $ACTIONs
if (1 === numparts) {
val = getprop(store, parts[0])
}
if (!isfunc(val)) {
val = src
const m = parts[0].match(R_META_PATH)
if (m && injdef && injdef.meta) {
val = getprop(injdef.meta, m[1])
parts[0] = m[3]
}
const dpath = getprop(injdef, 'dpath')
for (let pI = 0; NONE !== val && pI < numparts; pI++) {
let part = parts[pI]
if (injdef && S_DKEY === part) {
part = getprop(injdef, S_key)
} else if (injdef && part.startsWith('$GET:')) {
// $GET:path$ -> get store value, use as path part (string)
part = stringify(getpath(src, slice(part, 5, -1)))
} else if (injdef && part.startsWith('$REF:')) {
// $REF:refpath$ -> get spec value, use as path part (string)
part = stringify(getpath(getprop(store, S_DSPEC), slice(part, 5, -1)))
} else if (injdef && part.startsWith('$META:')) {
// $META:metapath$ -> get meta value, use as path part (string)
part = stringify(getpath(getprop(injdef, 'meta'), slice(part, 6, -1)))
}
// $$ escapes $
part = part.replace(R_DOUBLE_DOLLAR, '$')
if (S_MT === part) {
let ascends = 0
while (S_MT === parts[1 + pI]) {
ascends++
pI++
}
if (injdef && 0 < ascends) {
if (pI === parts.length - 1) {
ascends--
}
if (0 === ascends) {
val = dparent
} else {
// const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1))
const fullpath = flatten([slice(dpath, 0 - ascends), parts.slice(pI + 1)])