fallow-core 3.29.0

Internal detector backend for fallow-engine and fallow-api
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
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
//! Module Federation plugin and the shared `exposes` / `remotes` / `shared`
//! reader.
//!
//! Federation options reach a build in two shapes. A standalone
//! `module-federation.config.*` file default-exports the options object and is
//! owned by this plugin. The same options also reach a Federation plugin call
//! inside a bundler config, which the webpack, rspack, rsbuild, vite and
//! Next.js plugins read through [`apply_bundler_plugin_options`]. A call is read
//! wherever it sits in the config, because a plugin list is nested, held by a
//! variable, or built inside a hook as often as it is a literal array.
//!
//! Reading is syntactic. `exposes` targets become entry-point globs so an
//! exposed module is not mistaken for dead code, and `remotes` aliases become
//! runtime-provided specifiers so an import of a remote container is not
//! mistaken for an unlisted npm dependency. `shared` packages get dependency
//! credit, because the Federation runtime loads them for the remote containers
//! even when no project file imports them. No remote container is fetched and
//! no cross-deployment reachability is inferred.

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

use oxc_ast::ast::{
    Argument, CallExpression, Expression, NewExpression, ObjectExpression, ObjectPropertyKind,
    Program, PropertyKey,
};
use oxc_ast_visit::{Visit, walk};

use super::config_parser;
use super::{Plugin, PluginResult, ProvidedDependencyRule};

const ENABLERS: &[&str] = &[
    "@module-federation/enhanced",
    "@module-federation/modern-js",
    "@module-federation/nextjs-mf",
    "@module-federation/node",
    "@module-federation/rsbuild-plugin",
    "@module-federation/rspack",
    "@module-federation/runtime",
    "@module-federation/vite",
    "@module-federation/webpack-bundler-runtime",
    "@originjs/vite-plugin-federation",
];

/// The build plugin packages among the enablers. A standalone config that
/// declares a Federation key is read by one of these, and no config file
/// imports it, so the config credits them. The runtime packages are imported by
/// application code, which credits them on its own.
const BUILD_PLUGIN_ENABLERS: &[&str] = &[
    "@module-federation/enhanced",
    "@module-federation/modern-js",
    "@module-federation/nextjs-mf",
    "@module-federation/node",
    "@module-federation/rsbuild-plugin",
    "@module-federation/rspack",
    "@module-federation/vite",
    "@originjs/vite-plugin-federation",
];

/// Calls that return their options argument unchanged, so the argument is
/// read as the options with no diagnostic. Any other call can add to or change
/// what it returns.
const IDENTITY_WRAPPERS: &[&str] = &["createModuleFederationConfig", "defineConfig"];

const CONFIG_PATTERNS: &[&str] = &["module-federation.config.{ts,js,mjs,cjs,mts,cts}"];

const ALWAYS_USED: &[&str] = CONFIG_PATTERNS;

/// Callee names that receive Module Federation options inline in a bundler
/// config: `ModuleFederationPlugin` for webpack and rspack,
/// `pluginModuleFederation` for rsbuild, `federation` for vite,
/// `NextFederationPlugin` for Next.js.
/// The Federation callee that other libraries also name a function, so its
/// options pass the shape gate only when they declare a Federation key.
const AMBIGUOUS_CALLEE: &str = "federation";

const FEDERATION_CALLEES: &[&str] = &[
    "ModuleFederationPlugin",
    "NextFederationPlugin",
    "moduleFederationPlugin",
    "pluginModuleFederation",
    "federation",
];

/// Brace list appended to an extensionless `exposes` target.
const EXPOSE_EXTENSIONS: &str = super::REQUEST_EXTENSIONS;

/// Glob suffix that covers every file under the directory that declared the
/// remote.
const SCOPE_SUFFIX: &str = "**/*";

/// What one Federation options object statically declares.
#[derive(Debug, Default, PartialEq, Eq)]
struct FederationConfig {
    /// Local module targets from `exposes`, as written in the config.
    pub exposed_targets: Vec<String>,
    /// Package names of bare module requests named as `exposes` targets.
    pub exposed_packages: Vec<String>,
    /// Declared `remotes` alias names, in source order.
    pub remote_aliases: Vec<String>,
    /// Package names that `shared` declares, in source order.
    pub shared_packages: Vec<String>,
}

/// Where to look for Federation options in one config file.
struct FederationSites {
    /// Read the options of every Federation plugin call in the file, at any
    /// position.
    pub read_plugin_calls: bool,
    /// Read `exposes` / `remotes` off the config object itself, as the
    /// standalone `module-federation.config.*` file declares them.
    pub read_config_object: bool,
}

/// Where a config file sits, which decides how its declarations are anchored.
struct ConfigLocation<'a> {
    /// The config file that anchors the declarations.
    pub config_path: &'a Path,
    /// The file that holds the declarations: the config file itself, or a
    /// helper module that the config imports. Diagnostics and trace sources
    /// name this file.
    pub source_path: &'a Path,
    pub root: &'a Path,
    /// Project-relative base directory that replaces the config directory when
    /// resolving a relative `exposes` target, as webpack's `context` does.
    pub context: Option<&'a Path>,
    /// Project-relative package directory that replaces the config directory
    /// when the config sits in a config directory such as `config/`.
    pub package_dir: Option<&'a Path>,
}

/// The directories a bundler config anchors its Federation declarations to,
/// when they differ from the config file's own directory.
#[derive(Debug, Clone, Copy, Default)]
pub(super) struct FederationBase<'a> {
    /// The base directory option of the config, such as webpack's `context`,
    /// as a project-relative path.
    pub context: Option<&'a Path>,
    /// The project-relative package directory of a config that sits in a
    /// config directory. Webpack runs such a config from the package root.
    pub package_dir: Option<&'a Path>,
}

impl ConfigLocation<'_> {
    /// The directory a relative `exposes` target resolves against, expressed as
    /// a stand-in config path so the shared path normalization applies.
    fn target_base(&self) -> std::borrow::Cow<'_, Path> {
        match self.context.or(self.package_dir) {
            Some(context) => {
                std::borrow::Cow::Owned(self.root.join(context).join("module-federation"))
            }
            None => std::borrow::Cow::Borrowed(self.config_path),
        }
    }

    /// The config file's path relative to the project root.
    ///
    /// `normalize_config_path` reads a leading `/` as project-root-relative, the
    /// convention config values use, so it cannot relativize a filesystem path.
    fn relative_config_path(&self) -> Option<String> {
        if let Ok(relative) = self.config_path.strip_prefix(self.root) {
            return Some(config_parser::path_to_config_string(relative));
        }
        (!self.config_path.is_absolute())
            .then(|| config_parser::path_to_config_string(self.config_path))
    }

    /// The `package.json` of the package that owns the config: the nearest one
    /// at or above the config directory, within the plugin root. The root
    /// manifest is the fallback, because a config always belongs to the
    /// package it is read for.
    fn owning_manifest(&self) -> PathBuf {
        let mut directory = self.config_path.parent();
        while let Some(current) = directory {
            if !current.starts_with(self.root) {
                break;
            }
            let manifest = current.join("package.json");
            if manifest.is_file() {
                return manifest;
            }
            directory = current.parent();
        }
        self.root.join("package.json")
    }

    /// Glob covering the directory that declared the remote.
    ///
    /// A config file governs the tree it sits in, so a config inside a
    /// workspace package cannot silence a finding in a sibling package. A root
    /// config governs the whole project.
    fn scope_pattern(&self) -> String {
        let directory = match self.package_dir {
            Some(package_dir) => Some(config_parser::path_to_config_string(package_dir)),
            None => self.relative_config_path().and_then(|relative| {
                Path::new(&relative)
                    .parent()
                    .map(config_parser::path_to_config_string)
            }),
        }
        .filter(|directory| !directory.is_empty());
        match directory {
            Some(directory) => format!("{directory}/{SCOPE_SUFFIX}"),
            None => SCOPE_SUFFIX.to_string(),
        }
    }
}

/// A Federation key this reader understands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FederationKey {
    Exposes,
    Remotes,
    Shared,
}

impl FederationKey {
    /// The keys whose unread part records a diagnostic. An unread `shared`
    /// entry records none: it only withholds dependency credit, and the
    /// package that loses the credit still reports as it did before `shared`
    /// was read.
    const DIAGNOSED: [Self; 2] = [Self::Exposes, Self::Remotes];

    const fn name(self) -> &'static str {
        match self {
            Self::Exposes => "exposes",
            Self::Remotes => "remotes",
            Self::Shared => "shared",
        }
    }
}

/// Why a Federation key declaration could not be read in full.
///
/// The consequence and the remedy are rendered by the shared diagnostic
/// message, keyed on the token each variant maps to, so the vocabulary lives at
/// the one place every workspace diagnostic is rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UnreadReason {
    /// The value is not an object literal.
    NotObjectLiteral,
    /// The value is the array form, which this reader does not read yet.
    ArrayForm,
    /// The object literal spreads a value that is not statically readable, so
    /// it may declare more than what was read.
    Spread,
    /// At least one entry's value holds no statically readable string.
    Entries,
    /// The options pass through a call that is not a known identity wrapper,
    /// which can add to or change what it returns. The object literal passed
    /// to the call is read as a lower bound.
    UnrecognizedCall,
    /// The options come from a relative import or `require` whose target could
    /// not be read.
    ImportTargetUnreadable,
}

/// One Federation key declaration that was present but not fully readable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct UnreadDeclaration {
    key: FederationKey,
    reason: UnreadReason,
}

impl UnreadReason {
    /// The kebab-case token that reaches the wire. The shared renderer builds
    /// the situation clause from it.
    const fn token(self) -> &'static str {
        match self {
            Self::NotObjectLiteral => "not-object-literal",
            Self::ArrayForm => "array-form",
            Self::Spread => "spread",
            Self::Entries => "unreadable-entries",
            Self::UnrecognizedCall => "unrecognized-call",
            Self::ImportTargetUnreadable => "import-target-unreadable",
        }
    }
}

/// Read every statically available Federation options object in `source`,
/// recording one advisory per `exposes` or `remotes` declaration that is present
/// but not fully readable.
///
/// The plugin records the fact and never prints it: one renderer owns the
/// sentence, and one registry owns the deduplication, so a combined run states
/// it once and a consumer reading the envelope sees it at all (issue #2736).
fn extract(
    result: &mut PluginResult,
    source: &str,
    location: &ConfigLocation<'_>,
    plugin_label: &str,
    sites: &FederationSites,
) -> FederationRead {
    let read = read_declarations(source, location.source_path, sites);
    for declaration in &read.unread {
        result
            .config_diagnostics
            .push(super::PluginConfigDiagnostic::unreadable(
                location.source_path,
                plugin_label,
                declaration.key.name(),
                declaration.reason.token(),
            ));
    }
    read
}

/// Read and register the Federation options of one config file. Returns
/// whether the options declare a Federation key.
fn apply_from_source(
    result: &mut PluginResult,
    source: &str,
    location: &ConfigLocation<'_>,
    plugin_label: &str,
    sites: &FederationSites,
) -> bool {
    let read = extract(result, source, location, plugin_label, sites);
    apply(result, &read.config, location, plugin_label);
    read.declares_key
}

/// Read the Federation options of every Federation plugin call in a bundler
/// config and register what they declare.
///
/// `base` names the directories that replace the config directory when
/// resolving a relative `exposes` target and scoping a remote alias.
///
/// A plugin call in a helper module that the config imports with a relative
/// specifier is read too, one import deep, as if the call sat in the config.
/// A project often creates its Federation plugins in a module such as
/// `config/module-federation.js` and imports it from each bundler config.
pub(super) fn apply_bundler_plugin_options(
    result: &mut PluginResult,
    source: &str,
    config_path: &Path,
    root: &Path,
    base: FederationBase<'_>,
    plugin_label: &str,
) {
    let sites = FederationSites {
        read_plugin_calls: true,
        read_config_object: false,
    };
    let location = ConfigLocation {
        config_path,
        source_path: config_path,
        root,
        context: base.context,
        package_dir: base.package_dir,
    };
    apply_from_source(result, source, &location, plugin_label, &sites);
    for (helper_path, helper_source) in imported_helper_modules(source, config_path, root) {
        let helper = ConfigLocation {
            source_path: &helper_path,
            ..location
        };
        apply_from_source(result, &helper_source, &helper, plugin_label, &sites);
    }
}

/// The project modules that `source` imports with a relative specifier and
/// that name a Federation plugin callee, with their source text. A static
/// `import` and a `require` call at any position count. A module outside the
/// project root, and the config itself, are skipped.
fn imported_helper_modules(
    source: &str,
    config_path: &Path,
    root: &Path,
) -> Vec<(PathBuf, String)> {
    let specifiers = config_parser::extract_from_source(source, config_path, |program| {
        let mut collector = RelativeSpecifierCollector::default();
        collector.visit_program(program);
        Some(collector.specifiers)
    })
    .unwrap_or_default();
    let mut helpers: Vec<(PathBuf, String)> = Vec::new();
    for specifier in specifiers {
        let Some((path, helper_source)) =
            config_parser::resolve_sibling_module(config_path, &specifier)
        else {
            continue;
        };
        let path = normalize_lexically(&path);
        let Ok(real_path) = path.canonicalize() else {
            continue;
        };
        let inside_root = root
            .canonicalize()
            .is_ok_and(|root| real_path.starts_with(root));
        let is_config = config_path
            .canonicalize()
            .is_ok_and(|config| config == real_path);
        let names_callee = FEDERATION_CALLEES
            .iter()
            .any(|callee| helper_source.contains(callee));
        if inside_root
            && !is_config
            && names_callee
            && !helpers.iter().any(|(known, _)| *known == path)
        {
            helpers.push((path, helper_source));
        }
    }
    helpers
}

/// Drop the `.` components of a path and fold each `..` into its parent, so a
/// helper path keeps the spelling of the config path it was joined to.
fn normalize_lexically(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                if !normalized.pop() {
                    normalized.push(component);
                }
            }
            other => normalized.push(other),
        }
    }
    normalized
}

/// The relative specifiers of the static imports and the `require` calls in
/// one program.
#[derive(Default)]
struct RelativeSpecifierCollector {
    specifiers: Vec<String>,
}

impl RelativeSpecifierCollector {
    fn push(&mut self, specifier: &str) {
        if (specifier.starts_with("./") || specifier.starts_with("../"))
            && !self.specifiers.iter().any(|known| known == specifier)
        {
            self.specifiers.push(specifier.to_owned());
        }
    }
}

impl<'a> Visit<'a> for RelativeSpecifierCollector {
    fn visit_import_declaration(&mut self, declaration: &oxc_ast::ast::ImportDeclaration<'a>) {
        if !declaration.import_kind.is_type() {
            self.push(declaration.source.value.as_str());
        }
    }

    fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
        if config_parser::is_require_call(call)
            && let Some(specifier) = config_parser::get_require_source(call)
        {
            self.push(&specifier);
        }
        walk::walk_call_expression(self, call);
    }
}

/// Register what a Federation options object declares: exposed targets as
/// entry-point globs, exposed module requests and shared packages as
/// dependencies of the package that owns the config, and
/// remote aliases as runtime-provided specifiers scoped to the declaring
/// directory. Each exposed rule and each alias also records its config, so a
/// trace can name it.
fn apply(
    result: &mut PluginResult,
    config: &FederationConfig,
    location: &ConfigLocation<'_>,
    plugin_label: &str,
) {
    let base = location.target_base();
    let source = |target| super::FederationSource {
        target,
        config_path: location.source_path.to_path_buf(),
        plugin: plugin_label.to_owned(),
        key: FederationKey::Exposes.name(),
    };
    for target in &config.exposed_targets {
        let first_new = result.entry_patterns.len();
        push_exposed_entry_patterns(result, target, &base, location.root);
        let exposed: Vec<super::FederationSource> = result.entry_patterns[first_new..]
            .iter()
            .map(|rule| source(super::FederationSourceTarget::Exposed(rule.clone())))
            .collect();
        result.federation_sources.extend(exposed);
    }
    if !config.exposed_packages.is_empty() || !config.shared_packages.is_empty() {
        let manifest = location.owning_manifest();
        result.package_referenced_dependencies.extend(
            config
                .exposed_packages
                .iter()
                .chain(&config.shared_packages)
                .map(|package| (manifest.clone(), package.clone())),
        );
    }
    if config.remote_aliases.is_empty() {
        return;
    }
    let scope = location.scope_pattern();
    for alias in &config.remote_aliases {
        result
            .provided_dependencies
            .push(ProvidedDependencyRule::new(
                scope.clone(),
                [alias.clone()],
                [format!("{alias}/")],
            ));
        result.federation_sources.push(super::FederationSource {
            key: FederationKey::Remotes.name(),
            ..source(super::FederationSourceTarget::Remote(alias.clone()))
        });
    }
}

fn push_exposed_entry_patterns(result: &mut PluginResult, target: &str, base: &Path, root: &Path) {
    let trimmed = target.trim();
    if trimmed.is_empty() || trimmed.contains(':') {
        return;
    }
    let Some(normalized) = config_parser::normalize_config_path(trimmed, base, root)
        .or_else(|| config_parser::parent_relative_config_path(trimmed, base, root))
    else {
        return;
    };
    // An entry pattern is compiled as a glob, while a target is a literal path.
    // Bracketed route filenames are the Next.js convention, so an unescaped
    // target would both miss the exposed file and credit an unrelated one.
    let escaped = globset::escape(&normalized);
    let patterns = if super::has_source_extension(&normalized) {
        vec![escaped]
    } else {
        vec![
            format!("{escaped}.{EXPOSE_EXTENSIONS}"),
            format!("{escaped}/index.{EXPOSE_EXTENSIONS}"),
        ]
    };
    // Only a target that climbs out of the plugin root is parent-relative, so
    // only it asks the workspace prefix to resolve its `../` segments.
    let parent_relative = normalized.starts_with("../");
    for pattern in patterns {
        if parent_relative {
            result.push_parent_relative_entry_pattern(pattern);
        } else {
            result.push_entry_pattern(pattern);
        }
    }
}

/// What one config file declares for Module Federation.
#[derive(Debug, Default)]
struct FederationRead {
    config: FederationConfig,
    unread: Vec<UnreadDeclaration>,
    /// Whether an accepted options value declares `exposes`, `remotes` or
    /// `shared`.
    declares_key: bool,
}

#[cfg(test)]
fn read(
    source: &str,
    config_path: &Path,
    sites: &FederationSites,
) -> (FederationConfig, Vec<UnreadDeclaration>) {
    let read = read_declarations(source, config_path, sites);
    (read.config, read.unread)
}

fn read_declarations(source: &str, config_path: &Path, sites: &FederationSites) -> FederationRead {
    config_parser::extract_from_source(source, config_path, |program| {
        let mut collector = FederationCallCollector::new(program, config_path);

        if sites.read_config_object {
            let mut options = ResolvedOptions::default();
            if read_config_object_options(program, config_path, &mut options) {
                collector.merge(options, true);
            }
        }
        if sites.read_plugin_calls {
            collector.visit_program(program);
        }

        Some(FederationRead {
            config: collector.config,
            unread: collector.unread,
            declares_key: collector.declares_key,
        })
    })
    .unwrap_or_default()
}

/// Read the options a standalone config exports.
///
/// The exported value goes through the options resolver first, so a wrapper
/// call is read the same way as in a plugin call. A shape the resolver does not
/// accept, such as a function that returns the options, falls back to the
/// shared config object lookup.
fn read_config_object_options(
    program: &Program<'_>,
    config_path: &Path,
    options: &mut ResolvedOptions,
) -> bool {
    if config_parser::find_module_export_expression(program)
        .is_some_and(|export| resolve_options(program, config_path, export, 0, options))
    {
        return true;
    }
    let Some(config_object) = config_parser::find_config_object(program) else {
        return false;
    };
    read_options_object(program, config_path, config_object, 0, options);
    true
}

/// Every Federation plugin call in one config program, at any position.
///
/// A bundler config holds its plugin list in a literal array, in a nested array,
/// in a variable, under a tool-specific key, or inside a hook that receives the
/// config. One walk covers all of them, and the accept gate stays the callee name
/// plus an options object that declares a Federation key.
struct FederationCallCollector<'a, 'p> {
    program: &'a Program<'a>,
    config_path: &'p Path,
    config: FederationConfig,
    unread: Vec<UnreadDeclaration>,
    declares_key: bool,
}

impl<'a, 'p> FederationCallCollector<'a, 'p> {
    fn new(program: &'a Program<'a>, config_path: &'p Path) -> Self {
        Self {
            program,
            config_path,
            config: FederationConfig::default(),
            unread: Vec::new(),
            declares_key: false,
        }
    }

    fn read_plugin_call(&mut self, callee: &Expression<'a>, arguments: &[Argument<'a>]) {
        let Some(callee_name) = federation_callee_name(callee) else {
            return;
        };
        let Some(argument) = arguments.first().and_then(Argument::as_expression) else {
            return;
        };
        let mut options = ResolvedOptions::default();
        if !resolve_options(self.program, self.config_path, argument, 0, &mut options) {
            return;
        }
        self.merge(options, callee_name != AMBIGUOUS_CALLEE);
    }

    /// Take what one options value declares.
    ///
    /// The shape gate applies to the whole value: a call whose options declare
    /// no Federation key registers nothing, so a same-named local symbol does
    /// not activate extraction. The one exception is an unread part (a spread,
    /// an import target or an unrecognized call) in the options of a
    /// `federation_specific` source, which names Module Federation beyond
    /// doubt. A spread or an import that is not readable can hold each key the
    /// readable part does not declare, so it is recorded against each of those
    /// keys. An unrecognized call can change each key it receives, so it is
    /// recorded against each key its argument declares, or against both keys
    /// when the options declare none. For the ambiguous `federation` callee,
    /// options that declare only `shared` still get their package credit, but
    /// an unread part records nothing, because `shared` alone does not show
    /// that the call is Module Federation.
    fn merge(&mut self, options: ResolvedOptions, federation_specific: bool) {
        let has_unread_part =
            options.unreadable_spread || options.unreadable_import || options.unrecognized_call;
        if options.declared.is_empty() && !(has_unread_part && federation_specific) {
            return;
        }
        self.declares_key |= !options.declared.is_empty();
        for target in options.config.exposed_targets {
            push_unique(&mut self.config.exposed_targets, target);
        }
        for package in options.config.exposed_packages {
            push_unique(&mut self.config.exposed_packages, package);
        }
        for alias in options.config.remote_aliases {
            push_unique(&mut self.config.remote_aliases, alias);
        }
        for package in options.config.shared_packages {
            push_unique(&mut self.config.shared_packages, package);
        }
        for declaration in options.unread {
            push_unique(&mut self.unread, declaration);
        }
        let declares_diagnosed_key = FederationKey::DIAGNOSED
            .iter()
            .any(|key| options.declared.contains(key));
        // `shared` alone names Module Federation no better than an empty
        // object: other libraries name a function `federation`, so only
        // `exposes` or `remotes` lets an unread part of such a call record.
        if !federation_specific && !declares_diagnosed_key {
            return;
        }
        for key in FederationKey::DIAGNOSED {
            let declared = options.declared.contains(&key);
            let reasons = [
                (
                    options.unrecognized_keys.contains(&key)
                        || (options.unrecognized_call && !declares_diagnosed_key),
                    UnreadReason::UnrecognizedCall,
                ),
                (
                    options.unreadable_import && !declared,
                    UnreadReason::ImportTargetUnreadable,
                ),
                (options.unreadable_spread && !declared, UnreadReason::Spread),
            ];
            for (applies, reason) in reasons {
                if applies {
                    push_unique(&mut self.unread, UnreadDeclaration { key, reason });
                }
            }
        }
    }
}

/// How many steps of indirection the options resolver follows. A binding, a
/// spread, an `Object.assign` argument and an import are one step each.
const MAX_OPTIONS_DEPTH: usize = 4;

/// What one Federation options value declares, read from every object literal
/// the value resolves to.
#[derive(Debug, Default)]
struct ResolvedOptions {
    config: FederationConfig,
    unread: Vec<UnreadDeclaration>,
    /// The Federation keys the readable part declares.
    declared: Vec<FederationKey>,
    /// Whether a spread or an `Object.assign` argument did not resolve, so the
    /// value can declare more than what was read.
    unreadable_spread: bool,
    /// Whether a followed relative import or `require` target could not be
    /// read.
    unreadable_import: bool,
    /// Whether the options pass through a call that is not a known identity
    /// wrapper, so what was read is a lower bound.
    unrecognized_call: bool,
    /// The Federation keys that the argument of an unrecognized call declares.
    unrecognized_keys: Vec<FederationKey>,
}

impl ResolvedOptions {
    /// Take what a nested resolution read.
    fn absorb(&mut self, other: Self) {
        for target in other.config.exposed_targets {
            push_unique(&mut self.config.exposed_targets, target);
        }
        for package in other.config.exposed_packages {
            push_unique(&mut self.config.exposed_packages, package);
        }
        for alias in other.config.remote_aliases {
            push_unique(&mut self.config.remote_aliases, alias);
        }
        for package in other.config.shared_packages {
            push_unique(&mut self.config.shared_packages, package);
        }
        for declaration in other.unread {
            push_unique(&mut self.unread, declaration);
        }
        for key in other.declared {
            push_unique(&mut self.declared, key);
        }
        for key in other.unrecognized_keys {
            push_unique(&mut self.unrecognized_keys, key);
        }
        self.unreadable_spread |= other.unreadable_spread;
        self.unreadable_import |= other.unreadable_import;
        self.unrecognized_call |= other.unrecognized_call;
    }
}

/// Read every object literal that an options expression resolves to: an object
/// literal, a top-level binding of the same file, a relative ESM import or
/// `require`, a spread of one of these, `Object.assign(...)` over them, and the
/// argument of a wrapper call.
///
/// Returns `false` when the expression itself does not resolve. A package
/// `require` does not resolve. A relative import or `require` whose target
/// cannot be read resolves, and is recorded as unreadable.
fn resolve_options(
    program: &Program<'_>,
    path: &Path,
    expr: &Expression<'_>,
    depth: usize,
    options: &mut ResolvedOptions,
) -> bool {
    if depth > MAX_OPTIONS_DEPTH {
        return false;
    }
    match unwrap_expression(expr) {
        Expression::ObjectExpression(object) => {
            read_options_object(program, path, object, depth, options);
            true
        }
        Expression::CallExpression(call) if config_parser::is_require_call(call) => {
            resolve_required_options(path, call, depth, options)
        }
        Expression::CallExpression(call) if is_object_assign(&call.callee) => {
            for argument in &call.arguments {
                let resolved = argument.as_expression().is_some_and(|argument| {
                    resolve_options(program, path, argument, depth + 1, options)
                });
                options.unreadable_spread |= !resolved;
            }
            true
        }
        Expression::CallExpression(call) => {
            resolve_wrapped_options(program, path, unwrap_expression(expr), call, depth, options)
        }
        Expression::Identifier(identifier) => {
            resolve_options_name(program, path, &identifier.name, depth, options)
        }
        _ => false,
    }
}

/// Read the options a wrapper call receives.
///
/// A known identity wrapper passes its argument through unchanged. Any other
/// call can add to or change what it returns, so the object literal passed to
/// it is read as a lower bound and the call is recorded. A call with no
/// readable argument does not resolve.
fn resolve_wrapped_options(
    program: &Program<'_>,
    path: &Path,
    expr: &Expression<'_>,
    call: &CallExpression<'_>,
    depth: usize,
    options: &mut ResolvedOptions,
) -> bool {
    // Resolve the argument on its own, so the keys it declares are known.
    let mut received = ResolvedOptions::default();
    let resolved = call
        .arguments
        .first()
        .and_then(Argument::as_expression)
        .is_some_and(|argument| resolve_options(program, path, argument, depth + 1, &mut received))
        || config_parser::extract_object_from_expression(expr).is_some_and(|object| {
            read_options_object(program, path, object, depth + 1, &mut received);
            true
        });
    if !resolved {
        return false;
    }
    if !is_identity_wrapper(&call.callee) {
        received.unrecognized_call = true;
        received.unrecognized_keys.clone_from(&received.declared);
    }
    options.absorb(received);
    true
}

/// Whether a callee is a known identity wrapper, called by name or as a
/// member.
fn is_identity_wrapper(callee: &Expression<'_>) -> bool {
    let name = match unwrap_expression(callee) {
        Expression::Identifier(identifier) => identifier.name.as_str(),
        Expression::StaticMemberExpression(member) => member.property.name.as_str(),
        _ => return false,
    };
    IDENTITY_WRAPPERS.contains(&name)
}

/// Read the declarations of one options object literal, and follow each spread
/// in it.
fn read_options_object(
    program: &Program<'_>,
    path: &Path,
    object: &ObjectExpression<'_>,
    depth: usize,
    options: &mut ResolvedOptions,
) {
    for key in [
        FederationKey::Exposes,
        FederationKey::Remotes,
        FederationKey::Shared,
    ] {
        if config_parser::property_expr(object, key.name()).is_some() {
            push_unique(&mut options.declared, key);
        }
    }
    read_exposes(object, &mut options.config, &mut options.unread);
    read_remotes(object, &mut options.config, &mut options.unread);
    read_shared(object, &mut options.config);
    for property in &object.properties {
        if let ObjectPropertyKind::SpreadProperty(spread) = property {
            let resolved = resolve_options(program, path, &spread.argument, depth + 1, options);
            options.unreadable_spread |= !resolved;
        }
    }
}

/// Resolve a name to its options: a stable top-level binding of the same file
/// first, then a relative ESM import.
fn resolve_options_name(
    program: &Program<'_>,
    path: &Path,
    name: &str,
    depth: usize,
    options: &mut ResolvedOptions,
) -> bool {
    if let Some(init) = config_parser::find_stable_binding_init(program, name) {
        return resolve_options_init(program, path, init, depth + 1, options);
    }
    let Some((specifier, imported_name)) =
        config_parser::find_relative_import_binding(program, name)
    else {
        return false;
    };
    resolve_module_options(path, &specifier, imported_name.as_deref(), depth, options)
}

/// Record a followed import target that could not be read. The import is
/// still a resolved value: what it holds is unknown, not absent.
fn record_unreadable_import(resolved: bool, options: &mut ResolvedOptions) -> bool {
    options.unreadable_import |= !resolved;
    true
}

/// Resolve the options a relative `require('./x')` names: the value that module
/// exports as a whole. A package `require` does not resolve, and a relative
/// target that cannot be read is recorded.
fn resolve_required_options(
    path: &Path,
    call: &CallExpression<'_>,
    depth: usize,
    options: &mut ResolvedOptions,
) -> bool {
    let Some(specifier) = config_parser::get_require_source(call)
        .filter(|specifier| config_parser::is_relative_specifier(specifier))
    else {
        return false;
    };
    resolve_module_options(path, &specifier, None, depth, options)
}

/// Read the options a relative sibling module exports: under `export_name`,
/// or as the whole module when `export_name` is `None`. A target that cannot
/// be read is recorded, and the value still counts as resolved.
fn resolve_module_options(
    path: &Path,
    specifier: &str,
    export_name: Option<&str>,
    depth: usize,
    options: &mut ResolvedOptions,
) -> bool {
    let Some((module_path, source)) = config_parser::resolve_sibling_module(path, specifier) else {
        return record_unreadable_import(false, options);
    };
    let resolved = config_parser::extract_from_source(&source, &module_path, |module| {
        let init = match export_name {
            Some(name) => config_parser::find_exported_init(module, Some(name))?,
            None => config_parser::find_module_export_expression(module)?,
        };
        resolve_options_init(module, &module_path, init, depth + 1, options).then_some(())
    })
    .is_some();
    record_unreadable_import(resolved, options)
}

/// Resolve the value a binding or an export holds. Beyond the shapes of
/// [`resolve_options`], this accepts a function that returns the options.
fn resolve_options_init(
    program: &Program<'_>,
    path: &Path,
    init: &Expression<'_>,
    depth: usize,
    options: &mut ResolvedOptions,
) -> bool {
    if resolve_options(program, path, init, depth, options) {
        return true;
    }
    let Some(object) = config_parser::extract_object_from_expression(init) else {
        return false;
    };
    read_options_object(program, path, object, depth, options);
    true
}

/// Whether a callee is `Object.assign`.
fn is_object_assign(callee: &Expression<'_>) -> bool {
    matches!(
        unwrap_expression(callee),
        Expression::StaticMemberExpression(member)
            if member.property.name == "assign"
                && matches!(&member.object, Expression::Identifier(object) if object.name == "Object")
    )
}

impl<'a> Visit<'a> for FederationCallCollector<'a, '_> {
    fn visit_new_expression(&mut self, new_expression: &NewExpression<'a>) {
        self.read_plugin_call(&new_expression.callee, &new_expression.arguments);
        walk::walk_new_expression(self, new_expression);
    }

    fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
        self.read_plugin_call(&call.callee, &call.arguments);
        walk::walk_call_expression(self, call);
    }
}

fn read_exposes(
    options: &ObjectExpression<'_>,
    config: &mut FederationConfig,
    unread: &mut Vec<UnreadDeclaration>,
) {
    let mut has_unread_entry = false;
    for declaration in federation_key_declarations(options, FederationKey::Exposes, unread) {
        let mapping = match declaration {
            KeyDeclaration::Target(target) => {
                classify_exposed_target(&target, config);
                continue;
            }
            KeyDeclaration::Mapping(mapping) => mapping,
        };
        for property in &mapping.properties {
            let ObjectPropertyKind::ObjectProperty(property) = property else {
                continue;
            };
            let targets = exposed_target_strings(&property.value);
            if targets.is_empty() {
                has_unread_entry = true;
                continue;
            }
            for target in targets {
                classify_exposed_target(&target, config);
            }
        }
    }
    if has_unread_entry {
        push_unique(
            unread,
            UnreadDeclaration {
                key: FederationKey::Exposes,
                reason: UnreadReason::Entries,
            },
        );
    }
}

/// Read the target strings of one `exposes` entry, accepting a string, a
/// template literal, an array, and the entry descriptor `{ import: ... }`.
fn exposed_target_strings(value: &Expression<'_>) -> Vec<String> {
    match config_parser::object_expression(value) {
        Some(descriptor) => config_parser::property_expr(descriptor, "import")
            .map(config_parser::expression_to_string_or_array)
            .unwrap_or_default(),
        None => config_parser::expression_to_string_or_array(value),
    }
}

/// Split an exposed target into a local path and a bare module request.
///
/// A target without a leading `./` and without a source extension is a module
/// request, which is how a bundler resolves it: an entry glob would match no
/// file, while the package still needs dependency credit.
fn classify_exposed_target(target: &str, config: &mut FederationConfig) {
    let trimmed = target.trim();
    if trimmed.is_empty() {
        return;
    }
    if let Some(request) = super::module_request(trimmed) {
        push_unique(
            &mut config.exposed_packages,
            crate::resolve::extract_package_name(request),
        );
        return;
    }
    push_unique(&mut config.exposed_targets, trimmed.to_string());
}

fn read_remotes(
    options: &ObjectExpression<'_>,
    config: &mut FederationConfig,
    unread: &mut Vec<UnreadDeclaration>,
) {
    for declaration in federation_key_declarations(options, FederationKey::Remotes, unread) {
        let KeyDeclaration::Mapping(mapping) = declaration else {
            continue;
        };
        for property in &mapping.properties {
            let ObjectPropertyKind::ObjectProperty(property) = property else {
                continue;
            };
            if let Some(alias) = property_key_name(&property.key)
                && is_bare_specifier(&alias)
            {
                push_unique(&mut config.remote_aliases, alias);
            }
        }
    }
}

/// Read the packages that `shared` names.
///
/// The object form names a package with each key, and an entry descriptor can
/// name the module request it provides with `import` and the package that
/// holds its version with `packageName`. The array form names a package with
/// each string element, and an object element is read as the object form. A
/// key with a trailing `/` shares every subpath of the package, which credits
/// the same package. Only a bare package specifier gets credit: a relative
/// path shares a project module, which is no dependency.
///
/// Credit stays a lower bound. A value the reader cannot read gives no credit
/// and no diagnostic, so the package reports as unused as it did before.
fn read_shared(options: &ObjectExpression<'_>, config: &mut FederationConfig) {
    let Some(value) = config_parser::property_expr(options, FederationKey::Shared.name()) else {
        return;
    };
    if let Some(mapping) = config_parser::object_expression(value) {
        read_shared_mapping(mapping, config);
        return;
    }
    let Some(array) = config_parser::array_expression(value) else {
        return;
    };
    for element in &array.elements {
        let Some(expr) = element.as_expression() else {
            continue;
        };
        if let Some(mapping) = config_parser::object_expression(expr) {
            read_shared_mapping(mapping, config);
        } else if let Some(request) = config_parser::expression_to_string(expr) {
            push_shared_package(&request, config);
        }
    }
}

fn read_shared_mapping(mapping: &ObjectExpression<'_>, config: &mut FederationConfig) {
    for property in &mapping.properties {
        let ObjectPropertyKind::ObjectProperty(property) = property else {
            continue;
        };
        if let Some(key) = property_key_name(&property.key) {
            push_shared_package(&key, config);
        }
        let Some(descriptor) = config_parser::object_expression(&property.value) else {
            continue;
        };
        for field in ["import", "packageName"] {
            if let Some(request) = config_parser::property_expr(descriptor, field)
                .and_then(config_parser::expression_to_string)
            {
                push_shared_package(&request, config);
            }
        }
    }
}

fn push_shared_package(request: &str, config: &mut FederationConfig) {
    let request = request.trim();
    if !is_bare_specifier(request) {
        return;
    }
    push_unique(
        &mut config.shared_packages,
        crate::resolve::extract_package_name(request),
    );
}

/// One readable declaration under a Federation key.
enum KeyDeclaration<'a> {
    /// An object literal that maps a public name to a target.
    Mapping(&'a ObjectExpression<'a>),
    /// A single target, from the array form. A bundler uses the element both as
    /// the public name and as the module request.
    Target(String),
}

/// Resolve one Federation key to the declarations it holds, recording why the
/// declaration is not fully readable when that is the case.
///
/// The object form gives one mapping. The array form gives one declaration per
/// element, except under `remotes`, whose array form stays unread: a bundler
/// derives the request scope of an element from the whole container location,
/// which is never a bare specifier a provider rule can cover.
fn federation_key_declarations<'a>(
    options: &'a ObjectExpression<'a>,
    key: FederationKey,
    unread: &mut Vec<UnreadDeclaration>,
) -> Vec<KeyDeclaration<'a>> {
    let Some(value) = config_parser::property_expr(options, key.name()) else {
        return Vec::new();
    };
    if let Some(mapping) = config_parser::object_expression(value) {
        record_spread(mapping, key, unread);
        return vec![KeyDeclaration::Mapping(mapping)];
    }
    let Some(array) = config_parser::array_expression(value) else {
        push_unique(
            unread,
            UnreadDeclaration {
                key,
                reason: UnreadReason::NotObjectLiteral,
            },
        );
        return Vec::new();
    };
    if key == FederationKey::Remotes {
        push_unique(
            unread,
            UnreadDeclaration {
                key,
                reason: UnreadReason::ArrayForm,
            },
        );
        return Vec::new();
    }

    let mut declarations = Vec::new();
    let mut has_unread_element = false;
    for element in &array.elements {
        let Some(expr) = element.as_expression() else {
            has_unread_element = true;
            continue;
        };
        if let Some(mapping) = config_parser::object_expression(expr) {
            record_spread(mapping, key, unread);
            declarations.push(KeyDeclaration::Mapping(mapping));
            continue;
        }
        // A bundler reads an element as one module request. A glob and a nested
        // array are neither a request nor a mapping, so each one is unread
        // rather than a literal path.
        let target = config_parser::expression_to_string(expr)
            .filter(|target| !super::has_glob_syntax(target));
        let Some(target) = target else {
            has_unread_element = true;
            continue;
        };
        declarations.push(KeyDeclaration::Target(target));
    }
    if has_unread_element {
        push_unique(
            unread,
            UnreadDeclaration {
                key,
                reason: UnreadReason::Entries,
            },
        );
    }
    declarations
}

/// Record that a mapping spreads a value, which means it may declare more than
/// what was read.
fn record_spread(
    mapping: &ObjectExpression<'_>,
    key: FederationKey,
    unread: &mut Vec<UnreadDeclaration>,
) {
    if mapping
        .properties
        .iter()
        .any(|property| matches!(property, ObjectPropertyKind::SpreadProperty(_)))
    {
        push_unique(
            unread,
            UnreadDeclaration {
                key,
                reason: UnreadReason::Spread,
            },
        );
    }
}

/// The Federation callee name of a call, or `None` for any other callee.
fn federation_callee_name<'a>(callee: &'a Expression<'a>) -> Option<&'a str> {
    let name = match unwrap_expression(callee) {
        Expression::Identifier(identifier) => identifier.name.as_str(),
        Expression::StaticMemberExpression(member) => member.property.name.as_str(),
        Expression::ComputedMemberExpression(member) => match unwrap_expression(&member.expression)
        {
            Expression::StringLiteral(literal) => literal.value.as_str(),
            _ => return None,
        },
        _ => return None,
    };
    FEDERATION_CALLEES.contains(&name).then_some(name)
}

fn unwrap_expression<'a>(expr: &'a Expression<'a>) -> &'a Expression<'a> {
    match expr {
        Expression::ParenthesizedExpression(paren) => unwrap_expression(&paren.expression),
        Expression::TSAsExpression(ts_as) => unwrap_expression(&ts_as.expression),
        Expression::TSSatisfiesExpression(ts_satisfies) => {
            unwrap_expression(&ts_satisfies.expression)
        }
        Expression::TSNonNullExpression(non_null) => unwrap_expression(&non_null.expression),
        _ => expr,
    }
}

fn property_key_name(key: &PropertyKey<'_>) -> Option<String> {
    match key {
        PropertyKey::StaticIdentifier(identifier) => Some(identifier.name.to_string()),
        PropertyKey::StringLiteral(literal) => Some(literal.value.to_string()),
        _ => None,
    }
}

/// Whether a name is a bare specifier. A remote alias needs this form because
/// it is the only one a provider rule can cover, and a shared entry needs it
/// because only a package name gets dependency credit.
fn is_bare_specifier(name: &str) -> bool {
    config_parser::is_package_specifier(name) && !name.starts_with('.')
}

fn push_unique<T: PartialEq>(values: &mut Vec<T>, value: T) {
    if !values.contains(&value) {
        values.push(value);
    }
}

/// Reason token for a runtime call whose argument is not a static literal.
const DYNAMIC_ARGUMENT: &str = "dynamic-argument";

/// What the Federation runtime calls of the analyzed source files declare.
#[derive(Debug, Default)]
pub struct RuntimeRemotes {
    /// One provider rule per remote a literal call names, scoped to the
    /// workspace of the file that makes the call.
    pub rules: Vec<ProvidedDependencyRule>,
    /// One advisory per file and runtime function that receives an argument
    /// that is not a static literal.
    pub diagnostics: Vec<super::PluginConfigDiagnostic>,
}

/// Turn the Federation runtime facts that extraction read into provider rules
/// and advisories.
///
/// A literal `registerRemotes` or `loadRemote` call names a remote the same way
/// a `remotes` config entry does, so it gets the same rule: the alias and its
/// subpaths are provided inside the declaring package. The package is the
/// workspace that holds the file, or the whole project outside a workspace.
pub fn runtime_remotes<'a>(
    sources: impl IntoIterator<Item = (&'a Path, &'a [fallow_types::extract::SemanticFact])>,
    root: &Path,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> RuntimeRemotes {
    let mut remotes = RuntimeRemotes::default();
    for (path, facts) in sources {
        let mut scope = None;
        for fact in facts {
            let fallow_types::extract::SemanticFact::FederationRuntimeRemote(fact) = fact else {
                continue;
            };
            let Some(remote) = &fact.remote else {
                let diagnostic = super::PluginConfigDiagnostic::unreadable(
                    path,
                    "module-federation",
                    fact.call.name(),
                    DYNAMIC_ARGUMENT,
                );
                push_unique(&mut remotes.diagnostics, diagnostic);
                continue;
            };
            let scope = scope.get_or_insert_with(|| runtime_scope(path, root, workspaces));
            let rule = ProvidedDependencyRule::new(
                scope.clone(),
                [remote.clone()],
                [format!("{remote}/")],
            );
            push_unique(&mut remotes.rules, rule);
        }
    }
    remotes
}

/// Glob covering the workspace that holds `path`, or the whole project when no
/// workspace holds it.
fn runtime_scope(path: &Path, root: &Path, workspaces: &[fallow_config::WorkspaceInfo]) -> String {
    workspaces
        .iter()
        .filter(|workspace| path.starts_with(&workspace.root))
        .max_by_key(|workspace| workspace.root.components().count())
        .and_then(|workspace| workspace.root.strip_prefix(root).ok())
        .map(config_parser::path_to_config_string)
        .filter(|directory| !directory.is_empty())
        .map_or_else(
            || SCOPE_SUFFIX.to_string(),
            |directory| format!("{directory}/{SCOPE_SUFFIX}"),
        )
}

define_plugin! {
    struct ModuleFederationPlugin => "module-federation",
    enablers: ENABLERS,
    config_patterns: CONFIG_PATTERNS,
    always_used: ALWAYS_USED,
    resolve_config(config_path, source, root) {
        let mut result = PluginResult::default();
        super::add_import_referenced_dependencies(&mut result, source, config_path);

        let location = ConfigLocation {
            config_path,
            source_path: config_path,
            root,
            context: None,
            package_dir: None,
        };
        // The declared `always_used` pattern is matched against the
        // project-relative path without a `**/` rewrite, so it covers a root
        // config only. Credit the file that was actually read, at any depth.
        if let Some(relative) = location.relative_config_path() {
            result.always_used_files.push(globset::escape(&relative));
        }

        let declares_key = apply_from_source(
            &mut result,
            source,
            &location,
            "module-federation",
            &FederationSites {
                read_plugin_calls: false,
                read_config_object: true,
            },
        );
        if declares_key {
            result
                .referenced_dependencies
                .extend(BUILD_PLUGIN_ENABLERS.iter().map(|name| (*name).to_string()));
        }

        result
    }
}

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

    const CONFIG: &str = "/project/module-federation.config.ts";
    const ROOT: &str = "/project";

    fn resolve(source: &str) -> PluginResult {
        ModuleFederationPlugin.resolve_config(Path::new(CONFIG), source, Path::new(ROOT))
    }

    fn entry_patterns(result: &PluginResult) -> Vec<String> {
        result
            .entry_patterns
            .iter()
            .map(|rule| rule.pattern.clone())
            .collect()
    }

    /// Compile an entry pattern the way `CompiledPathRule::for_entry_rule` does,
    /// so a test observes the paths a pattern really covers.
    fn covers(pattern: &str, path: &str) -> bool {
        globset::GlobBuilder::new(pattern)
            .literal_separator(true)
            .build()
            .expect("entry pattern compiles")
            .compile_matcher()
            .is_match(path)
    }

    fn standalone(source: &str) -> (FederationConfig, Vec<UnreadDeclaration>) {
        read(
            source,
            Path::new(CONFIG),
            &FederationSites {
                read_plugin_calls: false,
                read_config_object: true,
            },
        )
    }

    /// Read a bundler config the way every bundler plugin does: plugin calls
    /// only, wherever they sit.
    fn bundler(source: &str) -> (FederationConfig, Vec<UnreadDeclaration>) {
        read(
            source,
            Path::new("webpack.config.js"),
            &FederationSites {
                read_plugin_calls: true,
                read_config_object: false,
            },
        )
    }

    #[test]
    fn exposes_string_target_becomes_entry_pattern() {
        let result = resolve(
            r"
            import { createModuleFederationConfig } from '@module-federation/enhanced';
            export default createModuleFederationConfig({
                name: 'checkout',
                exposes: { './Button': './src/components/Button.tsx' },
            });
            ",
        );
        assert_eq!(entry_patterns(&result), vec!["src/components/Button.tsx"]);
        assert!(
            result
                .referenced_dependencies
                .contains(&"@module-federation/enhanced".to_string())
        );
    }

    #[test]
    fn exposes_import_descriptor_becomes_entry_pattern() {
        let result = resolve(
            r"
            export default {
                exposes: { './Button': { import: './src/components/Button.tsx' } },
            };
            ",
        );
        assert_eq!(entry_patterns(&result), vec!["src/components/Button.tsx"]);
    }

    #[test]
    fn extensionless_exposes_target_expands_file_and_directory_index() {
        let result = resolve(r"export default { exposes: { './Button': './src/Button' } };");
        assert_eq!(
            entry_patterns(&result),
            vec![
                format!("src/Button.{EXPOSE_EXTENSIONS}"),
                format!("src/Button/index.{EXPOSE_EXTENSIONS}"),
            ]
        );
    }

    #[test]
    fn bracketed_target_covers_the_exposed_file_only() {
        let result = resolve(r"export default { exposes: { './Page': './src/pages/[id].tsx' } };");
        let patterns = entry_patterns(&result);
        assert_eq!(patterns.len(), 1, "got {patterns:?}");
        assert!(
            covers(&patterns[0], "src/pages/[id].tsx"),
            "the exposed file is covered, got {patterns:?}"
        );
        assert!(
            !covers(&patterns[0], "src/pages/d.tsx"),
            "a bracket is not a character class, got {patterns:?}"
        );
    }

    #[test]
    fn wildcard_target_does_not_cover_files_the_config_does_not_name() {
        let result = resolve(r"export default { exposes: { './all': './src/*' } };");
        let patterns = entry_patterns(&result);
        assert!(
            !patterns
                .iter()
                .any(|pattern| covers(pattern, "src/unrelated.ts")),
            "got {patterns:?}"
        );
        assert!(
            patterns.iter().any(|pattern| covers(pattern, "src/*.ts")),
            "a file literally named `*` is still covered, got {patterns:?}"
        );
    }

    #[test]
    fn a_target_naming_a_discovered_extension_is_used_as_written() {
        let result = resolve(r"export default { exposes: { './Button': './src/Button.gts' } };");
        assert_eq!(entry_patterns(&result), vec!["src/Button.gts"]);
    }

    #[test]
    fn bare_module_request_target_is_credited_as_dependency() {
        let result = resolve(r"export default { exposes: { './utils': 'shared-utils' } };");
        assert!(entry_patterns(&result).is_empty());
        assert!(
            result
                .package_referenced_dependencies
                .iter()
                .any(|(_, package)| package == "shared-utils")
        );
        assert!(
            !result
                .referenced_dependencies
                .contains(&"shared-utils".to_string())
        );
    }

    #[test]
    fn target_outside_the_project_root_matches_no_project_file() {
        let result = resolve(r"export default { exposes: { './Button': '../other/Button.tsx' } };");
        let patterns = entry_patterns(&result);
        assert_eq!(patterns, vec!["../other/Button.tsx".to_string()]);
        assert!(!covers(&patterns[0], "other/Button.tsx"));
    }

    #[test]
    fn remote_alias_covers_the_alias_and_its_subpaths_only() {
        let result = resolve(
            r"
            export default {
                remotes: { checkout: 'checkout@https://example.test/remoteEntry.js' },
            };
            ",
        );
        let rules = &result.provided_dependencies;
        assert_eq!(rules.len(), 1);
        let rule = &rules[0];
        assert!(rule.covers_specifier("checkout"));
        assert!(rule.covers_specifier("checkout/Button"));
        assert!(!rule.covers_specifier("checkout-ui"));
        assert!(rule.may_cover_package("checkout"));
    }

    #[test]
    fn remote_rule_is_scoped_to_the_directory_that_declared_it() {
        let source = r"
            export default {
                remotes: { checkout: 'checkout@https://example.test/remoteEntry.js' },
            };
        ";
        let nested = ModuleFederationPlugin.resolve_config(
            Path::new("/project/packages/host/module-federation.config.ts"),
            source,
            Path::new("/project"),
        );
        assert_eq!(
            nested.provided_dependencies[0].path.pattern,
            format!("packages/host/{SCOPE_SUFFIX}")
        );

        let at_root = resolve(source);
        assert_eq!(at_root.provided_dependencies[0].path.pattern, SCOPE_SUFFIX);
    }

    #[test]
    fn remote_external_descriptor_still_yields_the_alias() {
        let result = resolve(
            r"
            export default {
                remotes: {
                    remote: { external: 'app@http://example.test/remoteEntry.js', shareScope: 'default' },
                },
            };
            ",
        );
        assert_eq!(result.provided_dependencies.len(), 1);
        assert!(result.provided_dependencies[0].covers_specifier("remote/Thing"));
    }

    #[test]
    fn common_js_config_reads_both_keys() {
        let result = resolve(
            r"
            module.exports = {
                exposes: { './Button': './src/Button.tsx' },
                remotes: { checkout: 'checkout@https://example.test/remoteEntry.js' },
            };
            ",
        );
        assert_eq!(entry_patterns(&result), vec!["src/Button.tsx"]);
        assert_eq!(result.provided_dependencies.len(), 1);
    }

    fn unread(key: FederationKey, reason: UnreadReason) -> Vec<UnreadDeclaration> {
        vec![UnreadDeclaration { key, reason }]
    }

    #[test]
    fn computed_exposes_reports_the_key_and_keeps_literal_siblings() {
        let (config, declarations) =
            standalone(r"export default { exposes: computeExposes(), remotes: {} };");
        assert!(config.exposed_targets.is_empty());
        assert_eq!(
            declarations,
            unread(FederationKey::Exposes, UnreadReason::NotObjectLiteral)
        );

        let (config, declarations) = standalone(
            r"
            export default {
                exposes: { './a': './src/a.ts', ...extraExposes },
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/a.ts".to_string()]);
        assert_eq!(
            declarations,
            unread(FederationKey::Exposes, UnreadReason::Spread)
        );
    }

    #[test]
    fn an_entry_whose_target_is_not_readable_is_reported_once_beside_its_siblings() {
        let (config, declarations) = standalone(
            r"
            const widget = './src/Widget.tsx';
            export default {
                exposes: {
                    './Button': './src/Button.tsx',
                    './Widget': widget,
                    './Card': { name: 'card' },
                },
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
        assert_eq!(
            declarations,
            unread(FederationKey::Exposes, UnreadReason::Entries),
            "two unreadable entries under one key are one advisory"
        );
    }

    /// A bundler uses a string element of the `exposes` array both as the public
    /// name and as the module request, so the element is a target.
    #[test]
    fn exposes_array_form_reads_string_elements() {
        let (config, declarations) =
            standalone(r"export default { exposes: ['./src/Button.tsx', 'shared-utils'] };");
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
        assert_eq!(config.exposed_packages, vec!["shared-utils".to_string()]);
        assert!(declarations.is_empty(), "got {declarations:?}");
    }

    /// An object element of the array goes through the same mapping reader as
    /// the object form, entry descriptor included.
    #[test]
    fn exposes_array_form_reads_object_elements() {
        let (config, declarations) = standalone(
            r"
            export default {
                exposes: [
                    { './Button': './src/Button.tsx' },
                    { './Card': { import: './src/Card.tsx' } },
                ],
            };
            ",
        );
        assert_eq!(
            config.exposed_targets,
            vec!["./src/Button.tsx".to_string(), "./src/Card.tsx".to_string()]
        );
        assert!(declarations.is_empty(), "got {declarations:?}");
    }

    /// A bundler reads an `exposes` element as one module request. An element
    /// that holds glob syntax, a nested array or a non-string value is not a
    /// request, so the advisory names the key instead of a literal path.
    #[test]
    fn exposes_array_elements_that_are_not_a_request_are_reported() {
        for source in [
            r"export default { exposes: ['./src/*.tsx'] };",
            r"export default { exposes: [['./src/Button.tsx']] };",
            r"export default { exposes: [42] };",
        ] {
            let (config, declarations) = standalone(source);
            assert_eq!(config, FederationConfig::default(), "source: {source}");
            assert_eq!(
                declarations,
                unread(FederationKey::Exposes, UnreadReason::Entries),
                "source: {source}"
            );
        }
    }

    #[test]
    fn exposes_array_element_without_a_readable_target_is_reported() {
        let (config, declarations) = standalone(
            r"
            const widget = './src/Widget.tsx';
            export default { exposes: ['./src/Button.tsx', widget] };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
        assert_eq!(
            declarations,
            unread(FederationKey::Exposes, UnreadReason::Entries)
        );
    }

    /// A bundler derives the request scope of a `remotes` array element from the
    /// whole container location, which is never a bare specifier a provider rule
    /// can cover, so the array form of `remotes` stays unread.
    #[test]
    fn remotes_array_form_is_not_read() {
        let (config, declarations) = standalone(
            r"export default { remotes: ['checkout@https://example.test/remoteEntry.js'] };",
        );
        assert!(config.remote_aliases.is_empty());
        assert_eq!(
            declarations,
            unread(FederationKey::Remotes, UnreadReason::ArrayForm)
        );
    }

    /// The reader records a fact, and the shared renderer turns it into the
    /// sentence, so each shape has to reach the wire as its own token.
    #[test]
    fn each_unread_shape_carries_its_own_reason_token() {
        assert_eq!(UnreadReason::NotObjectLiteral.token(), "not-object-literal");
        assert_eq!(UnreadReason::ArrayForm.token(), "array-form");
        assert_eq!(UnreadReason::Spread.token(), "spread");
        assert_eq!(UnreadReason::Entries.token(), "unreadable-entries");
    }

    /// The advisory names the config file that was read and the plugin that
    /// read it, and the standalone reader names itself.
    #[test]
    fn an_unreadable_key_records_a_diagnostic_on_its_config_file() {
        let result = resolve(r"export default { exposes: computeExposes() };");
        assert_eq!(result.config_diagnostics.len(), 1);
        let diagnostic = &result.config_diagnostics[0];
        assert_eq!(diagnostic.config_path, Path::new(CONFIG));
        assert_eq!(diagnostic.plugin, "module-federation");
        assert_eq!(diagnostic.key, "exposes");
        assert_eq!(diagnostic.reason, "not-object-literal");
        assert_eq!(
            diagnostic.effect,
            super::super::PluginConfigEffect::Unreadable
        );
    }

    /// Two unreadable keys in one config file are two advisories: they share a
    /// kind and a path, and only the payload tells them apart.
    #[test]
    fn both_unreadable_keys_in_one_config_are_recorded() {
        let result = resolve(
            r"
            export default {
                exposes: makeExposes(),
                remotes: { ...envRemotes },
            };
            ",
        );
        let recorded: Vec<(&str, &str)> = result
            .config_diagnostics
            .iter()
            .map(|diagnostic| (diagnostic.key.as_str(), diagnostic.reason.as_str()))
            .collect();
        assert_eq!(
            recorded,
            vec![("exposes", "not-object-literal"), ("remotes", "spread")],
            "{:?}",
            result.config_diagnostics
        );
    }

    /// A config the reader understands in full records nothing, so a consumer
    /// warning on the kind warns about something.
    #[test]
    fn a_readable_config_records_no_diagnostic() {
        let result = resolve(
            r"
            export default {
                exposes: { './Button': './src/Button.tsx' },
                remotes: { checkout: 'checkout@https://example.test/remoteEntry.js' },
            };
            ",
        );
        assert!(
            result.config_diagnostics.is_empty(),
            "{:?}",
            result.config_diagnostics
        );
    }

    /// The same reader serves four bundler plugins through inline options, and
    /// the config file the user must edit is the bundler's, so the advisory
    /// names the bundler plugin rather than the reader.
    #[test]
    fn inline_bundler_options_record_under_the_bundler_plugin() {
        let mut result = PluginResult::default();
        let config_path = Path::new("/project/webpack.config.js");
        apply_bundler_plugin_options(
            &mut result,
            r"
            module.exports = {
                plugins: [new ModuleFederationPlugin({ remotes: envRemotes() })],
            };
            ",
            config_path,
            Path::new("/project"),
            FederationBase::default(),
            "webpack",
        );
        assert_eq!(result.config_diagnostics.len(), 1);
        let diagnostic = &result.config_diagnostics[0];
        assert_eq!(diagnostic.plugin, "webpack");
        assert_eq!(diagnostic.key, "remotes");
        assert_eq!(diagnostic.config_path, config_path);
    }

    /// A config whose ONLY contribution is an advisory must not be discarded by
    /// the registry's empty-result gate, which is how a bundler config with a
    /// computed `remotes` map and nothing else reaches the report.
    #[test]
    fn a_result_carrying_only_a_diagnostic_is_not_empty() {
        let mut result = PluginResult::default();
        assert!(result.is_empty());
        result
            .config_diagnostics
            .push(super::super::PluginConfigDiagnostic::unreadable(
                Path::new("/project/webpack.config.js"),
                "webpack",
                "remotes",
                "not-object-literal",
            ));
        assert!(
            !result.is_empty(),
            "the advisory is the whole contribution of this config"
        );
    }

    #[test]
    fn shorthand_remotes_property_reports_the_key() {
        let (config, declarations) = standalone(
            r"
            const remotes = { checkout: 'checkout@https://example.test/remoteEntry.js' };
            export default { remotes };
            ",
        );
        assert!(config.remote_aliases.is_empty());
        assert_eq!(
            declarations,
            unread(FederationKey::Remotes, UnreadReason::NotObjectLiteral)
        );
    }

    #[test]
    fn config_without_federation_keys_contributes_only_its_own_file() {
        let result = resolve(r"export default { name: 'checkout' };");
        assert!(entry_patterns(&result).is_empty());
        assert!(result.provided_dependencies.is_empty());
        assert!(result.referenced_dependencies.is_empty());
        assert_eq!(
            result.always_used_files,
            vec!["module-federation.config.ts".to_string()]
        );
    }

    #[test]
    fn a_nested_config_file_is_credited_as_used() {
        let nested = ModuleFederationPlugin.resolve_config(
            Path::new("/project/packages/host/module-federation.config.ts"),
            r"export default { exposes: { './Button': './src/Button.tsx' } };",
            Path::new("/project"),
        );
        assert_eq!(
            nested.always_used_files,
            vec!["packages/host/module-federation.config.ts".to_string()]
        );
    }

    #[test]
    fn inline_plugin_options_are_read_from_a_plugins_array() {
        let (config, computed) = bundler(
            r"
            const { ModuleFederationPlugin } = require('webpack').container;
            module.exports = {
                plugins: [
                    new ModuleFederationPlugin({
                        name: 'host',
                        exposes: { './Button': './src/Button.tsx' },
                        remotes: { checkout: 'checkout@https://example.test/remoteEntry.js' },
                    }),
                ],
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
        assert_eq!(config.remote_aliases, vec!["checkout".to_string()]);
        assert!(computed.is_empty());
    }

    #[test]
    fn member_expression_callee_is_recognised() {
        let (config, _) = bundler(
            r"
            module.exports = {
                plugins: [
                    new webpack.container.ModuleFederationPlugin({
                        exposes: { './B': './src/B.tsx' },
                    }),
                ],
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/B.tsx".to_string()]);
    }

    /// Vite flattens a nested plugin array, so a Federation call one level down
    /// is part of the same build.
    #[test]
    fn federation_options_in_a_nested_plugin_array_are_read() {
        let (config, computed) = bundler(
            r"
            export default defineConfig({
                plugins: [
                    [react(), federation({ exposes: { './Button': './src/Button.tsx' } })],
                    other(),
                ],
            });
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
        assert!(computed.is_empty(), "got {computed:?}");
    }

    /// A Next.js config registers the plugin inside the `webpack(config)` hook,
    /// which no config-object path reaches.
    #[test]
    fn federation_options_outside_the_plugins_array_are_read() {
        let (config, computed) = bundler(
            r"
            module.exports = {
                webpack(config, options) {
                    config.plugins.push(
                        new NextFederationPlugin({
                            name: 'shop',
                            exposes: { './pages-map': './pages-map.js' },
                        }),
                    );
                    return config;
                },
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./pages-map.js".to_string()]);
        assert!(computed.is_empty(), "got {computed:?}");
    }

    #[test]
    fn federation_options_from_a_plugins_identifier_are_read() {
        let (config, _) = bundler(
            r"
            const plugins = [
                new ModuleFederationPlugin({ exposes: { './Button': './src/Button.tsx' } }),
            ];
            module.exports = { plugins };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
    }

    /// An rsbuild config holds its rspack plugin list under `tools.rspack`.
    #[test]
    fn federation_options_under_a_tool_key_are_read() {
        let (config, _) = bundler(
            r"
            export default {
                tools: {
                    rspack: {
                        plugins: [
                            new ModuleFederationPlugin({
                                exposes: { './Button': './src/Button.tsx' },
                            }),
                        ],
                    },
                },
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
    }

    /// Options held by a `const` above the plugin list are the most common real
    /// shape, so the reader resolves a same-file binding.
    #[test]
    fn federation_options_bound_to_a_local_const_are_read() {
        let (config, computed) = bundler(
            r"
            const mfConfig = {
                name: 'host',
                exposes: { './Button': './src/Button.tsx' },
                remotes: { checkout: 'checkout@https://example.test/remoteEntry.js' },
            };
            module.exports = {
                plugins: [new ModuleFederationPlugin(mfConfig)],
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
        assert_eq!(config.remote_aliases, vec!["checkout".to_string()]);
        assert!(computed.is_empty(), "got {computed:?}");
    }

    /// Two calls at two positions that share one options `const` register one
    /// target.
    #[test]
    fn two_calls_that_share_one_options_const_register_one_target() {
        let (config, _) = bundler(
            r"
            const mfConfig = { exposes: { './Button': './src/Button.tsx' } };
            module.exports = {
                plugins: [new ModuleFederationPlugin(mfConfig)],
                webpack(config) {
                    config.plugins.push(new ModuleFederationPlugin(mfConfig));
                    return config;
                },
            };
            ",
        );
        assert_eq!(config.exposed_targets, vec!["./src/Button.tsx".to_string()]);
    }

    /// A `const` inside the `webpack(config)` hook shadows the top-level `const`
    /// of the same name, so the top-level object is not the object at the call.
    #[test]
    fn a_shadowed_options_name_is_not_read() {
        let (config, computed) = bundler(
            r"
            const mfConfig = { exposes: { './Top': './src/Top.tsx' } };
            module.exports = {
                webpack(config) {
                    const mfConfig = { exposes: { './Hook': './src/Hook.tsx' } };
                    config.plugins.push(new ModuleFederationPlugin(mfConfig));
                    return config;
                },
            };
            ",
        );
        assert_eq!(config, FederationConfig::default());
        assert!(computed.is_empty(), "got {computed:?}");
    }

    /// A parameter that carries the options is a different binding than the
    /// top-level `const` of the same name.
    #[test]
    fn an_options_parameter_is_not_read() {
        let (config, computed) = bundler(
            r"
            const options = { exposes: { './Top': './src/Top.tsx' } };
            function make(options) {
                return new ModuleFederationPlugin(options);
            }
            module.exports = { plugins: [make(buildOptions())] };
            ",
        );
        assert_eq!(config, FederationConfig::default());
        assert!(computed.is_empty(), "got {computed:?}");
    }

    /// A binding that the config writes to does not hold its initializer at the
    /// call, so a reassignment and a member write both stop the read.
    #[test]
    fn options_that_the_config_writes_to_are_not_read() {
        for source in [
            r"
            let mfConfig = { exposes: { './A': './src/A.tsx' } };
            mfConfig = buildConfig();
            module.exports = { plugins: [new ModuleFederationPlugin(mfConfig)] };
            ",
            r"
            const mfConfig = { exposes: { './Old': './src/Old.tsx' } };
            delete mfConfig.exposes['./Old'];
            module.exports = { plugins: [new ModuleFederationPlugin(mfConfig)] };
            ",
            r"
            const mfConfig = { exposes: { './A': './src/A.tsx' } };
            mfConfig.exposes['./B'] = './src/B.tsx';
            module.exports = { plugins: [new ModuleFederationPlugin(mfConfig)] };
            ",
        ] {
            let (config, computed) = bundler(source);
            assert_eq!(config, FederationConfig::default(), "source: {source}");
            assert!(computed.is_empty(), "source: {source}");
        }
    }

    /// A `var` is function scoped and hoisted, so its initializer is not the
    /// value at the call.
    #[test]
    fn options_bound_by_var_are_not_read() {
        let (config, computed) = bundler(
            r"
            var mfConfig = { exposes: { './Button': './src/Button.tsx' } };
            module.exports = { plugins: [new ModuleFederationPlugin(mfConfig)] };
            ",
        );
        assert_eq!(config, FederationConfig::default());
        assert!(computed.is_empty(), "got {computed:?}");
    }

    /// The callee name alone never activates the reader. A widened search must
    /// keep the shape gate, or a library that happens to export `federation`
    /// registers entry points for an unrelated project.
    #[test]
    fn plugin_call_without_federation_keys_is_inert() {
        for source in [
            r"module.exports = { plugins: [new ModuleFederationPlugin({ name: 'x' })] };",
            r"module.exports = { plugins: [somethingElse({ exposes: { './a': './src/a.ts' } })] };",
            r"module.exports = { plugins: [federation(mfConfig)] };",
            r"module.exports = { plugins: [federation('graphql-schema', { batch: true })] };",
            r"module.exports = { plugins: [federation({ ...opts })] };",
            r"
            const options = { registry: './src/registry.ts' };
            module.exports = { plugins: [federation(options)] };
            ",
            r"
            export default defineConfig({
                plugins: [[federation(), other()]],
            });
            ",
        ] {
            let (config, computed) = bundler(source);
            assert_eq!(config, FederationConfig::default(), "source: {source}");
            assert!(computed.is_empty(), "source: {source}");
        }
    }

    /// Read a bundler config from an empty temp directory, so a relative
    /// `require` or import resolves against no file of the test process.
    fn bundler_in_temp_dir(source: &str) -> (FederationConfig, Vec<UnreadDeclaration>) {
        let dir = tempfile::tempdir().expect("temp dir");
        read(
            source,
            &dir.path().join("webpack.config.js"),
            &FederationSites {
                read_plugin_calls: true,
                read_config_object: false,
            },
        )
    }

    fn exposed(target: &str) -> FederationConfig {
        FederationConfig {
            exposed_targets: vec![target.to_string()],
            ..FederationConfig::default()
        }
    }

    #[test]
    fn exported_options_const_is_read() {
        let (config, computed) = bundler(
            r"
            export const mfConfig = { exposes: { './Button': './src/Button.tsx' } };
            export default { plugins: [new ModuleFederationPlugin(mfConfig)] };
            ",
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert!(computed.is_empty(), "got {computed:?}");
    }

    #[test]
    fn non_null_options_and_computed_member_callee_are_read() {
        let (config, computed) = read(
            r"
            const mfConfig = { exposes: { './Button': './src/Button.tsx' } };
            export default { plugins: [new ModuleFederationPlugin(mfConfig!)] };
            ",
            Path::new("webpack.config.ts"),
            &FederationSites {
                read_plugin_calls: true,
                read_config_object: false,
            },
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert!(computed.is_empty(), "got {computed:?}");

        let (config, computed) = bundler(
            r"
            const container = require('@module-federation/enhanced');
            module.exports = {
                plugins: [new container['ModuleFederationPlugin']({
                    exposes: { './Button': './src/Button.tsx' },
                })],
            };
            ",
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert!(computed.is_empty(), "got {computed:?}");
    }

    #[test]
    fn spread_and_object_assign_over_local_bindings_are_read() {
        for source in [
            r"
            const base = { exposes: { './Button': './src/Button.tsx' } };
            const mfConfig = { ...base };
            module.exports = { plugins: [new ModuleFederationPlugin(mfConfig)] };
            ",
            r"
            const base = { exposes: { './Button': './src/Button.tsx' } };
            module.exports = { plugins: [new ModuleFederationPlugin(Object.assign({}, base))] };
            ",
            r"
            const base = createModuleFederationConfig({ exposes: { './Button': './src/Button.tsx' } });
            module.exports = { plugins: [new ModuleFederationPlugin({ name: 'app', ...base })] };
            ",
        ] {
            let (config, computed) = bundler(source);
            assert_eq!(config, exposed("./src/Button.tsx"), "source: {source}");
            assert!(computed.is_empty(), "source: {source}");
        }
    }

    #[test]
    fn an_unreadable_spread_is_recorded_against_each_undeclared_key() {
        let (config, computed) = bundler_in_temp_dir(
            r"
            module.exports = {
                plugins: [new ModuleFederationPlugin({
                    ...getShared(),
                    exposes: { './Button': './src/Button.tsx' },
                })],
            };
            ",
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert_eq!(
            computed,
            unread(FederationKey::Remotes, UnreadReason::Spread)
        );

        for source in [
            r"module.exports = { plugins: [new ModuleFederationPlugin({ ...shared })] };",
            r"module.exports = { plugins: [new ModuleFederationPlugin(Object.assign({}, shared))] };",
        ] {
            let (config, computed) = bundler_in_temp_dir(source);
            assert_eq!(config, FederationConfig::default(), "source: {source}");
            assert_eq!(
                computed,
                vec![
                    UnreadDeclaration {
                        key: FederationKey::Exposes,
                        reason: UnreadReason::Spread,
                    },
                    UnreadDeclaration {
                        key: FederationKey::Remotes,
                        reason: UnreadReason::Spread,
                    },
                ],
                "source: {source}"
            );
        }
    }

    #[test]
    fn a_spread_cycle_ends_as_an_unreadable_spread() {
        let (config, computed) = bundler(
            r"
            const a = { ...b, exposes: { './Button': './src/Button.tsx' } };
            const b = { ...a };
            module.exports = { plugins: [new ModuleFederationPlugin(a)] };
            ",
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert_eq!(
            computed,
            unread(FederationKey::Remotes, UnreadReason::Spread)
        );
    }

    #[test]
    fn a_package_require_is_silent() {
        let (config, computed) = bundler(
            r"
            const mfConfig = require('shared-federation-config');
            module.exports = { plugins: [new ModuleFederationPlugin(mfConfig)] };
            ",
        );
        assert_eq!(config, FederationConfig::default());
        assert!(computed.is_empty(), "got {computed:?}");
    }

    #[test]
    fn options_from_a_relative_require_are_read() {
        let dir = tempfile::tempdir().expect("temp dir");
        std::fs::write(
            dir.path().join("mf.config.js"),
            r"
            const options = { exposes: { './Button': './src/Button.tsx' } };
            module.exports = options;
            ",
        )
        .expect("write sibling config");
        let (config, computed) = read(
            r"
            const mfConfig = require('./mf.config');
            module.exports = {
                plugins: [
                    new ModuleFederationPlugin(mfConfig),
                    new ModuleFederationPlugin({ ...require('./mf.config.js') }),
                ],
            };
            ",
            &dir.path().join("webpack.config.js"),
            &FederationSites {
                read_plugin_calls: true,
                read_config_object: false,
            },
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert!(computed.is_empty(), "got {computed:?}");
    }

    #[test]
    fn options_from_a_relative_import_are_read() {
        let dir = tempfile::tempdir().expect("temp dir");
        let config_path = dir.path().join("webpack.config.ts");
        std::fs::write(
            dir.path().join("mf.config.ts"),
            r"
            const base = { exposes: { './Button': './src/Button.tsx' } };
            export const mfConfig = { ...base };
            export default createModuleFederationConfig({ remotes: { checkout: 'checkout@x' } });
            ",
        )
        .expect("write sibling config");
        let (config, computed) = read(
            r"
            import remote, { mfConfig } from './mf.config';
            export default {
                plugins: [
                    new ModuleFederationPlugin(mfConfig),
                    new ModuleFederationPlugin(remote),
                ],
            };
            ",
            &config_path,
            &FederationSites {
                read_plugin_calls: true,
                read_config_object: false,
            },
        );
        assert_eq!(
            config,
            FederationConfig {
                exposed_targets: vec!["./src/Button.tsx".to_string()],
                remote_aliases: vec!["checkout".to_string()],
                ..FederationConfig::default()
            }
        );
        assert!(computed.is_empty(), "got {computed:?}");
    }

    #[test]
    fn a_standalone_config_reads_a_spread_of_a_local_binding() {
        let (config, computed) = standalone(
            r"
            const base = { exposes: { './Button': './src/Button.tsx' } };
            export default { name: 'app', ...base };
            ",
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert!(computed.is_empty(), "got {computed:?}");
    }

    fn unread_both(reason: UnreadReason) -> Vec<UnreadDeclaration> {
        vec![
            UnreadDeclaration {
                key: FederationKey::Exposes,
                reason,
            },
            UnreadDeclaration {
                key: FederationKey::Remotes,
                reason,
            },
        ]
    }

    /// A known identity wrapper passes its argument through, so it is read
    /// with no diagnostic, inline and bound to a name alike.
    #[test]
    fn identity_wrappers_are_read_without_a_diagnostic() {
        for source in [
            r"module.exports = { plugins: [new ModuleFederationPlugin(createModuleFederationConfig({ exposes: { './Button': './src/Button.tsx' } }))] };",
            r"module.exports = { plugins: [new ModuleFederationPlugin(defineConfig({ exposes: { './Button': './src/Button.tsx' } }))] };",
            r"
            const mf = createModuleFederationConfig({ exposes: { './Button': './src/Button.tsx' } });
            module.exports = { plugins: [new ModuleFederationPlugin(mf)] };
            ",
            r"
            const base = { exposes: { './Button': './src/Button.tsx' } };
            module.exports = { plugins: [new ModuleFederationPlugin(mf.createModuleFederationConfig(base))] };
            ",
        ] {
            let (config, computed) = bundler(source);
            assert_eq!(config, exposed("./src/Button.tsx"), "source: {source}");
            assert!(computed.is_empty(), "source: {source}, got {computed:?}");
        }
        for source in [
            r"export default createModuleFederationConfig({ exposes: { './Button': './src/Button.tsx' } });",
            r"export default defineConfig({ exposes: { './Button': './src/Button.tsx' } });",
        ] {
            let (config, computed) = standalone(source);
            assert_eq!(config, exposed("./src/Button.tsx"), "source: {source}");
            assert!(computed.is_empty(), "source: {source}, got {computed:?}");
        }
    }

    /// A call that is not a known wrapper can add or change what it returns.
    /// The object literal passed to it stays credited as a lower bound, and the
    /// call is recorded against each key that literal declares. The inline
    /// form and the bound form give the same result.
    #[test]
    fn an_unrecognized_call_keeps_the_inner_literal_and_is_recorded() {
        let expected = unread(FederationKey::Exposes, UnreadReason::UnrecognizedCall);
        for source in [
            r"module.exports = { plugins: [new ModuleFederationPlugin(federationConfig({ name: 'app', exposes: { './Button': './src/Button.tsx' } }))] };",
            r"
            const mf = federationConfig({ name: 'app', exposes: { './Button': './src/Button.tsx' } });
            module.exports = { plugins: [new ModuleFederationPlugin(mf)] };
            ",
            r"
            const base = { name: 'app', exposes: { './Button': './src/Button.tsx' } };
            module.exports = { plugins: [new ModuleFederationPlugin(withShared(base))] };
            ",
        ] {
            let (config, computed) = bundler(source);
            assert_eq!(config, exposed("./src/Button.tsx"), "source: {source}");
            assert_eq!(computed, expected, "source: {source}");
        }
        let (config, computed) = standalone(
            r"export default federationConfig({ exposes: { './Button': './src/Button.tsx' } });",
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert_eq!(computed, expected);

        // A literal that declares no key still names Module Federation beyond
        // doubt under a specific callee, so the call is recorded against both
        // keys. The generic `federation` callee stays inert.
        let (config, computed) = bundler(
            r"module.exports = { plugins: [new ModuleFederationPlugin(withShared({ name: 'app' }))] };",
        );
        assert_eq!(config, FederationConfig::default());
        assert_eq!(computed, unread_both(UnreadReason::UnrecognizedCall));
        let (config, computed) =
            bundler(r"export default { plugins: [federation(withShared({ name: 'app' }))] };");
        assert_eq!(config, FederationConfig::default());
        assert!(computed.is_empty(), "got {computed:?}");
    }

    /// Only the keys that come from the unrecognized call are recorded. A key
    /// declared by a literal outside the call is read in full.
    #[test]
    fn an_unrecognized_call_records_only_the_keys_it_receives() {
        let (config, computed) = bundler(
            r"
            module.exports = { plugins: [new ModuleFederationPlugin({
                ...withShared({ exposes: { './Button': './src/Button.tsx' } }),
                remotes: { checkout: 'checkout@x' },
            })] };
            ",
        );
        assert_eq!(
            config,
            FederationConfig {
                exposed_targets: vec!["./src/Button.tsx".to_string()],
                remote_aliases: vec!["checkout".to_string()],
                ..FederationConfig::default()
            }
        );
        assert_eq!(
            computed,
            unread(FederationKey::Exposes, UnreadReason::UnrecognizedCall)
        );
    }

    /// A followed relative import or `require` whose target cannot be read is
    /// recorded. An argument with no relative binding records nothing.
    #[test]
    fn an_unreadable_import_target_is_recorded() {
        let dir = tempfile::tempdir().expect("temp dir");
        std::fs::write(
            dir.path().join("mf.options.js"),
            "const build = require('./build');\nmodule.exports = build();\n",
        )
        .expect("write sibling config");
        let read_in_dir = |source: &str| {
            read(
                source,
                &dir.path().join("webpack.config.js"),
                &FederationSites {
                    read_plugin_calls: true,
                    read_config_object: false,
                },
            )
        };
        for source in [
            r"module.exports = { plugins: [new ModuleFederationPlugin(require('./missing.options'))] };",
            r"module.exports = { plugins: [new ModuleFederationPlugin(require('./mf.options'))] };",
            r"
            const mf = require('./mf.options');
            module.exports = { plugins: [new ModuleFederationPlugin(mf)] };
            ",
            r"
            import mf from './missing.options';
            export default { plugins: [new ModuleFederationPlugin(mf)] };
            ",
        ] {
            let (config, computed) = read_in_dir(source);
            assert_eq!(config, FederationConfig::default(), "source: {source}");
            assert_eq!(
                computed,
                unread_both(UnreadReason::ImportTargetUnreadable),
                "source: {source}"
            );
        }

        // A readable key beside an unreadable spread of an import records the
        // import against the key it does not declare.
        let (config, computed) = read_in_dir(
            r"
            module.exports = { plugins: [new ModuleFederationPlugin({
                ...require('./missing.options'),
                exposes: { './Button': './src/Button.tsx' },
            })] };
            ",
        );
        assert_eq!(config, exposed("./src/Button.tsx"));
        assert_eq!(
            computed,
            unread(FederationKey::Remotes, UnreadReason::ImportTargetUnreadable)
        );

        for source in [
            r"module.exports = { plugins: [new ModuleFederationPlugin(require('shared-federation-options'))] };",
            r"module.exports = { plugins: [new ModuleFederationPlugin(options)] };",
            r"module.exports = { plugins: [federation(require('./missing.options'))] };",
        ] {
            let (config, computed) = read_in_dir(source);
            assert_eq!(config, FederationConfig::default(), "source: {source}");
            assert!(computed.is_empty(), "source: {source}, got {computed:?}");
        }
    }

    #[test]
    fn the_new_reasons_carry_their_own_tokens() {
        assert_eq!(UnreadReason::UnrecognizedCall.token(), "unrecognized-call");
        assert_eq!(
            UnreadReason::ImportTargetUnreadable.token(),
            "import-target-unreadable"
        );
    }

    /// A standalone config that declares a Federation key credits the build
    /// plugin packages, because no bundler config imports them. The runtime
    /// package is imported by application code and is never credited here.
    #[test]
    fn a_standalone_config_that_declares_a_key_credits_the_build_plugins() {
        let result = resolve(
            r"module.exports = { name: 'app', exposes: { './Button': './src/Button.tsx' } };",
        );
        for package in [
            "@module-federation/enhanced",
            "@module-federation/rsbuild-plugin",
            "@module-federation/vite",
        ] {
            assert!(
                result
                    .referenced_dependencies
                    .iter()
                    .any(|dep| dep == package),
                "{package} is credited, got {:?}",
                result.referenced_dependencies
            );
        }
        assert!(
            !result
                .referenced_dependencies
                .iter()
                .any(|dep| dep == "@module-federation/runtime"),
            "the runtime is not credited, got {:?}",
            result.referenced_dependencies
        );

        let result = resolve(r"module.exports = { remotes: { checkout: 'checkout@x' } };");
        assert!(
            result
                .referenced_dependencies
                .iter()
                .any(|dep| dep == "@module-federation/enhanced"),
            "a remotes key credits too, got {:?}",
            result.referenced_dependencies
        );

        let result = resolve(r"module.exports = { name: 'app', filename: 'remoteEntry.js' };");
        assert!(
            result.referenced_dependencies.is_empty(),
            "no Federation key, no credit, got {:?}",
            result.referenced_dependencies
        );
    }

    /// A target in a sibling directory of the plugin root keeps its parent
    /// segments. The workspace prefix resolves them later, so a target in a
    /// sibling workspace is credited and a target outside the project matches
    /// no file.
    #[test]
    fn a_target_outside_the_plugin_root_keeps_its_parent_segments() {
        let result = ModuleFederationPlugin.resolve_config(
            Path::new("/project/packages/app/webpack.config.js"),
            r"export default { exposes: { './Thing': '../shared/src/Thing.tsx', './Lib': '../shared/src/lib' } };",
            Path::new("/project/packages/app"),
        );
        let patterns = entry_patterns(&result);
        assert!(
            patterns.contains(&"../shared/src/Thing.tsx".to_string()),
            "got {patterns:?}"
        );
        assert!(
            patterns
                .iter()
                .any(|pattern| covers(pattern, "../shared/src/lib/index.ts")),
            "got {patterns:?}"
        );
    }

    fn shared(packages: &[&str]) -> FederationConfig {
        FederationConfig {
            shared_packages: packages.iter().map(|name| (*name).to_string()).collect(),
            ..FederationConfig::default()
        }
    }

    #[test]
    fn shared_object_and_array_forms_name_their_packages() {
        let (config, unread) = bundler(
            r"
            module.exports = { plugins: [new ModuleFederationPlugin({
                shared: {
                    react: { singleton: true },
                    'react-dom': '^18.0.0',
                    '@scope/ui/': {},
                    alias: { import: 'lodash/merge', packageName: 'lodash' },
                    './src/local': {},
                    off: { import: false },
                },
            })] };
            ",
        );
        assert_eq!(
            config,
            shared(&["react", "react-dom", "@scope/ui", "alias", "lodash", "off"])
        );
        assert!(unread.is_empty(), "got {unread:?}");

        let (config, unread) = standalone(
            r"export default { shared: ['react', { 'react-dom': { singleton: true } }, 42] };",
        );
        assert_eq!(config, shared(&["react", "react-dom"]));
        assert!(unread.is_empty(), "got {unread:?}");
    }

    #[test]
    fn an_unreadable_shared_value_records_no_diagnostic() {
        for source in [
            r"export default { shared: makeShared() };",
            r"export default { shared: { ...deps, react: {} } };",
        ] {
            let (_, unread) = standalone(source);
            assert!(unread.is_empty(), "{source}: got {unread:?}");
        }
        let (config, _) = standalone(r"export default { shared: { ...deps, react: {} } };");
        assert_eq!(config, shared(&["react"]));
    }

    #[test]
    fn shared_passes_the_shape_gate_of_the_ambiguous_callee() {
        let (config, _) = read(
            r"export default { plugins: [federation({ name: 'app', shared: ['vue'] })] };",
            Path::new("vite.config.ts"),
            &FederationSites {
                read_plugin_calls: true,
                read_config_object: false,
            },
        );
        assert_eq!(config, shared(&["vue"]));

        let result = resolve(r"export default { name: 'app', shared: ['react'] };");
        assert!(
            result
                .referenced_dependencies
                .contains(&"@module-federation/enhanced".to_string()),
            "a shared key credits the build plugins, got {:?}",
            result.referenced_dependencies
        );
        assert!(
            !result
                .referenced_dependencies
                .contains(&"react".to_string()),
            "a shared package is not credited project-wide, got {:?}",
            result.referenced_dependencies
        );
        assert_eq!(
            result.package_referenced_dependencies,
            vec![(PathBuf::from("/project/package.json"), "react".to_string())]
        );
    }

    /// An unrecognized call whose argument declares only `shared` can still
    /// return `exposes` and `remotes`, so both stay recorded.
    #[test]
    fn an_unrecognized_call_that_receives_only_shared_records_both_keys() {
        let (config, unread) = bundler(
            r"
            module.exports = { plugins: [new ModuleFederationPlugin(
                withDefaults({ shared: ['react'] }),
            )] };
            ",
        );
        assert_eq!(config, shared(&["react"]));
        assert_eq!(
            unread,
            vec![
                UnreadDeclaration {
                    key: FederationKey::Exposes,
                    reason: UnreadReason::UnrecognizedCall,
                },
                UnreadDeclaration {
                    key: FederationKey::Remotes,
                    reason: UnreadReason::UnrecognizedCall,
                },
            ]
        );
    }

    /// Other libraries name a function `federation`, so options that declare
    /// only `shared` do not open the gate for an unrecognized call. The
    /// shared packages still get credit.
    #[test]
    fn a_bare_federation_call_that_receives_only_shared_records_nothing() {
        let (config, unread) = read(
            r#"
            const federation = (options) => options;
            export default { plugins: [federation(withDefaults({ shared: ["vue"] }))] };
            "#,
            Path::new("vite.config.ts"),
            &FederationSites {
                read_plugin_calls: true,
                read_config_object: false,
            },
        );
        assert_eq!(config, shared(&["vue"]));
        assert!(unread.is_empty(), "got {unread:?}");
    }
}