voxgig-struct 0.1.2

Uniform JSON-shaped data structure manipulations — Rust port of @voxgig/struct
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
// Copyright (c) 2025-2026 Voxgig Ltd. MIT LICENSE.
// VERSION: @voxgig/struct 0.1.0
//
// Major utilities — walk, merge, getpath, setpath, and (staged) the
// inject / transform / validate / select machinery. See rs/PLAN.md §8-§11.
//
// `merge` is implemented walk-based to stay close to the canonical; the
// `cur`/`dst` scratch vectors are shared between the before/after closures
// via `Rc<RefCell<…>>` (Rust can't have two FnMut closures both holding a
// `&mut` to the same Vec).

use std::cell::RefCell;
use std::rc::Rc;

use crate::consts::*;
use crate::mini::*;
use crate::ordered_map::OrderedMap;
use crate::value::{js_string, js_to_int32, js_to_number, Value};
use crate::StructError;

// ---------------------------------------------------------------------
// callback / function types
// ---------------------------------------------------------------------

/// `WalkApply` — `(key, val, parent, path) -> any`. `key` is `Noval` at the
/// root and a `Str` for every descendant (matches the canonical, where
/// `items` always yields string keys).
pub type WalkClosure<'a> = dyn FnMut(&Value, &Value, &Value, &[String]) -> Value + 'a;

/// `Injector` — `(inj, val, ref, store) -> any`.
pub type NativeFn = crate::value::NativeFn;

/// `Modify` — `(val, key, parent, inj, store)`.
pub type Modify = crate::value::ModifyFn;

pub type Inj = Rc<RefCell<Injection>>;
pub type SVec = Rc<RefCell<Vec<String>>>;

// ---------------------------------------------------------------------
// walk
// ---------------------------------------------------------------------

pub fn walk(
    val: Value,
    before: Option<&mut WalkClosure>,
    after: Option<&mut WalkClosure>,
    maxdepth: Option<i64>,
) -> Value {
    let mut path: Vec<String> = Vec::new();
    walk_impl(
        val,
        before,
        after,
        maxdepth,
        &Value::Noval,
        &Value::Noval,
        &mut path,
    )
}

fn walk_impl(
    val: Value,
    mut before: Option<&mut WalkClosure>,
    mut after: Option<&mut WalkClosure>,
    maxdepth: Option<i64>,
    key: &Value,
    parent: &Value,
    path: &mut Vec<String>,
) -> Value {
    let depth = path.len() as i64;

    let out = match before {
        Some(ref mut f) => f(key, &val, parent, path),
        None => val,
    };

    let md = match maxdepth {
        Some(m) if m >= 0 => m,
        _ => MAXDEPTH,
    };
    if md == 0 || (md > 0 && md <= depth) {
        return out;
    }

    if is_node(&out) {
        let entries = items_vec(&out);
        for (ckey, child) in entries {
            path.push(ckey.clone());
            let res = walk_impl(
                child,
                before.as_deref_mut(),
                after.as_deref_mut(),
                maxdepth,
                &Value::str(ckey.clone()),
                &out,
                path,
            );
            path.pop();
            set_prop(out.clone(), &Value::str(ckey), res);
        }
    }

    match after {
        Some(ref mut f) => f(key, &out, parent, path),
        None => out,
    }
}

// ---------------------------------------------------------------------
// merge
// ---------------------------------------------------------------------

const T_INSTANCE_I: i64 = T_INSTANCE as i64;

pub fn merge(val: &Value, maxdepth: Option<i64>) -> Value {
    let md = match slice(
        Value::Num(maxdepth.unwrap_or(MAXDEPTH) as f64),
        Some(0),
        None,
        false,
    ) {
        Value::Num(n) => n as i64,
        _ => MAXDEPTH,
    };

    let list: Vec<Value> = match val {
        Value::List(l) => l.borrow().clone(),
        other => return other.clone(),
    };

    if list.is_empty() {
        return Value::Noval;
    }
    if list.len() == 1 {
        return list[0].clone();
    }

    let mut out = match &list[0] {
        Value::Noval => Value::empty_map(),
        other => other.clone(),
    };

    for obj in list.iter().skip(1) {
        let obj = obj.clone();
        if !is_node(&obj) {
            out = obj;
            continue;
        }

        let cur: Rc<RefCell<Vec<Value>>> = Rc::new(RefCell::new(vec![out.clone()]));
        let dst: Rc<RefCell<Vec<Value>>> = Rc::new(RefCell::new(vec![out.clone()]));

        let cur_b = cur.clone();
        let dst_b = dst.clone();
        let mut before = move |key: &Value, v: &Value, _parent: &Value, path: &[String]| -> Value {
            let pi = path.len() as i64;
            let mut ret = v.clone();

            if md <= pi {
                let target = cur_b
                    .borrow()
                    .get((pi - 1) as usize)
                    .cloned()
                    .unwrap_or(Value::Noval);
                set_prop(target, key, v.clone());
            } else if !is_node(v) {
                let mut cb = cur_b.borrow_mut();
                grow(&mut cb, pi as usize);
                cb[pi as usize] = v.clone();
            } else {
                let tval = {
                    let d = if pi > 0 {
                        let prev = dst_b
                            .borrow()
                            .get((pi - 1) as usize)
                            .cloned()
                            .unwrap_or(Value::Noval);
                        get_prop(&prev, key, Value::Noval)
                    } else {
                        dst_b
                            .borrow()
                            .get(pi as usize)
                            .cloned()
                            .unwrap_or(Value::Noval)
                    };
                    let mut db = dst_b.borrow_mut();
                    grow(&mut db, pi as usize);
                    db[pi as usize] = d.clone();
                    d
                };
                let mut cb = cur_b.borrow_mut();
                grow(&mut cb, pi as usize);
                if tval.is_noval() && (typify(v) & T_INSTANCE_I) == 0 {
                    cb[pi as usize] = if is_list(v) {
                        Value::empty_list()
                    } else {
                        Value::empty_map()
                    };
                } else if typify(v) == typify(&tval) {
                    cb[pi as usize] = tval;
                } else {
                    cb[pi as usize] = v.clone();
                    ret = Value::Noval;
                }
            }
            ret
        };

        let cur_a = cur.clone();
        let mut after = move |key: &Value, _v: &Value, _parent: &Value, path: &[String]| -> Value {
            let ci = path.len() as i64;
            let (target, value) = {
                let cb = cur_a.borrow();
                (
                    cb.get((ci - 1) as usize).cloned().unwrap_or(Value::Noval),
                    cb.get(ci as usize).cloned().unwrap_or(Value::Noval),
                )
            };
            set_prop(target, key, value.clone());
            value
        };

        out = walk(obj, Some(&mut before), Some(&mut after), maxdepth);
    }

    if md == 0 {
        let last = get_elem(&Value::list(list.clone()), &Value::Num(-1.0), Value::Noval);
        out = match &last {
            Value::List(_) => Value::empty_list(),
            Value::Map(_) => Value::empty_map(),
            other => other.clone(),
        };
    }

    out
}

fn grow(v: &mut Vec<Value>, idx: usize) {
    while v.len() <= idx {
        v.push(Value::Noval);
    }
}

// ---------------------------------------------------------------------
// Injection state
// ---------------------------------------------------------------------

pub struct Injection {
    pub mode: i64,
    pub full: bool,
    pub key_i: i64,
    pub keys: SVec,
    pub key: String,
    pub val: Value,
    pub parent: Value,
    pub path: Vec<String>,
    pub nodes: Vec<Value>,
    pub handler: NativeFn,
    pub errs: Value, // Value::List
    pub meta: Value, // Value::Map
    pub dparent: Value,
    pub dpath: Vec<String>,
    pub base: Option<String>,
    pub modify: Option<Modify>,
    pub extra: Option<Value>,
    pub prior: Option<Inj>,
}

/// Public `injdef` argument — the subset of `Partial<Injection>` callers set.
#[derive(Default, Clone)]
pub struct InjectDef {
    pub base: Option<String>,
    pub errs: Option<Value>,
    pub meta: Option<Value>,
    pub modify: Option<Modify>,
    pub handler: Option<NativeFn>,
    pub extra: Option<Value>,
    pub dparent: Option<Value>,
    pub dpath: Option<Vec<String>>,
    pub key: Option<Value>,
}

impl Injection {
    /// Build a (mostly-empty) injection carrying just the fields the public
    /// `getpath` / `setpath` read from an `injdef`.
    pub fn from_def(def: Option<&InjectDef>) -> Inj {
        let inj = Injection {
            mode: M_VAL,
            full: false,
            key_i: 0,
            keys: Rc::new(RefCell::new(vec![S_DTOP.to_string()])),
            key: S_DTOP.to_string(),
            val: Value::Noval,
            parent: Value::Noval,
            path: vec![S_DTOP.to_string()],
            nodes: vec![Value::Noval],
            handler: inject_handler_fn(),
            errs: Value::empty_list(),
            meta: Value::empty_map(),
            dparent: Value::Noval,
            dpath: vec![S_DTOP.to_string()],
            base: None,
            modify: None,
            extra: None,
            prior: None,
        };
        let inj = Rc::new(RefCell::new(inj));
        if let Some(d) = def {
            let mut b = inj.borrow_mut();
            if let Some(x) = &d.base {
                b.base = Some(x.clone());
            }
            if let Some(x) = &d.errs {
                b.errs = x.clone();
            }
            if let Some(x) = &d.meta {
                b.meta = x.clone();
            }
            if let Some(x) = &d.modify {
                b.modify = Some(x.clone());
            }
            if let Some(x) = &d.handler {
                b.handler = x.clone();
            }
            if let Some(x) = &d.extra {
                b.extra = Some(x.clone());
            }
            if let Some(x) = &d.dparent {
                b.dparent = x.clone();
            }
            if let Some(x) = &d.dpath {
                b.dpath = x.clone();
            }
            if let Some(x) = &d.key {
                b.key = str_key(x.clone());
            }
        }
        inj
    }

    fn has_handler(def: Option<&InjectDef>) -> bool {
        def.map(|d| d.handler.is_some()).unwrap_or(false)
    }

    /// Fresh root injection: `val` wrapped in the virtual parent holder.
    pub fn root(val: Value, parent: Value) -> Inj {
        let parent_clone = parent.clone();
        Rc::new(RefCell::new(Injection {
            mode: M_VAL,
            full: false,
            key_i: 0,
            keys: Rc::new(RefCell::new(vec![S_DTOP.to_string()])),
            key: S_DTOP.to_string(),
            val,
            parent,
            path: vec![S_DTOP.to_string()],
            nodes: vec![parent_clone],
            handler: inject_handler_fn(),
            errs: Value::empty_list(),
            meta: Value::empty_map(),
            dparent: Value::Noval,
            dpath: vec![S_DTOP.to_string()],
            base: Some(S_DTOP.to_string()),
            modify: None,
            extra: None,
            prior: None,
        }))
    }

    pub fn descend(this: &Inj) {
        // meta.__d++
        {
            let b = this.borrow();
            if let Value::Map(m) = &b.meta {
                let cur = m
                    .borrow()
                    .get("__d")
                    .and_then(|v| v.as_num())
                    .unwrap_or(0.0);
                m.borrow_mut()
                    .insert("__d".to_string(), Value::Num(cur + 1.0));
            }
        }
        let (parentkey, has_dparent, dpath_len, last_part) = {
            let b = this.borrow();
            let parentkey = if b.path.len() >= 2 {
                Some(b.path[b.path.len() - 2].clone())
            } else {
                None
            };
            (
                parentkey,
                !b.dparent.is_noval(),
                b.dpath.len(),
                b.dpath.last().cloned(),
            )
        };

        if !has_dparent {
            if dpath_len > 1 {
                if let Some(pk) = parentkey {
                    this.borrow_mut().dpath.push(pk);
                }
            }
        } else if let Some(pk) = parentkey {
            let newdparent = {
                let b = this.borrow();
                get_prop(&b.dparent, &Value::str(pk.clone()), Value::Noval)
            };
            let mut b = this.borrow_mut();
            b.dparent = newdparent;
            if last_part.as_deref() == Some(format!("$:{pk}").as_str()) {
                let n = b.dpath.len();
                b.dpath.truncate(n.saturating_sub(1));
            } else {
                b.dpath.push(pk);
            }
        }
    }

    pub fn child(this: &Inj, key_i: i64, keys: SVec) -> Inj {
        let (
            key,
            parent_val,
            cval,
            path,
            nodes,
            mode,
            handler,
            modify,
            base,
            meta,
            errs,
            dpath,
            dparent,
        ) = {
            let b = this.borrow();
            let key = str_key(
                keys.borrow()
                    .get(key_i.max(0) as usize)
                    .cloned()
                    .map(Value::Str)
                    .unwrap_or(Value::Noval),
            );
            let parent_val = b.val.clone();
            let cval = get_prop(&parent_val, &Value::str(key.clone()), Value::Noval);
            let mut path = b.path.clone();
            path.push(key.clone());
            let mut nodes = b.nodes.clone();
            nodes.push(parent_val.clone());
            (
                key,
                parent_val,
                cval,
                path,
                nodes,
                b.mode,
                b.handler.clone(),
                b.modify.clone(),
                b.base.clone(),
                b.meta.clone(),
                b.errs.clone(),
                b.dpath.clone(),
                b.dparent.clone(),
            )
        };
        Rc::new(RefCell::new(Injection {
            mode,
            full: false,
            key_i,
            keys,
            key,
            val: cval,
            parent: parent_val,
            path,
            nodes,
            handler,
            errs,
            meta,
            dparent,
            dpath,
            base,
            modify,
            extra: None,
            prior: Some(Rc::clone(this)),
        }))
    }

    pub fn setval(this: &Inj, val: Value, ancestor: Option<i64>) -> Value {
        let anc = ancestor.unwrap_or(0);
        if anc < 2 {
            let (parent, key) = {
                let b = this.borrow();
                (b.parent.clone(), b.key.clone())
            };
            if val.is_noval() {
                let np = del_prop(parent, &Value::str(key));
                this.borrow_mut().parent = np.clone();
                np
            } else {
                set_prop(parent, &Value::str(key), val)
            }
        } else {
            let (aval, akey) = {
                let b = this.borrow();
                let n = b.nodes.len() as i64;
                let aval = if n - anc >= 0 {
                    b.nodes[(n - anc) as usize].clone()
                } else {
                    Value::Noval
                };
                let pn = b.path.len() as i64;
                let akey = if pn - anc >= 0 {
                    b.path[(pn - anc) as usize].clone()
                } else {
                    String::new()
                };
                (aval, akey)
            };
            if val.is_noval() {
                del_prop(aval, &Value::str(akey))
            } else {
                set_prop(aval, &Value::str(akey), val)
            }
        }
    }
}

// ---------------------------------------------------------------------
// getpath
// ---------------------------------------------------------------------

pub fn get_path(store: &Value, path: &Value, injdef: Option<&InjectDef>) -> Value {
    let inj: Option<Inj> = injdef.map(|_| Injection::from_def(injdef));
    get_path_inj(store, path, inj.as_ref())
}

/// Internal `getpath` working against a full `Inj` (used by the inject
/// machinery and by the public `get_path` wrapper).
pub fn get_path_inj(store: &Value, path: &Value, injdef: Option<&Inj>) -> Value {
    let mut parts: Vec<String> = match path {
        Value::List(l) => l
            .borrow()
            .iter()
            .map(|x| match x {
                Value::Str(s) => s.clone(),
                other => js_string(other),
            })
            .collect(),
        Value::Str(s) => s.split('.').map(|p| p.to_string()).collect(),
        Value::Num(n) => vec![str_key(Value::Num(*n))],
        _ => return Value::Noval,
    };

    let base = injdef.and_then(|i| i.borrow().base.clone());
    let src = match &base {
        Some(b) => get_prop(store, &Value::str(b.clone()), store.clone()),
        None => store.clone(),
    };
    let numparts = parts.len();
    let dparent = injdef
        .map(|i| i.borrow().dparent.clone())
        .unwrap_or(Value::Noval);

    let mut val = store.clone();

    let path_nullish = matches!(path, Value::Noval | Value::Null);
    if path_nullish
        || matches!(store, Value::Noval | Value::Null)
        || (numparts == 1 && parts[0].is_empty())
    {
        val = src.clone();
    } else if numparts > 0 {
        if numparts == 1 {
            val = get_prop(store, &Value::str(parts[0].clone()), Value::Noval);
        }

        if !is_func(&val) {
            val = src.clone();

            // meta path prefix:  "name$=..."  /  "name$~..."
            if let Some(inj) = injdef {
                let meta = inj.borrow().meta.clone();
                let first = parts[0].clone();
                if let Some(caps) = R_META_PATH.captures(&first) {
                    if !meta.is_noval() {
                        val = get_prop(&meta, &Value::str(caps[1].to_string()), Value::Noval);
                        parts[0] = caps[3].to_string();
                    }
                }
            }

            let dpath: Vec<String> = injdef.map(|i| i.borrow().dpath.clone()).unwrap_or_default();

            let mut p_i = 0usize;
            while !val.is_noval() && p_i < numparts {
                let mut part = parts[p_i].clone();

                if let Some(inj) = injdef {
                    if part == S_DKEY {
                        part = inj.borrow().key.clone();
                    } else if let Some(rest) = part.strip_prefix("$GET:") {
                        part = js_string(&get_path_inj(&src, &Value::str(drop_last(rest)), None));
                    } else if let Some(rest) = part.strip_prefix("$REF:") {
                        let spec = get_prop(store, &Value::str(S_DSPEC), Value::Noval);
                        part = js_string(&get_path_inj(&spec, &Value::str(drop_last(rest)), None));
                    } else if let Some(rest) = part.strip_prefix("$META:") {
                        let meta = inj.borrow().meta.clone();
                        part = js_string(&get_path_inj(&meta, &Value::str(drop_last(rest)), None));
                    }
                }

                // str::replace allocates a fresh String even with no match, so
                // skip it for the common no-`$$` segment.
                if part.contains("$$") {
                    part = part.replace("$$", "$");
                }

                if part.is_empty() {
                    let mut ascends = 0i64;
                    while parts.get(1 + p_i).map(|s| s.is_empty()).unwrap_or(false) {
                        ascends += 1;
                        p_i += 1;
                    }

                    if injdef.is_some() && ascends > 0 {
                        if p_i == parts.len() - 1 {
                            ascends -= 1;
                        }
                        if ascends == 0 {
                            val = dparent.clone();
                        } else {
                            // fullpath = slice(dpath, -ascends) ++ parts[p_i+1..]
                            let head = slice(
                                Value::list(dpath.iter().cloned().map(Value::Str).collect()),
                                Some(-ascends),
                                None,
                                false,
                            );
                            let mut fullpath: Vec<String> = match &head {
                                Value::List(l) => l
                                    .borrow()
                                    .iter()
                                    .map(|x| x.as_str().map(|s| s.to_string()).unwrap_or_default())
                                    .collect(),
                                _ => Vec::new(),
                            };
                            fullpath.extend_from_slice(&parts[p_i + 1..]);
                            if ascends <= dpath.len() as i64 {
                                val = get_path_inj(
                                    store,
                                    &Value::list(fullpath.into_iter().map(Value::Str).collect()),
                                    None,
                                );
                            } else {
                                val = Value::Noval;
                            }
                            break;
                        }
                    } else {
                        val = dparent.clone();
                    }
                } else {
                    val = get_prop(&val, &Value::str(part), Value::Noval);
                }

                p_i += 1;
            }
        }
    }

    if let Some(inj) = injdef {
        let handler = inj.borrow().handler.clone();
        let r = pathify(path, None, None);
        val = handler(inj, &val, &r, store);
    }

    val
}

fn drop_last(s: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    if chars.is_empty() {
        String::new()
    } else {
        chars[..chars.len() - 1].iter().collect()
    }
}

// ---------------------------------------------------------------------
// setpath
// ---------------------------------------------------------------------

pub fn set_path(store: &Value, path: &Value, val: Value, injdef: Option<&InjectDef>) -> Value {
    // Keep parts as Values so a numeric part (only possible when `path` is an
    // array) makes its parent a list, while a string part makes a map.
    let parts: Vec<Value> = match path {
        Value::List(l) => l.borrow().clone(),
        Value::Str(s) => s.split('.').map(Value::str).collect(),
        Value::Num(n) => vec![Value::Num(*n)],
        _ => return Value::Noval,
    };
    if parts.is_empty() {
        return Value::Noval;
    }

    let base = injdef.and_then(|d| d.base.clone());
    let numparts = parts.len();
    let mut parent = match &base {
        Some(b) => get_prop(store, &Value::str(b.clone()), store.clone()),
        None => store.clone(),
    };

    for p_i in 0..numparts - 1 {
        let part_key = parts[p_i].clone();
        let next_parent = get_prop(&parent, &part_key, Value::Noval);
        let next_parent = if !is_node(&next_parent) {
            let next_is_num = parts
                .get(p_i + 1)
                .map(|p| typify(p) & (T_NUMBER as i64) != 0)
                .unwrap_or(false);
            let np = if next_is_num {
                Value::empty_list()
            } else {
                Value::empty_map()
            };
            set_prop(parent.clone(), &part_key, np.clone());
            np
        } else {
            next_parent
        };
        parent = next_parent;
    }

    let last = parts[numparts - 1].clone();
    if val.is_delete() {
        del_prop(parent.clone(), &last);
    } else {
        set_prop(parent.clone(), &last, val);
    }

    parent
}

// ---------------------------------------------------------------------
// inject / transform / validate / select — staged (see rs/PLAN.md, NOTES.md)
// ---------------------------------------------------------------------

/// Default inject handler (`_injecthandler`): if the value is a `$NAME`
/// command function, call it; otherwise, in `val` mode for a full-string
/// injection, write the value back into the parent.
pub fn inject_handler_fn() -> NativeFn {
    Rc::new(inject_handler)
}

fn inject_handler(inj: &Inj, val: &Value, r: &str, store: &Value) -> Value {
    let iscmd = is_func(val) && (r.is_empty() || r.starts_with('$'));
    if iscmd {
        if let Value::Func(f) = val {
            return f(inj, val, r, store);
        }
    }
    let (mode, full) = {
        let b = inj.borrow();
        (b.mode, b.full)
    };
    if mode == M_VAL && full {
        Injection::setval(inj, val.clone(), None);
    }
    val.clone()
}

/// `_injectstr` — substitute `` `path` `` references inside a string.
fn injectstr(val: &str, store: &Value, inj: Option<&Inj>) -> Value {
    if val.is_empty() {
        return Value::str("");
    }

    if let Some(caps) = R_INJECTION_FULL.captures(val) {
        if let Some(i) = inj {
            i.borrow_mut().full = true;
        }
        let mut pathref = caps[1].to_string();
        if pathref.chars().count() > 3 {
            pathref = pathref.replace("$BT", S_BT).replace("$DS", S_DS);
        }
        return get_path_inj(store, &Value::str(pathref), inj);
    }

    // partial injection: replace each `ref` occurrence
    let out_str = R_INJECTION_PARTIAL
        .replace_all(val, |caps: &crate::re::Captures<'_>| -> String {
            let mut r = caps[1].to_string();
            if r.chars().count() > 3 {
                r = r.replace("$BT", S_BT).replace("$DS", S_DS);
            }
            if let Some(i) = inj {
                i.borrow_mut().full = false;
            }
            let found = get_path_inj(store, &Value::str(r), inj);
            match &found {
                Value::Noval => String::new(),
                Value::Str(s) => s.clone(),
                other => jsonify(
                    other,
                    Some(&JsonFlags {
                        indent: 0,
                        offset: 0,
                    }),
                ),
            }
        })
        .to_string();

    if let Some(i) = inj {
        let handler = {
            i.borrow_mut().full = true;
            i.borrow().handler.clone()
        };
        return handler(i, &Value::str(out_str), val, store);
    }
    Value::str(out_str)
}

pub fn inject(val: Value, store: &Value, injdef: Option<&InjectDef>) -> Value {
    let inj = make_root_injection(val.clone(), store, injdef);
    inject_inj(val, store, &inj)
}

/// Build the root injection for a top-level `inject` (mirrors the TS setup
/// block when `injdef.mode == null`).
fn make_root_injection(val: Value, store: &Value, injdef: Option<&InjectDef>) -> Inj {
    let mut top = OrderedMap::new();
    top.insert(S_DTOP.to_string(), val.clone());
    let inj = Injection::root(val, Value::map(top));
    {
        let mut b = inj.borrow_mut();
        b.dparent = store.clone();
        let store_errs = get_prop(store, &Value::str(S_DERRS), Value::Noval);
        if !store_errs.is_noval() {
            b.errs = store_errs;
        }
        if let Value::Map(m) = &b.meta {
            m.borrow_mut().insert("__d".to_string(), Value::Num(0.0));
        }
        if let Some(d) = injdef {
            if let Some(x) = &d.modify {
                b.modify = Some(x.clone());
            }
            if let Some(x) = &d.extra {
                b.extra = Some(x.clone());
            }
            if let Some(x) = &d.meta {
                b.meta = x.clone();
            }
            if let Some(x) = &d.handler {
                b.handler = x.clone();
            }
        }
    }
    inj
}

/// Recursive `inject` working against an existing injection.
// `nk_i` is re-read after every child phase to match the canonical loop
// (an injector in the M_VAL phase, e.g. $REF, may change `key_i`).
#[allow(unused_assignments)]
fn inject_inj(mut val: Value, store: &Value, inj: &Inj) -> Value {
    Injection::descend(inj);

    if is_node(&val) {
        // node keys: sorted, then `$`-bearing keys last (for maps).
        let nodekeys: SVec = {
            let ks = keysof_vec(&val);
            if is_map(&val) {
                let (mut plain, dollar): (Vec<String>, Vec<String>) =
                    ks.into_iter().partition(|k| !k.contains(S_DS));
                plain.extend(dollar);
                Rc::new(RefCell::new(plain))
            } else {
                Rc::new(RefCell::new(ks))
            }
        };

        let mut nk_i: i64 = 0;
        loop {
            if nk_i < 0 {
                nk_i += 1;
                continue;
            }
            if nk_i as usize >= nodekeys.borrow().len() {
                break;
            }

            let childinj = Injection::child(inj, nk_i, nodekeys.clone());
            let nodekey = childinj.borrow().key.clone();
            childinj.borrow_mut().mode = M_KEYPRE;

            let prekey = injectstr(&nodekey, store, Some(&childinj));
            nk_i = childinj.borrow().key_i;
            // (keys may have been replaced by an injector — `nodekeys` itself
            // is the shared Rc, so re-reading is implicit.)

            if !prekey.is_noval() {
                let cval = get_prop(&val, &prekey, Value::Noval);
                {
                    let mut b = childinj.borrow_mut();
                    b.val = cval.clone();
                    b.mode = M_VAL;
                }
                inject_inj(cval, store, &childinj);
                nk_i = childinj.borrow().key_i;

                childinj.borrow_mut().mode = M_KEYPOST;
                injectstr(&nodekey, store, Some(&childinj));
                nk_i = childinj.borrow().key_i;
            }

            nk_i += 1;
        }
    } else if let Value::Str(s) = val.clone() {
        inj.borrow_mut().mode = M_VAL;
        let r = injectstr(&s, store, Some(inj));
        val = r.clone();
        if !val.is_skip() {
            Injection::setval(inj, val.clone(), None);
        }
    }

    // custom modification
    let modify = inj.borrow().modify.clone();
    if let Some(m) = modify {
        if !val.is_skip() {
            let (mkey, mparent) = {
                let b = inj.borrow();
                (b.key.clone(), b.parent.clone())
            };
            let mval = get_prop(&mparent, &Value::str(mkey.clone()), Value::Noval);
            m(&mval, &Value::str(mkey), &mparent, inj, store);
        }
    }

    inj.borrow_mut().val = val;
    let parent = inj.borrow().parent.clone();
    // Read back the root via raw lookup (canonical TS `_lookup(inj.parent,
    // S_DTOP)`) so a null result is preserved, not dropped by Group A.
    lookup(&parent, &Value::str(S_DTOP))
}

// ---- transform commands ----------------------------------------------

const T_ANY_I: i64 = T_ANY as i64;

fn errs_push(inj: &Inj, msg: String) {
    let errs = inj.borrow().errs.clone();
    if let Value::List(l) = &errs {
        l.borrow_mut().push(Value::Str(msg));
    }
}

fn placement_str(mode: i64) -> &'static str {
    match mode {
        M_VAL => "value",
        M_KEYPRE | M_KEYPOST => "key",
        _ => "",
    }
}

pub fn check_placement(modes: i64, ijname: &str, parent_types: i64, inj: &Inj) -> bool {
    let (mode, parent) = {
        let b = inj.borrow();
        (b.mode, b.parent.clone())
    };
    if modes & mode == 0 {
        let expected: Vec<&str> = [M_KEYPRE, M_KEYPOST, M_VAL]
            .iter()
            .filter(|m| modes & **m != 0)
            .map(|m| placement_str(*m))
            .collect();
        errs_push(
            inj,
            format!(
                "${ijname}: invalid placement as {}, expected: {}.",
                placement_str(mode),
                expected.join(",")
            ),
        );
        return false;
    }
    if !is_empty(&Value::Num(parent_types as f64)) {
        let ptype = typify(&parent);
        if parent_types & ptype == 0 {
            errs_push(
                inj,
                format!(
                    "${ijname}: invalid placement in parent {}, expected: {}.",
                    type_name(ptype),
                    type_name(parent_types)
                ),
            );
            return false;
        }
    }
    true
}

pub fn injector_args(arg_types: &[i64], args: &[Value]) -> Vec<Value> {
    let mut found: Vec<Value> = Vec::with_capacity(1 + arg_types.len());
    found.push(Value::Noval);
    for (i, at) in arg_types.iter().enumerate() {
        let arg = args.get(i).cloned().unwrap_or(Value::Noval);
        let argtype = typify(&arg);
        if at & argtype == 0 {
            found[0] = Value::str(format!(
                "invalid argument: {} ({} at position {}) is not of type: {}.",
                stringify(&arg, Some(22), false),
                type_name(argtype),
                1 + i,
                type_name(*at)
            ));
            return found;
        }
        found.push(arg);
    }
    found
}

pub fn inject_child(child: Value, store: &Value, inj: &Inj) -> Inj {
    let prior = inj.borrow().prior.clone();
    let cinj: Inj = match prior {
        None => Rc::clone(inj),
        Some(p) => {
            let pprior = p.borrow().prior.clone();
            match pprior {
                Some(pp) => {
                    let (pki, pkeys, pkey) = {
                        let b = p.borrow();
                        (b.key_i, b.keys.clone(), b.key.clone())
                    };
                    let c = Injection::child(&pp, pki, pkeys);
                    c.borrow_mut().val = child.clone();
                    let cparent = c.borrow().parent.clone();
                    set_prop(cparent, &Value::str(pkey), child.clone());
                    c
                }
                None => {
                    let (ki, keys, key) = {
                        let b = inj.borrow();
                        (b.key_i, b.keys.clone(), b.key.clone())
                    };
                    let c = Injection::child(&p, ki, keys);
                    c.borrow_mut().val = child.clone();
                    let cparent = c.borrow().parent.clone();
                    set_prop(cparent, &Value::str(key), child.clone());
                    c
                }
            }
        }
    };
    let _ = inject_inj(child, store, &cinj);
    cinj
}

const FORMATTER_NAMES: [&str; 7] = [
    "identity", "upper", "lower", "string", "number", "integer", "concat",
];

fn apply_formatter(name: &str, k: &Value, v: &Value) -> Value {
    match name {
        "identity" => v.clone(),
        "upper" => {
            if is_node(v) {
                v.clone()
            } else {
                Value::str(js_string(v).to_uppercase())
            }
        }
        "lower" => {
            if is_node(v) {
                v.clone()
            } else {
                Value::str(js_string(v).to_lowercase())
            }
        }
        "string" => {
            if is_node(v) {
                v.clone()
            } else {
                Value::str(js_string(v))
            }
        }
        "number" => {
            if is_node(v) {
                v.clone()
            } else {
                let n = js_to_number(v);
                Value::Num(if n.is_nan() { 0.0 } else { n })
            }
        }
        "integer" => {
            if is_node(v) {
                v.clone()
            } else {
                let n = js_to_number(v);
                let n = if n.is_nan() { 0.0 } else { n };
                Value::Num(js_to_int32(n) as f64)
            }
        }
        "concat" => {
            if k.is_noval() && is_list(v) {
                Value::str(
                    items_vec(v)
                        .iter()
                        .map(|(_, n)| {
                            if is_node(n) {
                                String::new()
                            } else {
                                js_string(n)
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(""),
                )
            } else {
                v.clone()
            }
        }
        _ => v.clone(),
    }
}

// `$FORMAT` — render a templated value through a named (or supplied) formatter.
fn transform_format(inj: &Inj, _val: &Value, _r: &str, store: &Value) -> Value {
    inj.borrow().keys.borrow_mut().truncate(1);
    if inj.borrow().mode != M_VAL {
        return Value::Noval;
    }
    let (parent, path, nodes) = {
        let b = inj.borrow();
        (b.parent.clone(), b.path.clone(), b.nodes.clone())
    };
    let name = lookup(&parent, &Value::Num(1.0));
    let child = lookup(&parent, &Value::Num(2.0));
    let tkey = path
        .get(path.len().saturating_sub(2))
        .cloned()
        .unwrap_or_default();
    let nlen = nodes.len();
    let target = if nlen >= 2 {
        nodes[nlen - 2].clone()
    } else if nlen >= 1 {
        nodes[nlen - 1].clone()
    } else {
        Value::Noval
    };

    let cinj = inject_child(child, store, inj);
    let resolved = cinj.borrow().val.clone();

    let fname: Option<String> = name
        .as_str()
        .filter(|n| FORMATTER_NAMES.contains(n))
        .map(|s| s.to_string());
    if fname.is_none() && !is_func(&name) {
        errs_push(
            inj,
            format!("$FORMAT: unknown format: {}.", js_string(&name)),
        );
        return Value::Noval;
    }

    let out = if let Some(fn_name) = &fname {
        let mut fmt = |k: &Value, v: &Value, _p: &Value, _t: &[String]| -> Value {
            apply_formatter(fn_name, k, v)
        };
        walk(resolved, Some(&mut fmt), None, None)
    } else if let Value::Func(f) = &name {
        let f = f.clone();
        let mut fmt =
            |_k: &Value, v: &Value, _p: &Value, _t: &[String]| -> Value { f(inj, v, "", store) };
        walk(resolved, Some(&mut fmt), None, None)
    } else {
        resolved
    };

    set_prop(target, &Value::str(tkey), out.clone());
    out
}

// `$APPLY` — call a function (from the spec args) on the resolved child.
fn transform_apply(inj: &Inj, _val: &Value, _r: &str, store: &Value) -> Value {
    if !check_placement(M_VAL, "APPLY", T_LIST as i64, inj) {
        return Value::Noval;
    }
    let (parent, path, nodes) = {
        let b = inj.borrow();
        (b.parent.clone(), b.path.clone(), b.nodes.clone())
    };
    let args: Vec<Value> = slice(parent.clone(), Some(1), None, false)
        .as_list()
        .map(|l| l.borrow().clone())
        .unwrap_or_default();
    let ia = injector_args(&[T_FUNCTION as i64, T_ANY as i64], &args);
    if let Value::Str(e) = &ia[0] {
        errs_push(inj, format!("$APPLY: {e}"));
        return Value::Noval;
    }
    let apply = ia.get(1).cloned().unwrap_or(Value::Noval);
    let child = ia.get(2).cloned().unwrap_or(Value::Noval);
    let tkey = path
        .get(path.len().saturating_sub(2))
        .cloned()
        .unwrap_or_default();
    let nlen = nodes.len();
    let target = if nlen >= 2 {
        nodes[nlen - 2].clone()
    } else if nlen >= 1 {
        nodes[nlen - 1].clone()
    } else {
        Value::Noval
    };
    let cinj = inject_child(child, store, inj);
    let resolved = cinj.borrow().val.clone();
    // The corpus only exercises the error paths; if `apply` is a callable, do
    // a best-effort call (the canonical passes (resolved, store, cinj)).
    let out = if let Value::Func(f) = &apply {
        f(&cinj, &resolved, "", store)
    } else {
        resolved
    };
    set_prop(target, &Value::str(tkey), out.clone());
    out
}

fn transform_delete(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    Injection::setval(inj, Value::Noval, None);
    Value::Noval
}

fn transform_copy(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    if !check_placement(M_VAL, "COPY", T_ANY_I, inj) {
        return Value::Noval;
    }
    let (dparent, key) = {
        let b = inj.borrow();
        (b.dparent.clone(), b.key.clone())
    };
    // Group B: preserve a stored null (canonical `_lookup(inj.dparent, inj.key)`).
    let out = lookup(&dparent, &Value::str(key));
    Injection::setval(inj, out.clone(), None);
    out
}

fn transform_key(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    let (mode, parent, dparent, anno_key) = {
        let b = inj.borrow();
        let anno_key = b.path.get(b.path.len().saturating_sub(2)).cloned();
        (b.mode, b.parent.clone(), b.dparent.clone(), anno_key)
    };
    if mode != M_VAL {
        return Value::Noval;
    }
    // Literal presence of the $KEY meta (canonical `_lookup(parent, S_BKEY)`):
    // a null keyspec still counts as declared, so use the raw lookup.
    let keyspec = lookup(&parent, &Value::str(S_BKEY));
    if !keyspec.is_noval() {
        del_prop(parent.clone(), &Value::str(S_BKEY));
        return get_prop(&dparent, &keyspec, Value::Noval);
    }
    let anno = get_prop(&parent, &Value::str(S_BANNO), Value::Noval);
    get_prop(
        &anno,
        &Value::str(S_KEY),
        anno_key.map(Value::Str).unwrap_or(Value::Noval),
    )
}

fn transform_anno(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    let parent = inj.borrow().parent.clone();
    del_prop(parent, &Value::str(S_BANNO));
    Value::Noval
}

fn transform_merge(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    let (mode, key, parent) = {
        let b = inj.borrow();
        (b.mode, b.key.clone(), b.parent.clone())
    };
    let mut out = Value::Noval;
    if mode == M_KEYPRE {
        out = Value::str(key);
    } else if mode == M_KEYPOST {
        out = Value::str(key.clone());
        let mut args = get_prop(&parent, &Value::str(key.clone()), Value::Noval);
        if !is_list(&args) {
            args = Value::list(vec![args]);
        }
        Injection::setval(inj, Value::Noval, None); // remove $MERGE key from parent
        let args_vec: Vec<Value> = args
            .as_list()
            .map(|l| l.borrow().clone())
            .unwrap_or_default();
        let mut mergelist: Vec<Value> = vec![parent.clone()];
        mergelist.extend(args_vec);
        mergelist.push(clone(&parent));
        merge(&Value::list(mergelist), Some(1));
    }
    out
}

fn slice_str_vec(v: &[String], start: Option<i64>, end: Option<i64>) -> Vec<String> {
    match slice(path_value(v), start, end, false) {
        Value::List(l) => l
            .borrow()
            .iter()
            .map(|x| x.as_str().map(|s| s.to_string()).unwrap_or_default())
            .collect(),
        _ => Vec::new(),
    }
}

// `$REF` — reference the original spec (enables recursive transforms).
fn transform_ref(inj: &Inj, val: &Value, _r: &str, store: &Value) -> Value {
    let (mode, parent, path, nodes) = {
        let b = inj.borrow();
        (b.mode, b.parent.clone(), b.path.clone(), b.nodes.clone())
    };
    if mode != M_VAL {
        return Value::Noval;
    }
    // Group B raw read of the ref arg (canonical `_lookup(inj.parent, 1)`).
    let refpath = lookup(&parent, &Value::Num(1.0));
    {
        let keylen = inj.borrow().keys.borrow().len() as i64;
        inj.borrow_mut().key_i = keylen;
    }
    // spec = ($SPEC)()
    let spec = {
        let sf = get_prop(store, &Value::str(S_DSPEC), Value::Noval);
        match &sf {
            Value::Func(f) => f(inj, &Value::Noval, "", store),
            _ => Value::Noval,
        }
    };
    let dpath = slice_str_vec(&path, Some(1), None);
    let dparent_for_ref = get_path_inj(&spec, &path_value(&dpath), None);
    let ref_def = InjectDef {
        dpath: Some(dpath.clone()),
        dparent: Some(dparent_for_ref),
        ..Default::default()
    };
    let refval = get_path(&spec, &refpath, Some(&ref_def));

    let mut has_sub_ref = false;
    if is_node(&refval) {
        let mut probe = |_k: &Value, v: &Value, _p: &Value, _t: &[String]| -> Value {
            if matches!(v, Value::Str(s) if s == "`$REF`") {
                has_sub_ref = true;
            }
            v.clone()
        };
        walk(refval.clone(), Some(&mut probe), None, None);
    }

    let tref = clone(&refval);
    let cpath = slice_str_vec(&path, Some(-3), None);
    let tpath = slice_str_vec(&path, Some(-1), None);
    let tcur = get_path_inj(store, &path_value(&cpath), None);
    let tval_at = get_path_inj(store, &path_value(&tpath), None);

    let rval = if !has_sub_ref || !tval_at.is_noval() {
        let tinj = Injection::child(
            inj,
            0,
            Rc::new(RefCell::new(vec![tpath
                .last()
                .cloned()
                .unwrap_or_default()])),
        );
        {
            let mut b = tinj.borrow_mut();
            b.path = tpath.clone();
            let nlen = nodes.len();
            b.nodes = if nlen >= 1 {
                nodes[..nlen - 1].to_vec()
            } else {
                Vec::new()
            };
            b.parent = if nlen >= 2 {
                nodes[nlen - 2].clone()
            } else {
                Value::Noval
            };
            b.val = tref.clone();
            b.dpath = cpath.clone();
            b.dparent = tcur.clone();
        }
        let _ = inject_inj(tref.clone(), store, &tinj);
        let v = tinj.borrow().val.clone();
        v
    } else {
        Value::Noval
    };

    let grandparent = Injection::setval(inj, rval, Some(2));
    if is_list(&grandparent) {
        let prior = inj.borrow().prior.clone();
        if let Some(p) = prior {
            p.borrow_mut().key_i -= 1;
        }
    }
    val.clone()
}

fn srcpath_split(srcpath: &str) -> Vec<String> {
    srcpath.split('.').map(|s| s.to_string()).collect()
}

// `$EACH` — apply a child template to every entry of a list or map.
// Spec form (a list): ['`$EACH`', 'source-path', child-template]
fn transform_each(inj: &Inj, _val: &Value, _r: &str, store: &Value) -> Value {
    if !check_placement(M_VAL, "EACH", T_LIST as i64, inj) {
        return Value::Noval;
    }
    // remove remaining keys to avoid spurious processing
    inj.borrow().keys.borrow_mut().truncate(1);

    let (parent, path, nodes, base) = {
        let b = inj.borrow();
        (
            b.parent.clone(),
            b.path.clone(),
            b.nodes.clone(),
            b.base.clone(),
        )
    };
    let args: Vec<Value> = slice(parent.clone(), Some(1), None, false)
        .as_list()
        .map(|l| l.borrow().clone())
        .unwrap_or_default();
    let ia = injector_args(&[T_STRING as i64, T_ANY as i64], &args);
    if let Value::Str(e) = &ia[0] {
        errs_push(inj, format!("$EACH: {e}"));
        return Value::Noval;
    }
    let srcpath = ia.get(1).cloned().unwrap_or(Value::Noval);
    let child = ia.get(2).cloned().unwrap_or(Value::Noval);
    let srcpath_str = srcpath.as_str().unwrap_or("").to_string();

    let srcstore = get_prop(
        store,
        &Value::str(base.clone().unwrap_or_default()),
        store.clone(),
    );
    let src = get_path_inj(&srcstore, &srcpath, Some(inj));
    let srctype = typify(&src);

    let tkey = path
        .get(path.len().saturating_sub(2))
        .cloned()
        .unwrap_or_default();
    let nlen = nodes.len();
    let target = if nlen >= 2 {
        nodes[nlen - 2].clone()
    } else if nlen >= 1 {
        nodes[nlen - 1].clone()
    } else {
        Value::Noval
    };

    let tval: Vec<Value> = if srctype & (T_LIST as i64) != 0 {
        items_vec(&src).iter().map(|_| clone(&child)).collect()
    } else if srctype & (T_MAP as i64) != 0 {
        items_vec(&src)
            .iter()
            .map(|(k, _)| {
                merge(
                    &Value::list(vec![
                        clone(&child),
                        Value::map_of([(
                            S_BANNO.to_string(),
                            Value::map_of([(S_KEY.to_string(), Value::str(k.clone()))]),
                        )]),
                    ]),
                    Some(1),
                )
            })
            .collect()
    } else {
        Vec::new()
    };

    let mut rval = Value::empty_list();
    if !tval.is_empty() {
        let tcur_inner: Value = if src.is_nullish() {
            Value::Noval
        } else {
            Value::list(items_vec(&src).into_iter().map(|(_, v)| v).collect())
        };
        let ckey = path
            .get(path.len().saturating_sub(2))
            .cloned()
            .unwrap_or_default();
        let tpath = slice_str_vec(&path, Some(-1), None);
        let mut dpath: Vec<String> = vec![S_DTOP.to_string()];
        dpath.extend(srcpath_split(&srcpath_str));
        dpath.push(format!("$:{ckey}"));

        let mut tcur = Value::map_of([(ckey.clone(), tcur_inner)]);
        if tpath.len() > 1 {
            let pkey = path
                .get(path.len().saturating_sub(3))
                .cloned()
                .unwrap_or_else(|| S_DTOP.to_string());
            tcur = Value::map_of([(pkey.clone(), tcur)]);
            dpath.push(format!("$:{pkey}"));
        }

        let tval_v = Value::list(tval);
        let tinj = Injection::child(inj, 0, Rc::new(RefCell::new(vec![ckey.clone()])));
        {
            let mut b = tinj.borrow_mut();
            b.path = tpath;
            b.nodes = if nlen >= 1 {
                nodes[..nlen - 1].to_vec()
            } else {
                Vec::new()
            };
            b.parent = b.nodes.last().cloned().unwrap_or(Value::Noval);
            b.val = tval_v.clone();
            b.dpath = dpath;
            b.dparent = tcur;
        }
        let pclone = tinj.borrow().parent.clone();
        set_prop(pclone, &Value::str(ckey), tval_v.clone());
        let _ = inject_inj(tval_v.clone(), store, &tinj);
        rval = tinj.borrow().val.clone();
    }

    set_prop(target, &Value::str(tkey), rval.clone());
    get_prop(&rval, &Value::Num(0.0), Value::Noval)
}

// `$PACK` — repack a list/map into a map keyed by `$KEY`.
// Spec form (a map): { '`$PACK`': ['source-path', child-template] }
fn transform_pack(inj: &Inj, _val: &Value, _r: &str, store: &Value) -> Value {
    if !check_placement(M_KEYPRE, "EACH", T_MAP as i64, inj) {
        return Value::Noval;
    }
    let (key, parent, path, nodes, base) = {
        let b = inj.borrow();
        (
            b.key.clone(),
            b.parent.clone(),
            b.path.clone(),
            b.nodes.clone(),
            b.base.clone(),
        )
    };
    let args = get_prop(&parent, &Value::str(key), Value::Noval);
    let args_vec: Vec<Value> = args
        .as_list()
        .map(|l| l.borrow().clone())
        .unwrap_or_default();
    let ia = injector_args(&[T_STRING as i64, T_ANY as i64], &args_vec);
    if let Value::Str(e) = &ia[0] {
        errs_push(inj, format!("$EACH: {e}"));
        return Value::Noval;
    }
    let srcpath = ia.get(1).cloned().unwrap_or(Value::Noval);
    let origchildspec = ia.get(2).cloned().unwrap_or(Value::Noval);
    let srcpath_str = srcpath.as_str().unwrap_or("").to_string();

    let tkey = path
        .get(path.len().saturating_sub(2))
        .cloned()
        .unwrap_or_default();
    let pathsize = path.len();
    let nlen = nodes.len();
    let target = if pathsize >= 2 {
        nodes.get(pathsize - 2).cloned().unwrap_or(Value::Noval)
    } else {
        nodes
            .get(pathsize.saturating_sub(1))
            .cloned()
            .unwrap_or(Value::Noval)
    };
    let target = if target.is_noval() {
        nodes
            .get(pathsize.saturating_sub(1))
            .cloned()
            .unwrap_or(Value::Noval)
    } else {
        target
    };

    let srcstore = get_prop(
        store,
        &Value::str(base.clone().unwrap_or_default()),
        store.clone(),
    );
    let src_raw = get_path_inj(&srcstore, &srcpath, Some(inj));
    let src: Value = if is_list(&src_raw) {
        src_raw
    } else if is_map(&src_raw) {
        Value::list(
            items_vec(&src_raw)
                .into_iter()
                .map(|(k, v)| {
                    set_prop(
                        v.clone(),
                        &Value::str(S_BANNO),
                        Value::map_of([(S_KEY.to_string(), Value::str(k))]),
                    );
                    v
                })
                .collect(),
        )
    } else {
        return Value::Noval;
    };
    if src.is_nullish() {
        return Value::Noval;
    }

    let keypath = get_prop(&origchildspec, &Value::str(S_BKEY), Value::Noval);
    let childspec = del_prop(origchildspec.clone(), &Value::str(S_BKEY));
    let child = get_prop(&childspec, &Value::str(S_BVAL), childspec.clone());

    let resolve_key = |srckey: &str, srcnode: &Value| -> Value {
        if keypath.is_noval() {
            Value::str(srckey)
        } else if let Value::Str(kp) = &keypath {
            if kp.starts_with('`') {
                let m = merge(
                    &Value::list(vec![
                        Value::empty_map(),
                        store.clone(),
                        Value::map_of([(S_DTOP.to_string(), srcnode.clone())]),
                    ]),
                    Some(1),
                );
                inject(Value::str(kp.clone()), &m, None)
            } else {
                get_path_inj(srcnode, &Value::str(kp.clone()), Some(inj))
            }
        } else {
            Value::str(srckey)
        }
    };

    let tval = Value::empty_map();
    for (srckey, srcnode) in items_vec(&src) {
        let k = resolve_key(&srckey, &srcnode);
        let tchild = clone(&child);
        set_prop(tval.clone(), &k, tchild.clone());
        let anno = get_prop(&srcnode, &Value::str(S_BANNO), Value::Noval);
        if anno.is_noval() {
            del_prop(tchild, &Value::str(S_BANNO));
        } else {
            set_prop(tchild, &Value::str(S_BANNO), anno);
        }
    }

    let mut rval = Value::empty_map();
    if !is_empty(&tval) {
        let tsrc = Value::empty_map();
        for (i, (_, n)) in items_vec(&src).into_iter().enumerate() {
            let kn = if keypath.is_noval() {
                Value::Num(i as f64)
            } else {
                resolve_key("", &n)
            };
            set_prop(tsrc.clone(), &kn, n);
        }
        let tpath = slice_str_vec(&path, Some(-1), None);
        let ckey = path
            .get(path.len().saturating_sub(2))
            .cloned()
            .unwrap_or_default();
        let mut dpath: Vec<String> = vec![S_DTOP.to_string()];
        dpath.extend(srcpath_split(&srcpath_str));
        dpath.push(format!("$:{ckey}"));
        let mut tcur = Value::map_of([(ckey.clone(), tsrc)]);
        if tpath.len() > 1 {
            let pkey = path
                .get(path.len().saturating_sub(3))
                .cloned()
                .unwrap_or_else(|| S_DTOP.to_string());
            tcur = Value::map_of([(pkey.clone(), tcur)]);
            dpath.push(format!("$:{pkey}"));
        }
        let tinj = Injection::child(inj, 0, Rc::new(RefCell::new(vec![ckey.clone()])));
        {
            let mut b = tinj.borrow_mut();
            b.path = tpath;
            b.nodes = if nlen >= 1 {
                nodes[..nlen - 1].to_vec()
            } else {
                Vec::new()
            };
            b.parent = b.nodes.last().cloned().unwrap_or(Value::Noval);
            b.val = tval.clone();
            b.dpath = dpath;
            b.dparent = tcur;
        }
        let _ = inject_inj(tval.clone(), store, &tinj);
        rval = tinj.borrow().val.clone();
    }

    set_prop(target, &Value::str(tkey), rval);
    Value::Noval
}

pub fn transform(
    data: &Value,
    spec: &Value,
    injdef: Option<&InjectDef>,
) -> Result<Value, StructError> {
    let origspec = spec.clone();
    let spec_clone = clone(&origspec);

    let extra = injdef.and_then(|d| d.extra.clone());
    let collect = injdef.map(|d| d.errs.is_some()).unwrap_or(false);
    let errs = injdef
        .and_then(|d| d.errs.clone())
        .unwrap_or_else(Value::empty_list);

    // split `extra` into data-extras (non-$) and transform-extras ($)
    let mut extra_transforms = OrderedMap::new();
    let extra_data: Value = match &extra {
        None => Value::Noval,
        Some(e) => {
            let mut a = OrderedMap::new();
            for (k, v) in items_vec(e) {
                if k.starts_with(S_DS) {
                    extra_transforms.insert(k, v);
                } else {
                    a.insert(k, v);
                }
            }
            Value::map(a)
        }
    };

    let data_clone = merge(
        &Value::list(vec![
            if is_empty(&extra_data) {
                Value::Noval
            } else {
                clone(&extra_data)
            },
            clone(data),
        ]),
        None,
    );

    // build the transform store
    let origspec_for_thunk = origspec.clone();
    let mut store_base: OrderedMap<Value> = OrderedMap::new();
    store_base.insert(S_DTOP.to_string(), data_clone);
    store_base.insert(
        "$SPEC".to_string(),
        Value::func(move |_i: &Inj, _v: &Value, _r: &str, _s: &Value| origspec_for_thunk.clone()),
    );
    store_base.insert(
        "$BT".to_string(),
        Value::func(|_i: &Inj, _v: &Value, _r: &str, _s: &Value| Value::str(S_BT)),
    );
    store_base.insert(
        "$DS".to_string(),
        Value::func(|_i: &Inj, _v: &Value, _r: &str, _s: &Value| Value::str(S_DS)),
    );
    store_base.insert(
        "$WHEN".to_string(),
        Value::func(|_i: &Inj, _v: &Value, _r: &str, _s: &Value| Value::str(iso_now())),
    );
    store_base.insert("$DELETE".to_string(), Value::func(transform_delete));
    store_base.insert("$COPY".to_string(), Value::func(transform_copy));
    store_base.insert("$KEY".to_string(), Value::func(transform_key));
    store_base.insert("$ANNO".to_string(), Value::func(transform_anno));
    store_base.insert("$MERGE".to_string(), Value::func(transform_merge));
    store_base.insert("$EACH".to_string(), Value::func(transform_each));
    store_base.insert("$PACK".to_string(), Value::func(transform_pack));
    store_base.insert("$REF".to_string(), Value::func(transform_ref));
    store_base.insert("$FORMAT".to_string(), Value::func(transform_format));
    store_base.insert("$APPLY".to_string(), Value::func(transform_apply));

    let store = merge(
        &Value::list(vec![
            Value::map(store_base),
            Value::map(extra_transforms),
            Value::map_of([(S_DERRS.to_string(), errs.clone())]),
        ]),
        Some(1),
    );

    let out = inject(spec_clone, &store, injdef);

    let errlen = errs.as_list().map(|l| l.borrow().len()).unwrap_or(0);
    if errlen > 0 && !collect {
        let msgs: Vec<String> = errs
            .as_list()
            .map(|l| l.borrow().iter().map(js_string).collect())
            .unwrap_or_default();
        return Err(StructError {
            message: msgs.join(" | "),
        });
    }

    Ok(out)
}

fn iso_now() -> String {
    // best-effort ISO-8601 UTC string; the corpus can't assert the exact
    // value (it changes), so granularity to the second is fine.
    use std::time::{SystemTime, UNIX_EPOCH};
    let dur = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    let secs = dur.as_secs() as i64;
    let millis = dur.subsec_millis();
    // days since 1970-01-01
    let days = secs.div_euclid(86_400);
    let tod = secs.rem_euclid(86_400);
    let (h, m, s) = (tod / 3600, (tod % 3600) / 60, tod % 60);
    let (y, mo, d) = civil_from_days(days);
    format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}.{millis:03}Z")
}

fn civil_from_days(z: i64) -> (i64, i64, i64) {
    // Howard Hinnant's algorithm.
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    (if m <= 2 { y + 1 } else { y }, m, d)
}

// ---- validate --------------------------------------------------------

fn path_value(path: &[String]) -> Value {
    Value::list(path.iter().cloned().map(Value::Str).collect())
}

fn invalid_type_msg(path: &[String], needtype: &str, vt: i64, v: &Value) -> String {
    let vs = if v.is_nullish() {
        "no value".to_string()
    } else {
        stringify(v, None, false)
    };
    let field_part = if path.len() > 1 {
        format!("field {} to be ", pathify(&path_value(path), Some(1), None))
    } else {
        String::new()
    };
    let type_part = if !v.is_nullish() {
        format!("{}{}", type_name(vt), S_VIZ)
    } else {
        String::new()
    };
    format!("Expected {field_part}{needtype}, but found {type_part}{vs}.")
}

fn validate_string(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    let (dparent, key, path) = {
        let b = inj.borrow();
        (b.dparent.clone(), b.key.clone(), b.path.clone())
    };
    let out = lookup(&dparent, &Value::str(key));
    let t = typify(&out);
    if t & (T_STRING as i64) == 0 {
        errs_push(inj, invalid_type_msg(&path, "string", t, &out));
        return Value::Noval;
    }
    if matches!(&out, Value::Str(s) if s.is_empty()) {
        errs_push(
            inj,
            format!(
                "Empty string at {}",
                pathify(&path_value(&path), Some(1), None)
            ),
        );
        return Value::Noval;
    }
    out
}

fn validate_type(inj: &Inj, _v: &Value, r: &str, _store: &Value) -> Value {
    let tname: String = r.chars().skip(1).collect::<String>().to_lowercase();
    let typev: i64 = match TYPENAME.iter().position(|x| *x == tname) {
        Some(idx) => 1i64 << (31 - idx as i64),
        None => 0,
    };
    let (dparent, key, path) = {
        let b = inj.borrow();
        (b.dparent.clone(), b.key.clone(), b.path.clone())
    };
    let out = lookup(&dparent, &Value::str(key));
    let t = typify(&out);
    if t & typev == 0 {
        errs_push(inj, invalid_type_msg(&path, &tname, t, &out));
        return Value::Noval;
    }
    out
}

fn validate_any(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    let (dparent, key) = {
        let b = inj.borrow();
        (b.dparent.clone(), b.key.clone())
    };
    lookup(&dparent, &Value::str(key))
}

/// Render a list of tvals as `"a, b, c"`, lowering `` `$NAME` `` -> `name`.
fn tvals_desc(tvals: &[Value]) -> String {
    let joined = tvals
        .iter()
        .map(|v| stringify(v, None, false))
        .collect::<Vec<_>>()
        .join(", ");
    R_TRANSFORM_NAME
        .replace_all(&joined, |caps: &crate::re::Captures<'_>| {
            caps[1].to_lowercase()
        })
        .to_string()
}

// Map / list `$CHILD`: apply a child template to every direct child.
fn validate_child(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    let (mode, key, parent, path, dparent) = {
        let b = inj.borrow();
        (
            b.mode,
            b.key.clone(),
            b.parent.clone(),
            b.path.clone(),
            b.dparent.clone(),
        )
    };

    if mode == M_KEYPRE {
        let childtm = get_prop(&parent, &Value::str(key), Value::Noval);
        let pkey = path
            .get(path.len().saturating_sub(2))
            .cloned()
            .unwrap_or_default();
        let mut tval = get_prop(&dparent, &Value::str(pkey), Value::Noval);
        if tval.is_noval() {
            tval = Value::empty_map();
        } else if !is_map(&tval) {
            errs_push(
                inj,
                invalid_type_msg(
                    &path[..path.len().saturating_sub(1)],
                    S_object,
                    typify(&tval),
                    &tval,
                ),
            );
            return Value::Noval;
        }
        let ckeys = keysof_vec(&tval);
        for ck in ckeys {
            set_prop(parent.clone(), &Value::str(ck.clone()), clone(&childtm));
            inj.borrow().keys.borrow_mut().push(ck);
        }
        Injection::setval(inj, Value::Noval, None);
        return Value::Noval;
    }

    if mode == M_VAL {
        if !is_list(&parent) {
            errs_push(inj, "Invalid $CHILD as value".to_string());
            return Value::Noval;
        }
        // List $CHILD template (canonical `_lookup(parent, 1)`): preserve a
        // null template literally rather than dropping it as Group A would.
        let childtm = lookup(&parent, &Value::Num(1.0));
        if dparent.is_noval() {
            slice(parent.clone(), Some(0), Some(0), true); // empty default
            return Value::Noval;
        }
        if !is_list(&dparent) {
            errs_push(
                inj,
                invalid_type_msg(
                    &path[..path.len().saturating_sub(1)],
                    S_list,
                    typify(&dparent),
                    &dparent,
                ),
            );
            let plen = parent.as_list().map(|l| l.borrow().len()).unwrap_or(0) as i64;
            inj.borrow_mut().key_i = plen;
            return dparent;
        }
        let dlen = dparent.as_list().map(|l| l.borrow().len()).unwrap_or(0);
        for n in 0..dlen {
            set_prop(parent.clone(), &Value::Num(n as f64), clone(&childtm));
        }
        slice(parent.clone(), Some(0), Some(dlen as i64), true);

        // NOTE: modifying inj! This extends the child value loop in inject
        // to cover every cloned child.
        {
            let keys = inj.borrow().keys.clone();
            let plen = parent.as_list().map(|l| l.borrow().len()).unwrap_or(0);
            let mut ks = keys.borrow_mut();
            for ckey_i in ks.len()..plen {
                ks.push(str_key(Value::Num(ckey_i as f64)));
            }
        }

        // Restart the child value loop at the first element (the loop
        // increments key_i on resume) so that the first element is also
        // validated against the child template.
        inj.borrow_mut().key_i = -1;

        // SKIP leaves the cloned child template in place at the first
        // element so the resumed loop can validate it.
        return Value::skip();
    }

    Value::Noval
}

// `$ONE`: value must match exactly one of a list of alternative sub-specs.
fn validate_one(inj: &Inj, _v: &Value, _r: &str, store: &Value) -> Value {
    let (mode, parent, key_i) = {
        let b = inj.borrow();
        (b.mode, b.parent.clone(), b.key_i)
    };
    if mode != M_VAL {
        return Value::Noval;
    }
    if !is_list(&parent) || key_i != 0 {
        let path = inj.borrow().path.clone();
        errs_push(
            inj,
            format!(
                "The $ONE validator at field {} must be the first element of an array.",
                pathify(&path_value(&path), Some(1), Some(1))
            ),
        );
        return Value::Noval;
    }
    let keylen = inj.borrow().keys.borrow().len() as i64;
    inj.borrow_mut().key_i = keylen;
    let dparent = inj.borrow().dparent.clone();
    Injection::setval(inj, dparent.clone(), Some(2));
    {
        let mut b = inj.borrow_mut();
        let n = b.path.len();
        b.path.truncate(n.saturating_sub(1));
        b.key = b.path.last().cloned().unwrap_or_default();
    }
    let path_after = inj.borrow().path.clone();
    let meta = inj.borrow().meta.clone();
    let tvals: Vec<Value> = slice(parent.clone(), Some(1), None, false)
        .as_list()
        .map(|l| l.borrow().clone())
        .unwrap_or_default();
    if tvals.is_empty() {
        errs_push(
            inj,
            format!(
                "The $ONE validator at field {} must have at least one argument.",
                pathify(&path_value(&path_after), Some(1), Some(1))
            ),
        );
        return Value::Noval;
    }
    for tval in &tvals {
        let terrs = Value::empty_list();
        let mut vstore = match merge(
            &Value::list(vec![Value::empty_map(), store.clone()]),
            Some(1),
        ) {
            v @ Value::Map(_) => v,
            _ => Value::empty_map(),
        };
        set_prop(vstore.clone(), &Value::str(S_DTOP), dparent.clone());
        let _ = &mut vstore;
        let vd = InjectDef {
            extra: Some(vstore.clone()),
            errs: Some(terrs.clone()),
            meta: Some(meta.clone()),
            ..Default::default()
        };
        let vcur = validate(&dparent, tval, Some(&vd)).unwrap_or(Value::Noval);
        Injection::setval(inj, vcur, Some(-2)); // hmm: ancestor -2 -> handled below
        let terrlen = terrs.as_list().map(|l| l.borrow().len()).unwrap_or(0);
        if terrlen == 0 {
            return Value::Noval;
        }
    }
    let valdesc = tvals_desc(&tvals);
    errs_push(
        inj,
        invalid_type_msg(
            &path_after,
            &format!(
                "{}{}",
                if tvals.len() > 1 { "one of " } else { "" },
                valdesc
            ),
            typify(&dparent),
            &dparent,
        ),
    );
    Value::Noval
}

// `$EXACT`: value must equal a literal exactly (no shape coercion).
fn validate_exact(inj: &Inj, _v: &Value, _r: &str, _store: &Value) -> Value {
    let (mode, parent, key, key_i) = {
        let b = inj.borrow();
        (b.mode, b.parent.clone(), b.key.clone(), b.key_i)
    };
    if mode != M_VAL {
        del_prop(parent, &Value::str(key));
        return Value::Noval;
    }
    if !is_list(&parent) || key_i != 0 {
        let path = inj.borrow().path.clone();
        errs_push(
            inj,
            format!(
                "The $EXACT validator at field {} must be the first element of an array.",
                pathify(&path_value(&path), Some(1), Some(1))
            ),
        );
        return Value::Noval;
    }
    let keylen = inj.borrow().keys.borrow().len() as i64;
    inj.borrow_mut().key_i = keylen;
    let dparent = inj.borrow().dparent.clone();
    Injection::setval(inj, dparent.clone(), Some(2));
    {
        let mut b = inj.borrow_mut();
        let n = b.path.len();
        b.path.truncate(n.saturating_sub(1));
        b.key = b.path.last().cloned().unwrap_or_default();
    }
    let path_after = inj.borrow().path.clone();
    let tvals: Vec<Value> = slice(parent.clone(), Some(1), None, false)
        .as_list()
        .map(|l| l.borrow().clone())
        .unwrap_or_default();
    if tvals.is_empty() {
        errs_push(
            inj,
            format!(
                "The $EXACT validator at field {} must have at least one argument.",
                pathify(&path_value(&path_after), Some(1), Some(1))
            ),
        );
        return Value::Noval;
    }
    let mut currentstr: Option<String> = None;
    for tval in &tvals {
        let mut exactmatch = tval == &dparent;
        if !exactmatch && is_node(tval) {
            let cs = currentstr
                .get_or_insert_with(|| stringify(&dparent, None, false))
                .clone();
            exactmatch = stringify(tval, None, false) == cs;
        }
        if exactmatch {
            return Value::Noval;
        }
    }
    let valdesc = tvals_desc(&tvals);
    let need = format!(
        "{}exactly equal to {}{}",
        if path_after.len() > 1 { "" } else { "value " },
        if tvals.len() == 1 { "" } else { "one of " },
        valdesc
    );
    errs_push(
        inj,
        invalid_type_msg(&path_after, &need, typify(&dparent), &dparent),
    );
    Value::Noval
}

/// `_validation` — the modify hook installed by `validate` (runs after the
/// per-key special commands).
fn validation_modify(pval: &Value, key: &Value, parent: &Value, inj: &Inj, _store: &Value) {
    if pval.is_skip() {
        return;
    }
    let (meta, dparent, path) = {
        let b = inj.borrow();
        (b.meta.clone(), b.dparent.clone(), b.path.clone())
    };
    let exact = matches!(
        get_prop(&meta, &Value::str(S_BEXACT), Value::Bool(false)),
        Value::Bool(true)
    );
    let cval = get_prop(&dparent, key, Value::Noval);
    if !exact && cval.is_noval() {
        return;
    }
    let ptype = typify(pval);
    if ptype & (T_STRING as i64) != 0 {
        if let Value::Str(s) = pval {
            if s.contains(S_DS) {
                return; // remaining special command — leave it
            }
        }
    }
    let ctype = typify(&cval);
    if ptype != ctype && !pval.is_noval() {
        errs_push(
            inj,
            invalid_type_msg(&path, &type_name(ptype), ctype, &cval),
        );
        return;
    }

    if is_map(&cval) {
        if !is_map(pval) {
            errs_push(
                inj,
                invalid_type_msg(&path, &type_name(ptype), ctype, &cval),
            );
            return;
        }
        let ckeys = keysof_vec(&cval);
        let pkeys = keysof_vec(pval);
        let open = matches!(
            get_prop(pval, &Value::str(S_BOPEN), Value::Noval),
            Value::Bool(true)
        );
        if !pkeys.is_empty() && !open {
            // Literal presence: the shape must be checked with a raw lookup
            // (canonical TS `NONE === _lookup(pval, ckey)`); the Group A
            // has_key would treat a null-valued shape slot as absent.
            let badkeys: Vec<String> = ckeys
                .iter()
                .filter(|ck| lookup(pval, &Value::str((*ck).clone())).is_noval())
                .cloned()
                .collect();
            if !badkeys.is_empty() {
                errs_push(
                    inj,
                    format!(
                        "Unexpected keys at field {}{}{}",
                        pathify(&path_value(&path), Some(1), None),
                        S_VIZ,
                        badkeys.join(", ")
                    ),
                );
            }
        } else {
            merge(&Value::list(vec![pval.clone(), cval.clone()]), None);
            if is_node(pval) {
                del_prop(pval.clone(), &Value::str(S_BOPEN));
            }
        }
    } else if is_list(&cval) {
        if !is_list(pval) {
            errs_push(
                inj,
                invalid_type_msg(&path, &type_name(ptype), ctype, &cval),
            );
        }
    } else if exact {
        if &cval != pval {
            let pathmsg = if path.len() > 1 {
                format!(
                    "at field {}{}",
                    pathify(&path_value(&path), Some(1), None),
                    S_VIZ
                )
            } else {
                String::new()
            };
            errs_push(
                inj,
                format!(
                    "Value {}{} should equal {}{}",
                    pathmsg,
                    js_string(&cval),
                    js_string(pval),
                    S_DT
                ),
            );
        }
    } else {
        set_prop(parent.clone(), key, cval.clone());
    }
}

/// `_validatehandler` — `getpath`/`_injectstr` handler installed by `validate`.
fn validatehandler(inj: &Inj, val: &Value, r: &str, store: &Value) -> Value {
    if let Some(caps) = R_META_PATH.captures(r) {
        if &caps[2] == "=" {
            Injection::setval(
                inj,
                Value::list(vec![Value::str(S_BEXACT), val.clone()]),
                None,
            );
        } else {
            Injection::setval(inj, val.clone(), None);
        }
        inj.borrow_mut().key_i = -1;
        return Value::skip();
    }
    inject_handler(inj, val, r, store)
}

pub fn validate(
    data: &Value,
    spec: &Value,
    injdef: Option<&InjectDef>,
) -> Result<Value, StructError> {
    let extra = injdef.and_then(|d| d.extra.clone());
    let collect = injdef.map(|d| d.errs.is_some()).unwrap_or(false);
    let errs = injdef
        .and_then(|d| d.errs.clone())
        .unwrap_or_else(Value::empty_list);

    // build the validator store
    let mut vmap: OrderedMap<Value> = OrderedMap::new();
    for k in [
        "$DELETE", "$COPY", "$KEY", "$META", "$MERGE", "$EACH", "$PACK",
    ] {
        vmap.insert(k.to_string(), Value::Null);
    }
    vmap.insert("$STRING".to_string(), Value::func(validate_string));
    for k in [
        "$NUMBER",
        "$INTEGER",
        "$DECIMAL",
        "$BOOLEAN",
        "$NULL",
        "$NIL",
        "$MAP",
        "$LIST",
        "$FUNCTION",
        "$INSTANCE",
    ] {
        vmap.insert(k.to_string(), Value::func(validate_type));
    }
    vmap.insert("$ANY".to_string(), Value::func(validate_any));
    vmap.insert("$CHILD".to_string(), Value::func(validate_child));
    vmap.insert("$ONE".to_string(), Value::func(validate_one));
    vmap.insert("$EXACT".to_string(), Value::func(validate_exact));

    let extra_or_empty = match &extra {
        Some(e) => e.clone(),
        None => Value::empty_map(),
    };
    let store = merge(
        &Value::list(vec![
            Value::map(vmap),
            extra_or_empty,
            Value::map_of([(S_DERRS.to_string(), errs.clone())]),
        ]),
        Some(1),
    );

    let meta = match injdef.and_then(|d| d.meta.clone()) {
        Some(m) => m,
        None => Value::empty_map(),
    };
    let exact_cur = get_prop(&meta, &Value::str(S_BEXACT), Value::Bool(false));
    set_prop(meta.clone(), &Value::str(S_BEXACT), exact_cur);

    let td = InjectDef {
        meta: Some(meta),
        extra: Some(store),
        modify: Some(Rc::new(validation_modify) as Modify),
        handler: Some(Rc::new(validatehandler) as NativeFn),
        errs: Some(errs.clone()),
        ..Default::default()
    };

    let out = transform(data, spec, Some(&td)).unwrap_or(Value::Noval);

    let errlen = errs.as_list().map(|l| l.borrow().len()).unwrap_or(0);
    if errlen > 0 && !collect {
        let msgs: Vec<String> = errs
            .as_list()
            .map(|l| l.borrow().iter().map(js_string).collect())
            .unwrap_or_default();
        return Err(StructError {
            message: msgs.join(" | "),
        });
    }

    Ok(out)
}

// ---- select ----------------------------------------------------------

fn js_lt(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Str(x), Value::Str(y)) => x < y,
        _ => {
            let (x, y) = (js_to_number(a), js_to_number(b));
            x < y // NaN -> false, matches JS
        }
    }
}
fn js_gt(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Str(x), Value::Str(y)) => x > y,
        _ => {
            let (x, y) = (js_to_number(a), js_to_number(b));
            x > y
        }
    }
}

fn select_subvalidate(point: &Value, term: &Value, store: &Value, meta: &Value) -> bool {
    let vstore = match merge(
        &Value::list(vec![Value::empty_map(), store.clone()]),
        Some(1),
    ) {
        v @ Value::Map(_) => v,
        _ => Value::empty_map(),
    };
    set_prop(vstore.clone(), &Value::str(S_DTOP), point.clone());
    let terrs = Value::empty_list();
    let vd = InjectDef {
        extra: Some(vstore),
        errs: Some(terrs.clone()),
        meta: Some(meta.clone()),
        ..Default::default()
    };
    let _ = validate(point, term, Some(&vd));
    terrs
        .as_list()
        .map(|l| l.borrow().is_empty())
        .unwrap_or(true)
}

fn select_and(inj: &Inj, _v: &Value, _r: &str, store: &Value) -> Value {
    if inj.borrow().mode != M_KEYPRE {
        return Value::Noval;
    }
    let (key, parent, path, nodes, meta) = {
        let b = inj.borrow();
        (
            b.key.clone(),
            b.parent.clone(),
            b.path.clone(),
            b.nodes.clone(),
            b.meta.clone(),
        )
    };
    let terms: Vec<Value> = lookup(&parent, &Value::str(key))
        .as_list()
        .map(|l| l.borrow().clone())
        .unwrap_or_default();
    let ppath = slice_str_vec(&path, Some(-1), None);
    let point = get_path_inj(store, &path_value(&ppath), None);
    for term in &terms {
        if !select_subvalidate(&point, term, store, &meta) {
            errs_push(
                inj,
                format!(
                    "AND:{}{}{} fail:{}",
                    pathify(&path_value(&ppath), None, None),
                    S_VIZ,
                    stringify(&point, None, false),
                    stringify(&Value::list(terms.clone()), None, false)
                ),
            );
        }
    }
    let gkey = path
        .get(path.len().saturating_sub(2))
        .cloned()
        .unwrap_or_default();
    let nlen = nodes.len();
    if nlen >= 2 {
        set_prop(nodes[nlen - 2].clone(), &Value::str(gkey), point);
    }
    Value::Noval
}

fn select_or(inj: &Inj, _v: &Value, _r: &str, store: &Value) -> Value {
    if inj.borrow().mode != M_KEYPRE {
        return Value::Noval;
    }
    let (key, parent, path, nodes, meta) = {
        let b = inj.borrow();
        (
            b.key.clone(),
            b.parent.clone(),
            b.path.clone(),
            b.nodes.clone(),
            b.meta.clone(),
        )
    };
    let terms: Vec<Value> = lookup(&parent, &Value::str(key))
        .as_list()
        .map(|l| l.borrow().clone())
        .unwrap_or_default();
    let ppath = slice_str_vec(&path, Some(-1), None);
    let point = get_path_inj(store, &path_value(&ppath), None);
    for term in &terms {
        if select_subvalidate(&point, term, store, &meta) {
            let gkey = path
                .get(path.len().saturating_sub(2))
                .cloned()
                .unwrap_or_default();
            let nlen = nodes.len();
            if nlen >= 2 {
                set_prop(nodes[nlen - 2].clone(), &Value::str(gkey), point);
            }
            return Value::Noval;
        }
    }
    errs_push(
        inj,
        format!(
            "OR:{}{}{} fail:{}",
            pathify(&path_value(&ppath), None, None),
            S_VIZ,
            stringify(&point, None, false),
            stringify(&Value::list(terms.clone()), None, false)
        ),
    );
    Value::Noval
}

fn select_not(inj: &Inj, _v: &Value, _r: &str, store: &Value) -> Value {
    if inj.borrow().mode != M_KEYPRE {
        return Value::Noval;
    }
    let (key, parent, path, nodes, meta) = {
        let b = inj.borrow();
        (
            b.key.clone(),
            b.parent.clone(),
            b.path.clone(),
            b.nodes.clone(),
            b.meta.clone(),
        )
    };
    let term = lookup(&parent, &Value::str(key));
    let ppath = slice_str_vec(&path, Some(-1), None);
    let point = get_path_inj(store, &path_value(&ppath), None);
    if select_subvalidate(&point, &term, store, &meta) {
        errs_push(
            inj,
            format!(
                "NOT:{}{}{} fail:{}",
                pathify(&path_value(&ppath), None, None),
                S_VIZ,
                stringify(&point, None, false),
                stringify(&term, None, false)
            ),
        );
    }
    let gkey = path
        .get(path.len().saturating_sub(2))
        .cloned()
        .unwrap_or_default();
    let nlen = nodes.len();
    if nlen >= 2 {
        set_prop(nodes[nlen - 2].clone(), &Value::str(gkey), point);
    }
    Value::Noval
}

fn select_cmp(inj: &Inj, _v: &Value, r: &str, store: &Value) -> Value {
    if inj.borrow().mode != M_KEYPRE {
        return Value::Noval;
    }
    let (key, parent, path, nodes) = {
        let b = inj.borrow();
        (
            b.key.clone(),
            b.parent.clone(),
            b.path.clone(),
            b.nodes.clone(),
        )
    };
    let term = lookup(&parent, &Value::str(key));
    let gkey = path
        .get(path.len().saturating_sub(2))
        .cloned()
        .unwrap_or_default();
    let ppath = slice_str_vec(&path, Some(-1), None);
    let point = get_path_inj(store, &path_value(&ppath), None);

    let pass = match r {
        "$GT" => js_gt(&point, &term),
        "$LT" => js_lt(&point, &term),
        "$GTE" => js_gt(&point, &term) || point == term,
        "$LTE" => js_lt(&point, &term) || point == term,
        "$LIKE" => {
            let pat = term.as_str().unwrap_or("").to_string();
            crate::re::Regex::new(&pat)
                .map(|re| re.is_match(&stringify(&point, None, false)))
                .unwrap_or(false)
        }
        _ => false,
    };

    if pass {
        let nlen = nodes.len();
        if nlen >= 2 {
            set_prop(nodes[nlen - 2].clone(), &Value::str(gkey), point);
        }
    } else {
        errs_push(
            inj,
            format!(
                "CMP: {}{}{} fail:{} {}",
                pathify(&path_value(&ppath), None, None),
                S_VIZ,
                stringify(&point, None, false),
                r,
                stringify(&term, None, false)
            ),
        );
    }
    Value::Noval
}

pub fn select(children: &Value, query: &Value) -> Value {
    if !is_node(children) {
        return Value::empty_list();
    }

    let child_list: Vec<Value> = match children {
        Value::Map(_) => items_vec(children)
            .into_iter()
            .map(|(k, v)| {
                set_prop(v.clone(), &Value::str(S_DKEY), Value::str(k));
                v
            })
            .collect(),
        Value::List(_) => items_vec(children)
            .into_iter()
            .map(|(k, v)| {
                set_prop(
                    v.clone(),
                    &Value::str(S_DKEY),
                    Value::Num(k.parse::<f64>().unwrap_or(f64::NAN)),
                );
                v
            })
            .collect(),
        _ => return Value::empty_list(),
    };

    let extra = Value::map_of([
        ("$AND".to_string(), Value::func(select_and)),
        ("$OR".to_string(), Value::func(select_or)),
        ("$NOT".to_string(), Value::func(select_not)),
        ("$GT".to_string(), Value::func(select_cmp)),
        ("$LT".to_string(), Value::func(select_cmp)),
        ("$GTE".to_string(), Value::func(select_cmp)),
        ("$LTE".to_string(), Value::func(select_cmp)),
        ("$LIKE".to_string(), Value::func(select_cmp)),
    ]);
    let meta = Value::map_of([(S_BEXACT.to_string(), Value::Bool(true))]);

    let q = clone(query);
    let mut open = |_k: &Value, v: &Value, _p: &Value, _t: &[String]| -> Value {
        if is_map(v) {
            let cur = get_prop(v, &Value::str(S_BOPEN), Value::Bool(true));
            set_prop(v.clone(), &Value::str(S_BOPEN), cur);
        }
        v.clone()
    };
    walk(q.clone(), Some(&mut open), None, None);

    let mut results: Vec<Value> = Vec::new();
    for child in &child_list {
        let errs = Value::empty_list();
        let vd = InjectDef {
            errs: Some(errs.clone()),
            meta: Some(meta.clone()),
            extra: Some(extra.clone()),
            ..Default::default()
        };
        let _ = validate(child, &clone(&q), Some(&vd));
        if errs
            .as_list()
            .map(|l| l.borrow().is_empty())
            .unwrap_or(true)
        {
            results.push(child.clone());
        }
    }
    Value::list(results)
}

// keep `Injection::has_handler` referenced (used once staging is complete)
#[allow(dead_code)]
fn _keepalive() {
    let _ = Injection::has_handler(None);
    let _ = inject_child as fn(Value, &Value, &Inj) -> Inj;
}