fallow-core 2.40.2

Core analysis engine for the fallow TypeScript/JavaScript codebase analyzer
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
//! AST-based config file parser utilities.
//!
//! Provides helpers to extract configuration values from JS/TS config files
//! without evaluating them. Uses Oxc's parser for fast, safe AST walking.
//!
//! Common patterns handled:
//! - `export default { key: "value" }` (default export object)
//! - `export default defineConfig({ key: "value" })` (factory function)
//! - `module.exports = { key: "value" }` (CJS)
//! - Import specifiers (`import x from 'pkg'`)
//! - Array literals (`["a", "b"]`)
//! - Object properties (`{ key: "value" }`)

use std::path::{Path, PathBuf};

use oxc_allocator::Allocator;
#[allow(clippy::wildcard_imports, reason = "many AST types used")]
use oxc_ast::ast::*;
use oxc_parser::Parser;
use oxc_span::SourceType;

/// Extract all import source specifiers from JS/TS source code.
#[must_use]
pub fn extract_imports(source: &str, path: &Path) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let mut sources = Vec::new();
        for stmt in &program.body {
            if let Statement::ImportDeclaration(decl) = stmt {
                sources.push(decl.source.value.to_string());
            }
        }
        Some(sources)
    })
    .unwrap_or_default()
}

/// Extract all import sources AND top-level `require('...')` expression statements.
///
/// Handles configs that load plugins via side-effect requires:
/// ```js
/// require("@nomiclabs/hardhat-waffle");
/// import "@nomicfoundation/hardhat-toolbox";
/// ```
#[must_use]
pub fn extract_imports_and_requires(source: &str, path: &Path) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let mut sources = Vec::new();
        for stmt in &program.body {
            match stmt {
                Statement::ImportDeclaration(decl) => {
                    sources.push(decl.source.value.to_string());
                }
                Statement::ExpressionStatement(expr) => {
                    if let Expression::CallExpression(call) = &expr.expression
                        && is_require_call(call)
                        && let Some(s) = get_require_source(call)
                    {
                        sources.push(s);
                    }
                }
                _ => {}
            }
        }
        Some(sources)
    })
    .unwrap_or_default()
}

/// Extract string array from a property at a nested path in a config's default export.
#[must_use]
pub fn extract_config_string_array(source: &str, path: &Path, prop_path: &[&str]) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        get_nested_string_array_from_object(obj, prop_path)
    })
    .unwrap_or_default()
}

/// Extract a single string from a property at a nested path.
#[must_use]
pub fn extract_config_string(source: &str, path: &Path, prop_path: &[&str]) -> Option<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        get_nested_string_from_object(obj, prop_path)
    })
}

/// Extract string values from top-level properties of the default export/module.exports object.
/// Returns all string literal values found for the given property key, recursively.
///
/// **Warning**: This recurses into nested objects/arrays. For config arrays that contain
/// tuples like `["pkg-name", { options }]`, use [`extract_config_shallow_strings`] instead
/// to avoid extracting option values as package names.
#[must_use]
pub fn extract_config_property_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let mut values = Vec::new();
        if let Some(prop) = find_property(obj, key) {
            collect_all_string_values(&prop.value, &mut values);
        }
        Some(values)
    })
    .unwrap_or_default()
}

/// Extract only top-level string values from a property's array.
///
/// Unlike [`extract_config_property_strings`], this does NOT recurse into nested
/// objects or sub-arrays. Useful for config arrays with tuple elements like:
/// `reporters: ["default", ["jest-junit", { outputDirectory: "reports" }]]`
/// — only `"default"` and `"jest-junit"` are returned, not `"reports"`.
#[must_use]
pub fn extract_config_shallow_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let prop = find_property(obj, key)?;
        Some(collect_shallow_string_values(&prop.value))
    })
    .unwrap_or_default()
}

/// Extract shallow strings from an array property inside a nested object path.
///
/// Navigates `outer_path` to find a nested object, then extracts shallow strings
/// from the `key` property. Useful for configs like Vitest where reporters are at
/// `test.reporters`: `{ test: { reporters: ["default", ["vitest-sonar-reporter", {...}]] } }`.
#[must_use]
pub fn extract_config_nested_shallow_strings(
    source: &str,
    path: &Path,
    outer_path: &[&str],
    key: &str,
) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let nested = get_nested_expression(obj, outer_path)?;
        if let Expression::ObjectExpression(nested_obj) = nested {
            let prop = find_property(nested_obj, key)?;
            Some(collect_shallow_string_values(&prop.value))
        } else {
            None
        }
    })
    .unwrap_or_default()
}

/// Public wrapper for `find_config_object` for plugins that need manual AST walking.
pub fn find_config_object_pub<'a>(program: &'a Program) -> Option<&'a ObjectExpression<'a>> {
    find_config_object(program)
}

/// Get a top-level property expression from an object.
pub(crate) fn property_expr<'a>(
    obj: &'a ObjectExpression<'a>,
    key: &str,
) -> Option<&'a Expression<'a>> {
    find_property(obj, key).map(|prop| &prop.value)
}

/// Get a top-level property object from an object.
pub(crate) fn property_object<'a>(
    obj: &'a ObjectExpression<'a>,
    key: &str,
) -> Option<&'a ObjectExpression<'a>> {
    property_expr(obj, key).and_then(object_expression)
}

/// Get a string-like top-level property value from an object.
pub(crate) fn property_string(obj: &ObjectExpression<'_>, key: &str) -> Option<String> {
    property_expr(obj, key).and_then(expression_to_string)
}

/// Convert an expression to an object expression when it is statically recoverable.
pub(crate) fn object_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ObjectExpression<'a>> {
    match expr {
        Expression::ObjectExpression(obj) => Some(obj),
        Expression::ParenthesizedExpression(paren) => object_expression(&paren.expression),
        Expression::TSSatisfiesExpression(ts_sat) => object_expression(&ts_sat.expression),
        Expression::TSAsExpression(ts_as) => object_expression(&ts_as.expression),
        _ => None,
    }
}

/// Convert an expression to an array expression when it is statically recoverable.
pub(crate) fn array_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ArrayExpression<'a>> {
    match expr {
        Expression::ArrayExpression(arr) => Some(arr),
        Expression::ParenthesizedExpression(paren) => array_expression(&paren.expression),
        Expression::TSSatisfiesExpression(ts_sat) => array_expression(&ts_sat.expression),
        Expression::TSAsExpression(ts_as) => array_expression(&ts_as.expression),
        _ => None,
    }
}

/// Convert a path-like expression to zero or more statically recoverable path strings.
pub(crate) fn expression_to_path_values(expr: &Expression<'_>) -> Vec<String> {
    match expr {
        Expression::ArrayExpression(arr) => arr
            .elements
            .iter()
            .filter_map(|element| element.as_expression().and_then(expression_to_path_string))
            .collect(),
        _ => expression_to_path_string(expr).into_iter().collect(),
    }
}

/// True when an expression explicitly disables a config section.
pub(crate) fn is_disabled_expression(expr: &Expression<'_>) -> bool {
    matches!(expr, Expression::BooleanLiteral(boolean) if !boolean.value)
        || matches!(expr, Expression::NullLiteral(_))
}

/// Extract keys of an object property at a nested path.
///
/// Useful for `PostCSS` config: `{ plugins: { autoprefixer: {}, tailwindcss: {} } }`
/// → returns `["autoprefixer", "tailwindcss"]`.
#[must_use]
pub fn extract_config_object_keys(source: &str, path: &Path, prop_path: &[&str]) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        get_nested_object_keys(obj, prop_path)
    })
    .unwrap_or_default()
}

/// Extract a value that may be a single string, a string array, or an object with string values.
///
/// Useful for Webpack `entry`, Rollup `input`, etc. that accept multiple formats:
/// - `entry: "./src/index.js"` → `["./src/index.js"]`
/// - `entry: ["./src/a.js", "./src/b.js"]` → `["./src/a.js", "./src/b.js"]`
/// - `entry: { main: "./src/main.js" }` → `["./src/main.js"]`
#[must_use]
pub fn extract_config_string_or_array(
    source: &str,
    path: &Path,
    prop_path: &[&str],
) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        get_nested_string_or_array(obj, prop_path)
    })
    .unwrap_or_default()
}

/// Extract string values from a property path, also searching inside array elements.
///
/// Navigates `array_path` to find an array expression, then for each object in the
/// array, navigates `inner_path` to extract string values. Useful for configs like
/// Vitest projects where values are nested in array elements:
/// - `test.projects[*].test.setupFiles`
#[must_use]
pub fn extract_config_array_nested_string_or_array(
    source: &str,
    path: &Path,
    array_path: &[&str],
    inner_path: &[&str],
) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let array_expr = get_nested_expression(obj, array_path)?;
        let Expression::ArrayExpression(arr) = array_expr else {
            return None;
        };
        let mut results = Vec::new();
        for element in &arr.elements {
            if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
                && let Some(values) = get_nested_string_or_array(element_obj, inner_path)
            {
                results.extend(values);
            }
        }
        if results.is_empty() {
            None
        } else {
            Some(results)
        }
    })
    .unwrap_or_default()
}

/// Extract string values from a property path, searching inside all values of an object.
///
/// Navigates `object_path` to find an object expression, then for each property value
/// (regardless of key name), navigates `inner_path` to extract string values. Useful for
/// configs with dynamic keys like `angular.json`:
/// - `projects.*.architect.build.options.styles`
#[must_use]
pub fn extract_config_object_nested_string_or_array(
    source: &str,
    path: &Path,
    object_path: &[&str],
    inner_path: &[&str],
) -> Vec<String> {
    extract_config_object_nested(source, path, object_path, |value_obj| {
        get_nested_string_or_array(value_obj, inner_path)
    })
}

/// Extract string values from a property path, searching inside all values of an object.
///
/// Like [`extract_config_object_nested_string_or_array`] but returns a single optional string
/// per object value (useful for fields like `architect.build.options.main`).
#[must_use]
pub fn extract_config_object_nested_strings(
    source: &str,
    path: &Path,
    object_path: &[&str],
    inner_path: &[&str],
) -> Vec<String> {
    extract_config_object_nested(source, path, object_path, |value_obj| {
        get_nested_string_from_object(value_obj, inner_path).map(|s| vec![s])
    })
}

/// Shared helper for object-nested extraction.
///
/// Navigates `object_path` to find an object expression, then for each property value
/// that is itself an object, calls `extract_fn` to produce string values.
fn extract_config_object_nested(
    source: &str,
    path: &Path,
    object_path: &[&str],
    extract_fn: impl Fn(&ObjectExpression<'_>) -> Option<Vec<String>>,
) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let obj_expr = get_nested_expression(obj, object_path)?;
        let Expression::ObjectExpression(target_obj) = obj_expr else {
            return None;
        };
        let mut results = Vec::new();
        for prop in &target_obj.properties {
            if let ObjectPropertyKind::ObjectProperty(p) = prop
                && let Expression::ObjectExpression(value_obj) = &p.value
                && let Some(values) = extract_fn(value_obj)
            {
                results.extend(values);
            }
        }
        if results.is_empty() {
            None
        } else {
            Some(results)
        }
    })
    .unwrap_or_default()
}

/// Extract `require('...')` call argument strings from a property's value.
///
/// Handles direct require calls and arrays containing require calls or tuples:
/// - `plugins: [require('autoprefixer')]`
/// - `plugins: [require('postcss-import'), [require('postcss-preset-env'), { ... }]]`
#[must_use]
pub fn extract_config_require_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let prop = find_property(obj, key)?;
        Some(collect_require_sources(&prop.value))
    })
    .unwrap_or_default()
}

/// Extract alias mappings from an object or array-based alias config.
///
/// Supports common bundler config shapes like:
/// - `resolve.alias = { "@": "./src" }`
/// - `resolve.alias = [{ find: "@", replacement: "./src" }]`
/// - `resolve.alias = [{ find: "@", replacement: fileURLToPath(new URL("./src", import.meta.url)) }]`
#[must_use]
pub fn extract_config_aliases(
    source: &str,
    path: &Path,
    prop_path: &[&str],
) -> Vec<(String, String)> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let expr = get_nested_expression(obj, prop_path)?;
        let aliases = expression_to_alias_pairs(expr);
        (!aliases.is_empty()).then_some(aliases)
    })
    .unwrap_or_default()
}

/// Extract string values from a nested array, supporting both string elements and
/// object elements with a named string/path field.
///
/// Useful for configs like:
/// - `components: ["~/components", { path: "~/feature-components" }]`
#[must_use]
pub fn extract_config_array_object_strings(
    source: &str,
    path: &Path,
    array_path: &[&str],
    key: &str,
) -> Vec<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let array_expr = get_nested_expression(obj, array_path)?;
        let Expression::ArrayExpression(arr) = array_expr else {
            return None;
        };

        let mut results = Vec::new();
        for element in &arr.elements {
            let Some(expr) = element.as_expression() else {
                continue;
            };
            match expr {
                Expression::ObjectExpression(item) => {
                    if let Some(prop) = find_property(item, key)
                        && let Some(value) = expression_to_path_string(&prop.value)
                    {
                        results.push(value);
                    }
                }
                _ => {
                    if let Some(value) = expression_to_path_string(expr) {
                        results.push(value);
                    }
                }
            }
        }

        (!results.is_empty()).then_some(results)
    })
    .unwrap_or_default()
}

/// Extract a string-like option from a plugin tuple inside a config plugin array.
///
/// Supports config shapes like:
/// - `{ expo: { plugins: [["expo-router", { root: "src/app" }]] } }`
/// - `export default { expo: { plugins: [["expo-router", { root: "./src/app" }]] } }`
/// - `{ plugins: [["expo-router", { root: "./src/routes" }]] }`
#[must_use]
pub fn extract_config_plugin_option_string(
    source: &str,
    path: &Path,
    plugins_path: &[&str],
    plugin_name: &str,
    option_key: &str,
) -> Option<String> {
    extract_from_source(source, path, |program| {
        let obj = find_config_object(program)?;
        let plugins_expr = get_nested_expression(obj, plugins_path)?;
        let Expression::ArrayExpression(plugins) = plugins_expr else {
            return None;
        };

        for entry in &plugins.elements {
            let Some(Expression::ArrayExpression(tuple)) = entry.as_expression() else {
                continue;
            };
            let Some(plugin_expr) = tuple
                .elements
                .first()
                .and_then(ArrayExpressionElement::as_expression)
            else {
                continue;
            };
            if expression_to_string(plugin_expr).as_deref() != Some(plugin_name) {
                continue;
            }

            let Some(options_expr) = tuple
                .elements
                .get(1)
                .and_then(ArrayExpressionElement::as_expression)
            else {
                continue;
            };
            let Expression::ObjectExpression(options_obj) = options_expr else {
                continue;
            };
            let option = find_property(options_obj, option_key)?;
            return expression_to_path_string(&option.value);
        }

        None
    })
}

/// Extract a string-like option from the first plugin array path that contains it.
#[must_use]
pub fn extract_config_plugin_option_string_from_paths(
    source: &str,
    path: &Path,
    plugin_paths: &[&[&str]],
    plugin_name: &str,
    option_key: &str,
) -> Option<String> {
    plugin_paths.iter().find_map(|plugins_path| {
        extract_config_plugin_option_string(source, path, plugins_path, plugin_name, option_key)
    })
}

/// Normalize a config-relative path string to a project-root-relative path.
///
/// Handles values extracted from config files such as `"./src"`, `"src/lib"`,
/// `"/src"`, or absolute filesystem paths under `root`.
#[must_use]
pub fn normalize_config_path(raw: &str, config_path: &Path, root: &Path) -> Option<String> {
    if raw.is_empty() {
        return None;
    }

    let candidate = if let Some(stripped) = raw.strip_prefix('/') {
        lexical_normalize(&root.join(stripped))
    } else {
        let path = Path::new(raw);
        if path.is_absolute() {
            lexical_normalize(path)
        } else {
            let base = config_path.parent().unwrap_or(root);
            lexical_normalize(&base.join(path))
        }
    };

    let relative = candidate.strip_prefix(root).ok()?;
    let normalized = relative.to_string_lossy().replace('\\', "/");
    (!normalized.is_empty()).then_some(normalized)
}

// ── Internal helpers ──────────────────────────────────────────────

/// Parse source and run an extraction function on the AST.
///
/// JSON files (`.json`, `.jsonc`) are parsed as JavaScript expressions wrapped in
/// parentheses to produce an AST compatible with `find_config_object`. The native
/// JSON source type in Oxc produces a different AST structure that our helpers
/// don't handle.
fn extract_from_source<T>(
    source: &str,
    path: &Path,
    extractor: impl FnOnce(&Program) -> Option<T>,
) -> Option<T> {
    let source_type = SourceType::from_path(path).unwrap_or_default();
    let alloc = Allocator::default();

    // For JSON files, wrap in parens and parse as JS so the AST matches
    // what find_config_object expects (ExpressionStatement → ObjectExpression).
    let is_json = path
        .extension()
        .is_some_and(|ext| ext == "json" || ext == "jsonc");
    if is_json {
        let wrapped = format!("({source})");
        let parsed = Parser::new(&alloc, &wrapped, SourceType::mjs()).parse();
        return extractor(&parsed.program);
    }

    let parsed = Parser::new(&alloc, source, source_type).parse();
    extractor(&parsed.program)
}

/// Find the "config object" — the object expression in the default export or module.exports.
///
/// Handles these patterns:
/// - `export default { ... }`
/// - `export default defineConfig({ ... })`
/// - `export default defineConfig(async () => ({ ... }))`
/// - `export default { ... } satisfies Config` / `export default { ... } as Config`
/// - `const config = { ... }; export default config;`
/// - `const config: Config = { ... }; export default config;`
/// - `module.exports = { ... }`
/// - Top-level JSON object (for .json files)
fn find_config_object<'a>(program: &'a Program) -> Option<&'a ObjectExpression<'a>> {
    for stmt in &program.body {
        match stmt {
            // export default { ... } or export default defineConfig({ ... })
            Statement::ExportDefaultDeclaration(decl) => {
                // ExportDefaultDeclarationKind inherits Expression variants directly
                let expr: Option<&Expression> = match &decl.declaration {
                    ExportDefaultDeclarationKind::ObjectExpression(obj) => {
                        return Some(obj);
                    }
                    ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
                        return extract_object_from_function(func);
                    }
                    _ => decl.declaration.as_expression(),
                };
                if let Some(expr) = expr {
                    // Try direct extraction (handles defineConfig(), parens, TS annotations)
                    if let Some(obj) = extract_object_from_expression(expr) {
                        return Some(obj);
                    }
                    // Fallback: resolve identifier reference to variable declaration
                    // Handles: const config: Type = { ... }; export default config;
                    if let Some(name) = unwrap_to_identifier_name(expr) {
                        return find_variable_init_object(program, name);
                    }
                }
            }
            // module.exports = { ... }
            Statement::ExpressionStatement(expr_stmt) => {
                if let Expression::AssignmentExpression(assign) = &expr_stmt.expression
                    && is_module_exports_target(&assign.left)
                {
                    return extract_object_from_expression(&assign.right);
                }
            }
            _ => {}
        }
    }

    // JSON files: the program body might be a single expression statement
    // Also handles JSON wrapped in parens: `({ ... })` (used for tsconfig.json parsing)
    if program.body.len() == 1
        && let Statement::ExpressionStatement(expr_stmt) = &program.body[0]
    {
        match &expr_stmt.expression {
            Expression::ObjectExpression(obj) => return Some(obj),
            Expression::ParenthesizedExpression(paren) => {
                if let Expression::ObjectExpression(obj) = &paren.expression {
                    return Some(obj);
                }
            }
            _ => {}
        }
    }

    None
}

/// Extract an `ObjectExpression` from an expression, handling wrapper patterns.
fn extract_object_from_expression<'a>(
    expr: &'a Expression<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    match expr {
        // Direct object: `{ ... }`
        Expression::ObjectExpression(obj) => Some(obj),
        // Factory call: `defineConfig({ ... })`
        Expression::CallExpression(call) => {
            // Look for the first object argument
            for arg in &call.arguments {
                match arg {
                    Argument::ObjectExpression(obj) => return Some(obj),
                    // Arrow function body: `defineConfig(() => ({ ... }))`
                    Argument::ArrowFunctionExpression(arrow) => {
                        if arrow.expression
                            && !arrow.body.statements.is_empty()
                            && let Statement::ExpressionStatement(expr_stmt) =
                                &arrow.body.statements[0]
                        {
                            return extract_object_from_expression(&expr_stmt.expression);
                        }
                    }
                    _ => {}
                }
            }
            None
        }
        // Parenthesized: `({ ... })`
        Expression::ParenthesizedExpression(paren) => {
            extract_object_from_expression(&paren.expression)
        }
        // TS type annotations: `{ ... } satisfies Config` or `{ ... } as Config`
        Expression::TSSatisfiesExpression(ts_sat) => {
            extract_object_from_expression(&ts_sat.expression)
        }
        Expression::TSAsExpression(ts_as) => extract_object_from_expression(&ts_as.expression),
        Expression::ArrowFunctionExpression(arrow) => extract_object_from_arrow_function(arrow),
        Expression::FunctionExpression(func) => extract_object_from_function(func),
        _ => None,
    }
}

fn extract_object_from_arrow_function<'a>(
    arrow: &'a ArrowFunctionExpression<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    if arrow.expression {
        arrow.body.statements.first().and_then(|stmt| {
            if let Statement::ExpressionStatement(expr_stmt) = stmt {
                extract_object_from_expression(&expr_stmt.expression)
            } else {
                None
            }
        })
    } else {
        extract_object_from_function_body(&arrow.body)
    }
}

fn extract_object_from_function<'a>(func: &'a Function<'a>) -> Option<&'a ObjectExpression<'a>> {
    func.body
        .as_ref()
        .and_then(|body| extract_object_from_function_body(body))
}

fn extract_object_from_function_body<'a>(
    body: &'a FunctionBody<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    for stmt in &body.statements {
        if let Statement::ReturnStatement(ret) = stmt
            && let Some(argument) = &ret.argument
            && let Some(obj) = extract_object_from_expression(argument)
        {
            return Some(obj);
        }
    }
    None
}

/// Check if an assignment target is `module.exports`.
fn is_module_exports_target(target: &AssignmentTarget) -> bool {
    if let AssignmentTarget::StaticMemberExpression(member) = target
        && let Expression::Identifier(obj) = &member.object
    {
        return obj.name == "module" && member.property.name == "exports";
    }
    false
}

/// Unwrap TS annotations and return the identifier name if the expression resolves to one.
///
/// Handles `config`, `config satisfies Type`, `config as Type`.
fn unwrap_to_identifier_name<'a>(expr: &'a Expression<'a>) -> Option<&'a str> {
    match expr {
        Expression::Identifier(id) => Some(&id.name),
        Expression::TSSatisfiesExpression(ts_sat) => unwrap_to_identifier_name(&ts_sat.expression),
        Expression::TSAsExpression(ts_as) => unwrap_to_identifier_name(&ts_as.expression),
        _ => None,
    }
}

/// Find a top-level variable declaration by name and extract its init as an object expression.
///
/// Handles `const config = { ... }`, `const config: Type = { ... }`,
/// and `const config = defineConfig({ ... })`.
fn find_variable_init_object<'a>(
    program: &'a Program,
    name: &str,
) -> Option<&'a ObjectExpression<'a>> {
    for stmt in &program.body {
        if let Statement::VariableDeclaration(decl) = stmt {
            for declarator in &decl.declarations {
                if let BindingPattern::BindingIdentifier(id) = &declarator.id
                    && id.name == name
                    && let Some(init) = &declarator.init
                {
                    return extract_object_from_expression(init);
                }
            }
        }
    }
    None
}

/// Find a named property in an object expression.
pub(crate) fn find_property<'a>(
    obj: &'a ObjectExpression<'a>,
    key: &str,
) -> Option<&'a ObjectProperty<'a>> {
    for prop in &obj.properties {
        if let ObjectPropertyKind::ObjectProperty(p) = prop
            && property_key_matches(&p.key, key)
        {
            return Some(p);
        }
    }
    None
}

/// Check if a property key matches a string.
pub(crate) fn property_key_matches(key: &PropertyKey, name: &str) -> bool {
    match key {
        PropertyKey::StaticIdentifier(id) => id.name == name,
        PropertyKey::StringLiteral(s) => s.value == name,
        _ => false,
    }
}

/// Get a string value from an object property.
fn get_object_string_property(obj: &ObjectExpression, key: &str) -> Option<String> {
    find_property(obj, key).and_then(|p| expression_to_string(&p.value))
}

/// Get an array of strings from an object property.
fn get_object_string_array_property(obj: &ObjectExpression, key: &str) -> Vec<String> {
    find_property(obj, key)
        .map(|p| expression_to_string_array(&p.value))
        .unwrap_or_default()
}

/// Navigate a nested property path and get a string array.
fn get_nested_string_array_from_object(
    obj: &ObjectExpression,
    path: &[&str],
) -> Option<Vec<String>> {
    if path.is_empty() {
        return None;
    }
    if path.len() == 1 {
        return Some(get_object_string_array_property(obj, path[0]));
    }
    // Navigate into nested object
    let prop = find_property(obj, path[0])?;
    if let Expression::ObjectExpression(nested) = &prop.value {
        get_nested_string_array_from_object(nested, &path[1..])
    } else {
        None
    }
}

/// Navigate a nested property path and get a string value.
fn get_nested_string_from_object(obj: &ObjectExpression, path: &[&str]) -> Option<String> {
    if path.is_empty() {
        return None;
    }
    if path.len() == 1 {
        return get_object_string_property(obj, path[0]);
    }
    let prop = find_property(obj, path[0])?;
    if let Expression::ObjectExpression(nested) = &prop.value {
        get_nested_string_from_object(nested, &path[1..])
    } else {
        None
    }
}

/// Convert an expression to a string if it's a string literal.
pub(crate) fn expression_to_string(expr: &Expression) -> Option<String> {
    match expr {
        Expression::StringLiteral(s) => Some(s.value.to_string()),
        Expression::TemplateLiteral(t) if t.expressions.is_empty() => {
            // Template literal with no expressions: `\`value\``
            t.quasis.first().map(|q| q.value.raw.to_string())
        }
        _ => None,
    }
}

/// Convert an expression to a path-like string if it's statically recoverable.
pub(crate) fn expression_to_path_string(expr: &Expression) -> Option<String> {
    match expr {
        Expression::ParenthesizedExpression(paren) => expression_to_path_string(&paren.expression),
        Expression::TSAsExpression(ts_as) => expression_to_path_string(&ts_as.expression),
        Expression::TSSatisfiesExpression(ts_sat) => expression_to_path_string(&ts_sat.expression),
        Expression::CallExpression(call) => call_expression_to_path_string(call),
        Expression::NewExpression(new_expr) => new_expression_to_path_string(new_expr),
        _ => expression_to_string(expr),
    }
}

fn call_expression_to_path_string(call: &CallExpression) -> Option<String> {
    if matches!(&call.callee, Expression::Identifier(id) if id.name == "fileURLToPath") {
        return call
            .arguments
            .first()
            .and_then(Argument::as_expression)
            .and_then(expression_to_path_string);
    }

    let callee_name = match &call.callee {
        Expression::Identifier(id) => Some(id.name.as_str()),
        Expression::StaticMemberExpression(member) => Some(member.property.name.as_str()),
        _ => None,
    }?;

    if !matches!(callee_name, "resolve" | "join") {
        return None;
    }

    let mut segments = Vec::new();
    for (index, arg) in call.arguments.iter().enumerate() {
        let expr = arg.as_expression()?;

        if matches!(expr, Expression::Identifier(id) if id.name == "__dirname") {
            if index == 0 {
                continue;
            }
            return None;
        }

        segments.push(expression_to_string(expr)?);
    }

    (!segments.is_empty()).then(|| join_path_segments(&segments))
}

fn new_expression_to_path_string(new_expr: &NewExpression) -> Option<String> {
    if !matches!(&new_expr.callee, Expression::Identifier(id) if id.name == "URL") {
        return None;
    }

    let source = new_expr
        .arguments
        .first()
        .and_then(Argument::as_expression)
        .and_then(expression_to_string)?;

    let base = new_expr
        .arguments
        .get(1)
        .and_then(Argument::as_expression)?;
    is_import_meta_url_expression(base).then_some(source)
}

fn is_import_meta_url_expression(expr: &Expression) -> bool {
    if let Expression::StaticMemberExpression(member) = expr {
        member.property.name == "url" && matches!(member.object, Expression::MetaProperty(_))
    } else {
        false
    }
}

fn join_path_segments(segments: &[String]) -> String {
    let mut joined = PathBuf::new();
    for segment in segments {
        joined.push(segment);
    }
    joined.to_string_lossy().replace('\\', "/")
}

fn expression_to_alias_pairs(expr: &Expression) -> Vec<(String, String)> {
    match expr {
        Expression::ObjectExpression(obj) => obj
            .properties
            .iter()
            .filter_map(|prop| {
                let ObjectPropertyKind::ObjectProperty(prop) = prop else {
                    return None;
                };
                let find = property_key_to_string(&prop.key)?;
                let replacement = expression_to_path_string(&prop.value)?;
                Some((find, replacement))
            })
            .collect(),
        Expression::ArrayExpression(arr) => arr
            .elements
            .iter()
            .filter_map(|element| {
                let Expression::ObjectExpression(obj) = element.as_expression()? else {
                    return None;
                };
                let find = find_property(obj, "find")
                    .and_then(|prop| expression_to_string(&prop.value))?;
                let replacement = find_property(obj, "replacement")
                    .and_then(|prop| expression_to_path_string(&prop.value))?;
                Some((find, replacement))
            })
            .collect(),
        _ => Vec::new(),
    }
}

fn lexical_normalize(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();

    for component in path.components() {
        match component {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                normalized.pop();
            }
            _ => normalized.push(component.as_os_str()),
        }
    }

    normalized
}

/// Convert an expression to a string array if it's an array of string literals.
fn expression_to_string_array(expr: &Expression) -> Vec<String> {
    match expr {
        Expression::ArrayExpression(arr) => arr
            .elements
            .iter()
            .filter_map(|el| match el {
                ArrayExpressionElement::SpreadElement(_) => None,
                _ => el.as_expression().and_then(expression_to_string),
            })
            .collect(),
        _ => vec![],
    }
}

/// Collect only top-level string values from an expression.
///
/// For arrays, extracts direct string elements and the first string element of sub-arrays
/// (to handle `["pkg-name", { options }]` tuples). Does NOT recurse into objects.
fn collect_shallow_string_values(expr: &Expression) -> Vec<String> {
    let mut values = Vec::new();
    match expr {
        Expression::StringLiteral(s) => {
            values.push(s.value.to_string());
        }
        Expression::ArrayExpression(arr) => {
            for el in &arr.elements {
                if let Some(inner) = el.as_expression() {
                    match inner {
                        Expression::StringLiteral(s) => {
                            values.push(s.value.to_string());
                        }
                        // Handle tuples: ["pkg-name", { options }] → extract first string
                        Expression::ArrayExpression(sub_arr) => {
                            if let Some(first) = sub_arr.elements.first()
                                && let Some(first_expr) = first.as_expression()
                                && let Some(s) = expression_to_string(first_expr)
                            {
                                values.push(s);
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        // Handle objects: { "key": "value" } or { "key": ["pkg", { opts }] } → extract values
        Expression::ObjectExpression(obj) => {
            for prop in &obj.properties {
                if let ObjectPropertyKind::ObjectProperty(p) = prop {
                    match &p.value {
                        Expression::StringLiteral(s) => {
                            values.push(s.value.to_string());
                        }
                        // Handle tuples: { "key": ["pkg-name", { options }] }
                        Expression::ArrayExpression(sub_arr) => {
                            if let Some(first) = sub_arr.elements.first()
                                && let Some(first_expr) = first.as_expression()
                                && let Some(s) = expression_to_string(first_expr)
                            {
                                values.push(s);
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        _ => {}
    }
    values
}

/// Recursively collect all string literal values from an expression tree.
fn collect_all_string_values(expr: &Expression, values: &mut Vec<String>) {
    match expr {
        Expression::StringLiteral(s) => {
            values.push(s.value.to_string());
        }
        Expression::ArrayExpression(arr) => {
            for el in &arr.elements {
                if let Some(expr) = el.as_expression() {
                    collect_all_string_values(expr, values);
                }
            }
        }
        Expression::ObjectExpression(obj) => {
            for prop in &obj.properties {
                if let ObjectPropertyKind::ObjectProperty(p) = prop {
                    collect_all_string_values(&p.value, values);
                }
            }
        }
        _ => {}
    }
}

/// Convert a `PropertyKey` to a `String`.
fn property_key_to_string(key: &PropertyKey) -> Option<String> {
    match key {
        PropertyKey::StaticIdentifier(id) => Some(id.name.to_string()),
        PropertyKey::StringLiteral(s) => Some(s.value.to_string()),
        _ => None,
    }
}

/// Extract keys of an object at a nested property path.
fn get_nested_object_keys(obj: &ObjectExpression, path: &[&str]) -> Option<Vec<String>> {
    if path.is_empty() {
        return None;
    }
    let prop = find_property(obj, path[0])?;
    if path.len() == 1 {
        if let Expression::ObjectExpression(nested) = &prop.value {
            let keys = nested
                .properties
                .iter()
                .filter_map(|p| {
                    if let ObjectPropertyKind::ObjectProperty(p) = p {
                        property_key_to_string(&p.key)
                    } else {
                        None
                    }
                })
                .collect();
            return Some(keys);
        }
        return None;
    }
    if let Expression::ObjectExpression(nested) = &prop.value {
        get_nested_object_keys(nested, &path[1..])
    } else {
        None
    }
}

/// Navigate a nested property path and return the raw expression at the end.
fn get_nested_expression<'a>(
    obj: &'a ObjectExpression<'a>,
    path: &[&str],
) -> Option<&'a Expression<'a>> {
    if path.is_empty() {
        return None;
    }
    let prop = find_property(obj, path[0])?;
    if path.len() == 1 {
        return Some(&prop.value);
    }
    if let Expression::ObjectExpression(nested) = &prop.value {
        get_nested_expression(nested, &path[1..])
    } else {
        None
    }
}

/// Navigate a nested path and extract a string, string array, or object string values.
fn get_nested_string_or_array(obj: &ObjectExpression, path: &[&str]) -> Option<Vec<String>> {
    if path.is_empty() {
        return None;
    }
    if path.len() == 1 {
        let prop = find_property(obj, path[0])?;
        return Some(expression_to_string_or_array(&prop.value));
    }
    let prop = find_property(obj, path[0])?;
    if let Expression::ObjectExpression(nested) = &prop.value {
        get_nested_string_or_array(nested, &path[1..])
    } else {
        None
    }
}

/// Convert an expression to a `Vec<String>`, handling string, array, and object-with-string-values.
///
/// Array elements that are object literals are inspected for an `input` property
/// (Angular CLI schema for `styles`/`scripts`/`polyfills`:
/// `{ "input": "src/x.scss", "bundleName": "x", "inject": false }`). Extracting
/// `input` prevents object-form entries from being silently dropped. See #126.
fn expression_to_string_or_array(expr: &Expression) -> Vec<String> {
    match expr {
        Expression::StringLiteral(s) => vec![s.value.to_string()],
        Expression::TemplateLiteral(t) if t.expressions.is_empty() => t
            .quasis
            .first()
            .map(|q| vec![q.value.raw.to_string()])
            .unwrap_or_default(),
        Expression::ArrayExpression(arr) => arr
            .elements
            .iter()
            .filter_map(|el| el.as_expression())
            .filter_map(|e| match e {
                Expression::ObjectExpression(obj) => {
                    find_property(obj, "input").and_then(|p| expression_to_string(&p.value))
                }
                _ => expression_to_string(e),
            })
            .collect(),
        Expression::ObjectExpression(obj) => obj
            .properties
            .iter()
            .filter_map(|p| {
                if let ObjectPropertyKind::ObjectProperty(p) = p {
                    expression_to_string(&p.value)
                } else {
                    None
                }
            })
            .collect(),
        _ => vec![],
    }
}

/// Collect `require('...')` argument strings from an expression.
fn collect_require_sources(expr: &Expression) -> Vec<String> {
    let mut sources = Vec::new();
    match expr {
        Expression::CallExpression(call) if is_require_call(call) => {
            if let Some(s) = get_require_source(call) {
                sources.push(s);
            }
        }
        Expression::ArrayExpression(arr) => {
            for el in &arr.elements {
                if let Some(inner) = el.as_expression() {
                    match inner {
                        Expression::CallExpression(call) if is_require_call(call) => {
                            if let Some(s) = get_require_source(call) {
                                sources.push(s);
                            }
                        }
                        // Tuple: [require('pkg'), options]
                        Expression::ArrayExpression(sub_arr) => {
                            if let Some(first) = sub_arr.elements.first()
                                && let Some(Expression::CallExpression(call)) =
                                    first.as_expression()
                                && is_require_call(call)
                                && let Some(s) = get_require_source(call)
                            {
                                sources.push(s);
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        _ => {}
    }
    sources
}

/// Check if a call expression is `require(...)`.
fn is_require_call(call: &CallExpression) -> bool {
    matches!(&call.callee, Expression::Identifier(id) if id.name == "require")
}

/// Get the first string argument of a `require()` call.
fn get_require_source(call: &CallExpression) -> Option<String> {
    call.arguments.first().and_then(|arg| {
        if let Argument::StringLiteral(s) = arg {
            Some(s.value.to_string())
        } else {
            None
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn js_path() -> PathBuf {
        PathBuf::from("config.js")
    }

    fn ts_path() -> PathBuf {
        PathBuf::from("config.ts")
    }

    #[test]
    fn extract_imports_basic() {
        let source = r"
            import foo from 'foo-pkg';
            import { bar } from '@scope/bar';
            export default {};
        ";
        let imports = extract_imports(source, &js_path());
        assert_eq!(imports, vec!["foo-pkg", "@scope/bar"]);
    }

    #[test]
    fn extract_default_export_object_property() {
        let source = r#"export default { testDir: "./tests" };"#;
        let val = extract_config_string(source, &js_path(), &["testDir"]);
        assert_eq!(val, Some("./tests".to_string()));
    }

    #[test]
    fn extract_define_config_property() {
        let source = r#"
            import { defineConfig } from 'vitest/config';
            export default defineConfig({
                test: {
                    include: ["**/*.test.ts", "**/*.spec.ts"],
                    setupFiles: ["./test/setup.ts"]
                }
            });
        "#;
        let include = extract_config_string_array(source, &ts_path(), &["test", "include"]);
        assert_eq!(include, vec!["**/*.test.ts", "**/*.spec.ts"]);

        let setup = extract_config_string_array(source, &ts_path(), &["test", "setupFiles"]);
        assert_eq!(setup, vec!["./test/setup.ts"]);
    }

    #[test]
    fn extract_module_exports_property() {
        let source = r#"module.exports = { testEnvironment: "jsdom" };"#;
        let val = extract_config_string(source, &js_path(), &["testEnvironment"]);
        assert_eq!(val, Some("jsdom".to_string()));
    }

    #[test]
    fn extract_nested_string_array() {
        let source = r#"
            export default {
                resolve: {
                    alias: {
                        "@": "./src"
                    }
                },
                test: {
                    include: ["src/**/*.test.ts"]
                }
            };
        "#;
        let include = extract_config_string_array(source, &js_path(), &["test", "include"]);
        assert_eq!(include, vec!["src/**/*.test.ts"]);
    }

    #[test]
    fn extract_addons_array() {
        let source = r#"
            export default {
                addons: [
                    "@storybook/addon-a11y",
                    "@storybook/addon-docs",
                    "@storybook/addon-links"
                ]
            };
        "#;
        let addons = extract_config_property_strings(source, &ts_path(), "addons");
        assert_eq!(
            addons,
            vec![
                "@storybook/addon-a11y",
                "@storybook/addon-docs",
                "@storybook/addon-links"
            ]
        );
    }

    #[test]
    fn handle_empty_config() {
        let source = "";
        let result = extract_config_string(source, &js_path(), &["key"]);
        assert_eq!(result, None);
    }

    // ── extract_config_object_keys tests ────────────────────────────

    #[test]
    fn object_keys_postcss_plugins() {
        let source = r"
            module.exports = {
                plugins: {
                    autoprefixer: {},
                    tailwindcss: {},
                    'postcss-import': {}
                }
            };
        ";
        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
        assert_eq!(keys, vec!["autoprefixer", "tailwindcss", "postcss-import"]);
    }

    #[test]
    fn object_keys_nested_path() {
        let source = r"
            export default {
                build: {
                    plugins: {
                        minify: {},
                        compress: {}
                    }
                }
            };
        ";
        let keys = extract_config_object_keys(source, &js_path(), &["build", "plugins"]);
        assert_eq!(keys, vec!["minify", "compress"]);
    }

    #[test]
    fn object_keys_empty_object() {
        let source = r"export default { plugins: {} };";
        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
        assert!(keys.is_empty());
    }

    #[test]
    fn object_keys_non_object_returns_empty() {
        let source = r#"export default { plugins: ["a", "b"] };"#;
        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
        assert!(keys.is_empty());
    }

    // ── extract_config_string_or_array tests ────────────────────────

    #[test]
    fn string_or_array_single_string() {
        let source = r#"export default { entry: "./src/index.js" };"#;
        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
        assert_eq!(result, vec!["./src/index.js"]);
    }

    #[test]
    fn string_or_array_array() {
        let source = r#"export default { entry: ["./src/a.js", "./src/b.js"] };"#;
        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
        assert_eq!(result, vec!["./src/a.js", "./src/b.js"]);
    }

    #[test]
    fn string_or_array_object_values() {
        let source =
            r#"export default { entry: { main: "./src/main.js", vendor: "./src/vendor.js" } };"#;
        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
        assert_eq!(result, vec!["./src/main.js", "./src/vendor.js"]);
    }

    #[test]
    fn string_or_array_nested_path() {
        let source = r#"
            export default {
                build: {
                    rollupOptions: {
                        input: ["./index.html", "./about.html"]
                    }
                }
            };
        "#;
        let result = extract_config_string_or_array(
            source,
            &js_path(),
            &["build", "rollupOptions", "input"],
        );
        assert_eq!(result, vec!["./index.html", "./about.html"]);
    }

    #[test]
    fn string_or_array_template_literal() {
        let source = r"export default { entry: `./src/index.js` };";
        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
        assert_eq!(result, vec!["./src/index.js"]);
    }

    // ── extract_config_require_strings tests ────────────────────────

    #[test]
    fn require_strings_array() {
        let source = r"
            module.exports = {
                plugins: [
                    require('autoprefixer'),
                    require('postcss-import')
                ]
            };
        ";
        let deps = extract_config_require_strings(source, &js_path(), "plugins");
        assert_eq!(deps, vec!["autoprefixer", "postcss-import"]);
    }

    #[test]
    fn require_strings_with_tuples() {
        let source = r"
            module.exports = {
                plugins: [
                    require('autoprefixer'),
                    [require('postcss-preset-env'), { stage: 3 }]
                ]
            };
        ";
        let deps = extract_config_require_strings(source, &js_path(), "plugins");
        assert_eq!(deps, vec!["autoprefixer", "postcss-preset-env"]);
    }

    #[test]
    fn require_strings_empty_array() {
        let source = r"module.exports = { plugins: [] };";
        let deps = extract_config_require_strings(source, &js_path(), "plugins");
        assert!(deps.is_empty());
    }

    #[test]
    fn require_strings_no_require_calls() {
        let source = r#"module.exports = { plugins: ["a", "b"] };"#;
        let deps = extract_config_require_strings(source, &js_path(), "plugins");
        assert!(deps.is_empty());
    }

    #[test]
    fn extract_aliases_from_object_with_file_url_to_path() {
        let source = r#"
            import { defineConfig } from 'vite';
            import { fileURLToPath, URL } from 'node:url';

            export default defineConfig({
                resolve: {
                    alias: {
                        "@": fileURLToPath(new URL("./src", import.meta.url))
                    }
                }
            });
        "#;

        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string())]);
    }

    #[test]
    fn extract_aliases_from_array_form() {
        let source = r#"
            export default {
                resolve: {
                    alias: [
                        { find: "@", replacement: "./src" },
                        { find: "$utils", replacement: "src/lib/utils" }
                    ]
                }
            };
        "#;

        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
        assert_eq!(
            aliases,
            vec![
                ("@".to_string(), "./src".to_string()),
                ("$utils".to_string(), "src/lib/utils".to_string())
            ]
        );
    }

    #[test]
    fn extract_array_object_strings_mixed_forms() {
        let source = r#"
            export default {
                components: [
                    "~/components",
                    { path: "@/feature-components" }
                ]
            };
        "#;

        let values =
            extract_config_array_object_strings(source, &ts_path(), &["components"], "path");
        assert_eq!(
            values,
            vec![
                "~/components".to_string(),
                "@/feature-components".to_string()
            ]
        );
    }

    #[test]
    fn extract_config_plugin_option_string_from_json() {
        let source = r#"{
            "expo": {
                "plugins": [
                    ["expo-router", { "root": "src/app" }]
                ]
            }
        }"#;

        let value = extract_config_plugin_option_string(
            source,
            &json_path(),
            &["expo", "plugins"],
            "expo-router",
            "root",
        );

        assert_eq!(value, Some("src/app".to_string()));
    }

    #[test]
    fn extract_config_plugin_option_string_from_top_level_plugins() {
        let source = r#"{
            "plugins": [
                ["expo-router", { "root": "./src/routes" }]
            ]
        }"#;

        let value = extract_config_plugin_option_string_from_paths(
            source,
            &json_path(),
            &[&["plugins"], &["expo", "plugins"]],
            "expo-router",
            "root",
        );

        assert_eq!(value, Some("./src/routes".to_string()));
    }

    #[test]
    fn extract_config_plugin_option_string_from_ts_config() {
        let source = r"
            export default {
                expo: {
                    plugins: [
                        ['expo-router', { root: './src/app' }]
                    ]
                }
            };
        ";

        let value = extract_config_plugin_option_string(
            source,
            &ts_path(),
            &["expo", "plugins"],
            "expo-router",
            "root",
        );

        assert_eq!(value, Some("./src/app".to_string()));
    }

    #[test]
    fn extract_config_plugin_option_string_returns_none_when_plugin_missing() {
        let source = r#"{
            "expo": {
                "plugins": [
                    ["expo-font", {}]
                ]
            }
        }"#;

        let value = extract_config_plugin_option_string(
            source,
            &json_path(),
            &["expo", "plugins"],
            "expo-router",
            "root",
        );

        assert_eq!(value, None);
    }

    #[test]
    fn normalize_config_path_relative_to_root() {
        let config_path = PathBuf::from("/project/vite.config.ts");
        let root = PathBuf::from("/project");

        assert_eq!(
            normalize_config_path("./src/lib", &config_path, &root),
            Some("src/lib".to_string())
        );
        assert_eq!(
            normalize_config_path("/src/lib", &config_path, &root),
            Some("src/lib".to_string())
        );
    }

    // ── JSON wrapped in parens (for tsconfig.json parsing) ──────────

    #[test]
    fn json_wrapped_in_parens_string() {
        let source = r#"({"extends": "@tsconfig/node18/tsconfig.json"})"#;
        let val = extract_config_string(source, &js_path(), &["extends"]);
        assert_eq!(val, Some("@tsconfig/node18/tsconfig.json".to_string()));
    }

    #[test]
    fn json_wrapped_in_parens_nested_array() {
        let source =
            r#"({"compilerOptions": {"types": ["node", "jest"]}, "include": ["src/**/*"]})"#;
        let types = extract_config_string_array(source, &js_path(), &["compilerOptions", "types"]);
        assert_eq!(types, vec!["node", "jest"]);

        let include = extract_config_string_array(source, &js_path(), &["include"]);
        assert_eq!(include, vec!["src/**/*"]);
    }

    #[test]
    fn json_wrapped_in_parens_object_keys() {
        let source = r#"({"plugins": {"autoprefixer": {}, "tailwindcss": {}}})"#;
        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
        assert_eq!(keys, vec!["autoprefixer", "tailwindcss"]);
    }

    // ── JSON file extension detection ────────────────────────────

    fn json_path() -> PathBuf {
        PathBuf::from("config.json")
    }

    #[test]
    fn json_file_parsed_correctly() {
        let source = r#"{"key": "value", "list": ["a", "b"]}"#;
        let val = extract_config_string(source, &json_path(), &["key"]);
        assert_eq!(val, Some("value".to_string()));

        let list = extract_config_string_array(source, &json_path(), &["list"]);
        assert_eq!(list, vec!["a", "b"]);
    }

    #[test]
    fn jsonc_file_parsed_correctly() {
        let source = r#"{"key": "value"}"#;
        let path = PathBuf::from("tsconfig.jsonc");
        let val = extract_config_string(source, &path, &["key"]);
        assert_eq!(val, Some("value".to_string()));
    }

    // ── defineConfig with arrow function ─────────────────────────

    #[test]
    fn extract_define_config_arrow_function() {
        let source = r#"
            import { defineConfig } from 'vite';
            export default defineConfig(() => ({
                test: {
                    include: ["**/*.test.ts"]
                }
            }));
        "#;
        let include = extract_config_string_array(source, &ts_path(), &["test", "include"]);
        assert_eq!(include, vec!["**/*.test.ts"]);
    }

    #[test]
    fn extract_config_from_default_export_function_declaration() {
        let source = r#"
            export default function createConfig() {
                return {
                    clientModules: ["./src/client/global.js"]
                };
            }
        "#;

        let client_modules = extract_config_string_array(source, &ts_path(), &["clientModules"]);
        assert_eq!(client_modules, vec!["./src/client/global.js"]);
    }

    #[test]
    fn extract_config_from_default_export_async_function_declaration() {
        let source = r#"
            export default async function createConfigAsync() {
                return {
                    docs: {
                        path: "knowledge"
                    }
                };
            }
        "#;

        let docs_path = extract_config_string(source, &ts_path(), &["docs", "path"]);
        assert_eq!(docs_path, Some("knowledge".to_string()));
    }

    #[test]
    fn extract_config_from_exported_arrow_function_identifier() {
        let source = r#"
            const config = async () => {
                return {
                    themes: ["classic"]
                };
            };

            export default config;
        "#;

        let themes = extract_config_shallow_strings(source, &ts_path(), "themes");
        assert_eq!(themes, vec!["classic"]);
    }

    // ── module.exports with nested properties ────────────────────

    #[test]
    fn module_exports_nested_string() {
        let source = r#"
            module.exports = {
                resolve: {
                    alias: {
                        "@": "./src"
                    }
                }
            };
        "#;
        let val = extract_config_string(source, &js_path(), &["resolve", "alias", "@"]);
        assert_eq!(val, Some("./src".to_string()));
    }

    // ── extract_config_property_strings (recursive) ──────────────

    #[test]
    fn property_strings_nested_objects() {
        let source = r#"
            export default {
                plugins: {
                    group1: { a: "val-a" },
                    group2: { b: "val-b" }
                }
            };
        "#;
        let values = extract_config_property_strings(source, &js_path(), "plugins");
        assert!(values.contains(&"val-a".to_string()));
        assert!(values.contains(&"val-b".to_string()));
    }

    #[test]
    fn property_strings_missing_key_returns_empty() {
        let source = r#"export default { other: "value" };"#;
        let values = extract_config_property_strings(source, &js_path(), "missing");
        assert!(values.is_empty());
    }

    // ── extract_config_shallow_strings ────────────────────────────

    #[test]
    fn shallow_strings_tuple_array() {
        let source = r#"
            module.exports = {
                reporters: ["default", ["jest-junit", { outputDirectory: "reports" }]]
            };
        "#;
        let values = extract_config_shallow_strings(source, &js_path(), "reporters");
        assert_eq!(values, vec!["default", "jest-junit"]);
        // "reports" should NOT be extracted (it's inside an options object)
        assert!(!values.contains(&"reports".to_string()));
    }

    #[test]
    fn shallow_strings_single_string() {
        let source = r#"export default { preset: "ts-jest" };"#;
        let values = extract_config_shallow_strings(source, &js_path(), "preset");
        assert_eq!(values, vec!["ts-jest"]);
    }

    #[test]
    fn shallow_strings_missing_key() {
        let source = r#"export default { other: "val" };"#;
        let values = extract_config_shallow_strings(source, &js_path(), "missing");
        assert!(values.is_empty());
    }

    // ── extract_config_nested_shallow_strings tests ──────────────

    #[test]
    fn nested_shallow_strings_vitest_reporters() {
        let source = r#"
            export default {
                test: {
                    reporters: ["default", "vitest-sonar-reporter"]
                }
            };
        "#;
        let values =
            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
        assert_eq!(values, vec!["default", "vitest-sonar-reporter"]);
    }

    #[test]
    fn nested_shallow_strings_tuple_format() {
        let source = r#"
            export default {
                test: {
                    reporters: ["default", ["vitest-sonar-reporter", { outputFile: "report.xml" }]]
                }
            };
        "#;
        let values =
            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
        assert_eq!(values, vec!["default", "vitest-sonar-reporter"]);
    }

    #[test]
    fn nested_shallow_strings_missing_outer() {
        let source = r"export default { other: {} };";
        let values =
            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
        assert!(values.is_empty());
    }

    #[test]
    fn nested_shallow_strings_missing_inner() {
        let source = r#"export default { test: { include: ["**/*.test.ts"] } };"#;
        let values =
            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
        assert!(values.is_empty());
    }

    // ── extract_config_string_or_array edge cases ────────────────

    #[test]
    fn string_or_array_missing_path() {
        let source = r"export default {};";
        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
        assert!(result.is_empty());
    }

    #[test]
    fn string_or_array_non_string_values() {
        // When values are not strings (e.g., numbers), they should be skipped
        let source = r"export default { entry: [42, true] };";
        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
        assert!(result.is_empty());
    }

    // ── extract_config_array_nested_string_or_array ──────────────

    #[test]
    fn array_nested_extraction() {
        let source = r#"
            export default defineConfig({
                test: {
                    projects: [
                        {
                            test: {
                                setupFiles: ["./test/setup-a.ts"]
                            }
                        },
                        {
                            test: {
                                setupFiles: "./test/setup-b.ts"
                            }
                        }
                    ]
                }
            });
        "#;
        let results = extract_config_array_nested_string_or_array(
            source,
            &ts_path(),
            &["test", "projects"],
            &["test", "setupFiles"],
        );
        assert!(results.contains(&"./test/setup-a.ts".to_string()));
        assert!(results.contains(&"./test/setup-b.ts".to_string()));
    }

    #[test]
    fn array_nested_empty_when_no_array() {
        let source = r#"export default { test: { projects: "not-an-array" } };"#;
        let results = extract_config_array_nested_string_or_array(
            source,
            &js_path(),
            &["test", "projects"],
            &["test", "setupFiles"],
        );
        assert!(results.is_empty());
    }

    // ── extract_config_object_nested_string_or_array ─────────────

    #[test]
    fn object_nested_extraction() {
        let source = r#"{
            "projects": {
                "app-one": {
                    "architect": {
                        "build": {
                            "options": {
                                "styles": ["src/styles.css"]
                            }
                        }
                    }
                }
            }
        }"#;
        let results = extract_config_object_nested_string_or_array(
            source,
            &json_path(),
            &["projects"],
            &["architect", "build", "options", "styles"],
        );
        assert_eq!(results, vec!["src/styles.css"]);
    }

    #[test]
    fn array_with_object_input_form_extracted() {
        // Angular CLI schema allows both string and object forms in `styles`:
        //   "styles": ["src/styles.scss", { "input": "src/theme.scss", "inject": false }]
        // The object form declares bundle-name / inject options for vendor
        // stylesheets. Previously the array branch silently dropped object
        // elements. See #126.
        let source = r#"{
            "projects": {
                "app": {
                    "architect": {
                        "build": {
                            "options": {
                                "styles": [
                                    "src/styles.scss",
                                    { "input": "src/theme.scss", "bundleName": "theme", "inject": false },
                                    { "bundleName": "lazy-only" }
                                ]
                            }
                        }
                    }
                }
            }
        }"#;
        let results = extract_config_object_nested_string_or_array(
            source,
            &json_path(),
            &["projects"],
            &["architect", "build", "options", "styles"],
        );
        assert!(
            results.contains(&"src/styles.scss".to_string()),
            "string form must still work: {results:?}"
        );
        assert!(
            results.contains(&"src/theme.scss".to_string()),
            "object form with `input` must be extracted: {results:?}"
        );
        // Object without `input` has nothing to extract; must NOT leak
        // unrelated property values (e.g., `bundleName`).
        assert!(
            !results.contains(&"lazy-only".to_string()),
            "bundleName must not be misinterpreted as a path: {results:?}"
        );
        assert!(
            !results.contains(&"theme".to_string()),
            "bundleName from full object must not leak: {results:?}"
        );
    }

    // ── extract_config_object_nested_strings ─────────────────────

    #[test]
    fn object_nested_strings_extraction() {
        let source = r#"{
            "targets": {
                "build": {
                    "executor": "@angular/build:application"
                },
                "test": {
                    "executor": "@nx/vite:test"
                }
            }
        }"#;
        let results =
            extract_config_object_nested_strings(source, &json_path(), &["targets"], &["executor"]);
        assert!(results.contains(&"@angular/build:application".to_string()));
        assert!(results.contains(&"@nx/vite:test".to_string()));
    }

    // ── extract_config_require_strings edge cases ────────────────

    #[test]
    fn require_strings_direct_call() {
        let source = r"module.exports = { adapter: require('@sveltejs/adapter-node') };";
        let deps = extract_config_require_strings(source, &js_path(), "adapter");
        assert_eq!(deps, vec!["@sveltejs/adapter-node"]);
    }

    #[test]
    fn require_strings_no_matching_key() {
        let source = r"module.exports = { other: require('something') };";
        let deps = extract_config_require_strings(source, &js_path(), "plugins");
        assert!(deps.is_empty());
    }

    // ── extract_imports edge cases ───────────────────────────────

    #[test]
    fn extract_imports_no_imports() {
        let source = r"export default {};";
        let imports = extract_imports(source, &js_path());
        assert!(imports.is_empty());
    }

    #[test]
    fn extract_imports_side_effect_import() {
        let source = r"
            import 'polyfill';
            import './local-setup';
            export default {};
        ";
        let imports = extract_imports(source, &js_path());
        assert_eq!(imports, vec!["polyfill", "./local-setup"]);
    }

    #[test]
    fn extract_imports_mixed_specifiers() {
        let source = r"
            import defaultExport from 'module-a';
            import { named } from 'module-b';
            import * as ns from 'module-c';
            export default {};
        ";
        let imports = extract_imports(source, &js_path());
        assert_eq!(imports, vec!["module-a", "module-b", "module-c"]);
    }

    // ── Template literal support ─────────────────────────────────

    #[test]
    fn template_literal_in_string_or_array() {
        let source = r"export default { entry: `./src/index.ts` };";
        let result = extract_config_string_or_array(source, &ts_path(), &["entry"]);
        assert_eq!(result, vec!["./src/index.ts"]);
    }

    #[test]
    fn template_literal_in_config_string() {
        let source = r"export default { testDir: `./tests` };";
        let val = extract_config_string(source, &js_path(), &["testDir"]);
        assert_eq!(val, Some("./tests".to_string()));
    }

    // ── Empty/missing path navigation ────────────────────────────

    #[test]
    fn nested_string_array_empty_path() {
        let source = r#"export default { items: ["a", "b"] };"#;
        let result = extract_config_string_array(source, &js_path(), &[]);
        assert!(result.is_empty());
    }

    #[test]
    fn nested_string_empty_path() {
        let source = r#"export default { key: "val" };"#;
        let result = extract_config_string(source, &js_path(), &[]);
        assert!(result.is_none());
    }

    #[test]
    fn object_keys_empty_path() {
        let source = r"export default { plugins: {} };";
        let result = extract_config_object_keys(source, &js_path(), &[]);
        assert!(result.is_empty());
    }

    // ── No config object found ───────────────────────────────────

    #[test]
    fn no_config_object_returns_empty() {
        // Source with no default export or module.exports
        let source = r"const x = 42;";
        let result = extract_config_string(source, &js_path(), &["key"]);
        assert!(result.is_none());

        let arr = extract_config_string_array(source, &js_path(), &["items"]);
        assert!(arr.is_empty());

        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
        assert!(keys.is_empty());
    }

    // ── String literal with string key property ──────────────────

    #[test]
    fn property_with_string_key() {
        let source = r#"export default { "string-key": "value" };"#;
        let val = extract_config_string(source, &js_path(), &["string-key"]);
        assert_eq!(val, Some("value".to_string()));
    }

    #[test]
    fn nested_navigation_through_non_object() {
        // Trying to navigate through a string value should return None
        let source = r#"export default { level1: "not-an-object" };"#;
        let val = extract_config_string(source, &js_path(), &["level1", "level2"]);
        assert!(val.is_none());
    }

    // ── Variable reference resolution ───────────────────────────

    #[test]
    fn variable_reference_untyped() {
        let source = r#"
            const config = {
                testDir: "./tests"
            };
            export default config;
        "#;
        let val = extract_config_string(source, &js_path(), &["testDir"]);
        assert_eq!(val, Some("./tests".to_string()));
    }

    #[test]
    fn variable_reference_with_type_annotation() {
        let source = r#"
            import type { StorybookConfig } from '@storybook/react-vite';
            const config: StorybookConfig = {
                addons: ["@storybook/addon-a11y", "@storybook/addon-docs"],
                framework: "@storybook/react-vite"
            };
            export default config;
        "#;
        let addons = extract_config_shallow_strings(source, &ts_path(), "addons");
        assert_eq!(
            addons,
            vec!["@storybook/addon-a11y", "@storybook/addon-docs"]
        );

        let framework = extract_config_string(source, &ts_path(), &["framework"]);
        assert_eq!(framework, Some("@storybook/react-vite".to_string()));
    }

    #[test]
    fn variable_reference_with_define_config() {
        let source = r#"
            import { defineConfig } from 'vitest/config';
            const config = defineConfig({
                test: {
                    include: ["**/*.test.ts"]
                }
            });
            export default config;
        "#;
        let include = extract_config_string_array(source, &ts_path(), &["test", "include"]);
        assert_eq!(include, vec!["**/*.test.ts"]);
    }

    // ── TS type annotation wrappers ─────────────────────────────

    #[test]
    fn ts_satisfies_direct_export() {
        let source = r#"
            export default {
                testDir: "./tests"
            } satisfies PlaywrightTestConfig;
        "#;
        let val = extract_config_string(source, &ts_path(), &["testDir"]);
        assert_eq!(val, Some("./tests".to_string()));
    }

    #[test]
    fn ts_as_direct_export() {
        let source = r#"
            export default {
                testDir: "./tests"
            } as const;
        "#;
        let val = extract_config_string(source, &ts_path(), &["testDir"]);
        assert_eq!(val, Some("./tests".to_string()));
    }
}