rolldown 1.0.0

Fast JavaScript bundler in Rust, designed for the future of Vite
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
use bitflags::bitflags;
use oxc::ast::ast::ObjectPropertyKind;
use oxc::semantic::{ReferenceId, ScopeFlags, SymbolId};
use oxc::{
  allocator::{self, Allocator, Box as ArenaBox, CloneIn, Dummy, IntoIn, TakeIn},
  ast::{
    AstBuilder, NONE,
    ast::{
      self, ClassElement, Expression, IdentifierReference, ImportExpression, MemberExpression,
      NumberBase, Statement, VariableDeclarationKind,
    },
  },
  span::{GetSpan, GetSpanMut, SPAN},
};
use rolldown_common::{
  AstScopes, Chunk, ChunkIdx, ConcatenateWrappedModuleKind, ExportsKind, ImportRecordIdx,
  ImportRecordMeta, InlineConstMode, MemberExprRefResolution, Module, ModuleIdx,
  ModuleNamespaceIncludedReason, ModuleType, NamespaceAlias, NormalModule, OutputExports,
  OutputFormat, Platform, RenderedConcatenatedModuleParts, Specifier, SymbolRef, WrapKind,
};
use rolldown_ecmascript::ToSourceString;
use rolldown_ecmascript_utils::{
  AstSnippet, BindingPatternExt, CallExpressionExt, ExpressionExt, StatementExt,
};

mod finalizer_context;
mod impl_visit_mut;
pub use finalizer_context::ScopeHoistingFinalizerContext;
use oxc_str::{CompactStr, Ident};
use rolldown_utils::ecmascript::is_validate_identifier_name;
use rolldown_utils::indexmap::{FxIndexMap, FxIndexSet};
use rustc_hash::{FxHashMap, FxHashSet};
use sugar_path::SugarPath;

use crate::hmr::utils::HmrAstBuilder;
use crate::utils::external_import_interop::import_record_needs_interop;

mod hmr;
mod rename;

/// Helper enum for `try_rewrite_cjs_member_expr_assignment_target` to handle both static and computed member properties.
enum CjsMemberProperty<'a, 'ast> {
  Static(&'a str),
  Computed(&'a ast::Expression<'ast>),
}

bitflags! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct TraverseState: u8 {
        const TopLevel = 1;
        /// - `if (test) {} else {}`
        /// - test ? a : b
        /// - test1 || test2
        /// - test1 && test2
        /// - test1 ?? test2
        const SmartInlineConst = 1 << 1;
        const IsRootLevel = 1 << 2;
    }
}

bitflags! {
  #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  pub struct FinalizedExprProcessHint: u8 {
      const FromCjsWrapKindEntry = 1;
  }
}

/// Represents different ways to identify a name for `keep_names` functionality.
#[derive(Clone, Debug, Copy)]
pub enum KeepNameId<'a> {
  /// A symbol ID from the AST's symbol table.
  SymbolId(SymbolId),
  /// A reference ID from the AST's reference table.
  ReferenceId(ReferenceId),
  /// A string name used directly (e.g., for "default" exports).
  CompactStr(&'a CompactStr),
}

/// Finalizer for emitting output code with scope hoisting.
pub struct ScopeHoistingFinalizer<'me, 'ast: 'me> {
  pub ctx: ScopeHoistingFinalizerContext<'me>,
  pub scope: &'me AstScopes,
  pub alloc: &'ast Allocator,
  pub snippet: AstSnippet<'ast>,
  pub generated_init_esm_importee_ids: FxHashSet<ModuleIdx>,
  pub scope_stack: Vec<ScopeFlags>,
  pub state: TraverseState,
  pub top_level_var_bindings: FxIndexSet<Ident<'ast>>,
  pub cur_stmt_index: usize,
  pub keep_name_statement_to_insert: Vec<(usize, CompactStr, CompactStr)>,
  pub needs_hosted_top_level_binding: bool,
  pub module_namespace_included: bool,
  pub transferred_import_record: FxIndexMap<ImportRecordIdx, String>,
  pub rendered_concatenated_wrapped_module_parts: RenderedConcatenatedModuleParts,
  pub json_module_inlined_prop: Option<Box<FxHashMap<SymbolId, ast::Expression<'ast>>>>,
}

impl<'me, 'ast> ScopeHoistingFinalizer<'me, 'ast> {
  pub fn is_global_identifier_reference(&self, id_ref: &IdentifierReference) -> bool {
    let Some(reference_id) = id_ref.reference_id.get() else {
      // Some `IdentifierReference`s constructed by bundler don't have a `ReferenceId`. They might be global variables.
      // But we don't care about them in this method. This method is only used to check if a `IdentifierReference` from user code is a global variable.
      return false;
    };
    self.scope.is_unresolved(reference_id)
  }

  pub fn canonical_name_for(&self, symbol: SymbolRef) -> &'me str {
    self.ctx.symbol_db.canonical_name_for_or_original(symbol, &self.ctx.chunk.canonical_names)
  }

  pub fn canonical_name_for_runtime(&self, name: &str) -> &'me str {
    let sym_ref = self.ctx.runtime.resolve_symbol(name);
    self.canonical_name_for(sym_ref)
  }

  pub fn canonical_ref_for_runtime(&self, name: &str) -> SymbolRef {
    self.ctx.runtime.resolve_symbol(name)
  }

  pub fn finalized_expr_for_runtime_symbol(&self, name: &str) -> ast::Expression<'ast> {
    let (expr, _) =
      self.finalized_expr_for_symbol_ref(self.ctx.runtime.resolve_symbol(name), false, false);
    expr
  }

  /// For excluded re-export statements in strict execution order, generate init
  /// calls by traversing through non-included barrel modules to find included
  /// importees whose wrappers are available in this chunk.
  fn generate_transitive_esm_init(
    &mut self,
    module_idx: ModuleIdx,
    body: &mut allocator::Vec<'ast, Statement<'ast>>,
  ) {
    let mut stack = vec![module_idx];
    while let Some(module_idx) = stack.pop() {
      let Module::Normal(importee) = &self.ctx.modules[module_idx] else { continue };
      let importee_linking_info = &self.ctx.linking_infos[importee.idx];
      if !matches!(importee_linking_info.wrap_kind(), WrapKind::Esm) {
        continue;
      }

      // `generated_init_esm_importee_ids` serves double duty: it tracks both
      // modules for which we already emitted an init call AND modules we have
      // already visited during transitive traversal.
      if !self.generated_init_esm_importee_ids.insert(importee.idx) {
        continue;
      }

      // Only generate init calls for modules in the same chunk whose wrapper is
      // declared (i.e. the module is included in the output).
      if importee_linking_info.is_included
        && self.ctx.chunk_graph.module_to_chunk[importee.idx] == Some(self.ctx.chunk_idx)
      {
        let (wrapper_ref_expr, _) = self.finalized_expr_for_symbol_ref(
          importee_linking_info.wrapper_ref.unwrap(),
          false,
          false,
        );
        let init_call = self.snippet.builder.expression_call(
          SPAN,
          wrapper_ref_expr,
          NONE,
          self.snippet.builder.vec(),
          false,
        );
        body.push(self.snippet.builder.statement_expression(SPAN, init_call));
      } else {
        // Importee is not included (barrel module) — traverse its import records
        // to find included importees transitively.
        // Preserve the old recursive DFS order when using an explicit LIFO stack:
        // pushing children in reverse keeps source-order visitation left-to-right.
        for rec in importee.import_records.iter().rev() {
          if let Some(sub_importee_idx) = rec.resolved_module {
            stack.push(sub_importee_idx);
          }
        }
      }
    }
  }

  fn collect_wrapped_esm_init_modules_for_import_record(
    &self,
    rec_idx: ImportRecordIdx,
  ) -> FxIndexSet<ModuleIdx> {
    // See meta/design/linking/reference-needed-symbols.md for why this follows
    // canonical owners through non-wrapped barrel modules.
    let mut init_modules = FxIndexSet::default();
    let rec = &self.ctx.module.import_records[rec_idx];
    let Some(importee_idx) = rec.resolved_module else { return init_modules };
    let importee_linking_info = &self.ctx.linking_infos[importee_idx];

    if rec.meta.contains(ImportRecordMeta::IsExportStar) {
      for resolved_export in importee_linking_info.resolved_exports.values() {
        self.add_wrapped_esm_init_module_for_symbol(resolved_export.symbol_ref, &mut init_modules);
      }
      return init_modules;
    }

    for named_import in
      self.ctx.module.named_imports.values().filter(|item| item.record_idx == rec_idx)
    {
      match &named_import.imported {
        Specifier::Star => {
          for resolved_export in importee_linking_info.resolved_exports.values() {
            self.add_wrapped_esm_init_module_for_symbol(
              resolved_export.symbol_ref,
              &mut init_modules,
            );
          }
        }
        Specifier::Literal(name) => {
          if let Some(resolved_export) = importee_linking_info.resolved_exports.get(name) {
            self.add_wrapped_esm_init_module_for_symbol(
              resolved_export.symbol_ref,
              &mut init_modules,
            );
          } else {
            self
              .add_wrapped_esm_init_module_for_symbol(named_import.imported_as, &mut init_modules);
          }
        }
      }
    }

    init_modules
  }

  fn add_wrapped_esm_init_module_for_symbol(
    &self,
    symbol_ref: SymbolRef,
    init_modules: &mut FxIndexSet<ModuleIdx>,
  ) {
    let canonical_ref = self.ctx.symbol_db.canonical_ref_resolving_namespace(symbol_ref);
    let meta = &self.ctx.linking_infos[canonical_ref.owner];
    if matches!(meta.wrap_kind(), WrapKind::Esm)
      && meta.wrapper_ref.is_some()
      && !matches!(meta.concatenated_wrapped_module_kind, ConcatenateWrappedModuleKind::Inner)
    {
      init_modules.insert(canonical_ref.owner);
    }
  }

  fn wrapped_esm_init_stmt_for_import_record(
    &mut self,
    rec_idx: ImportRecordIdx,
  ) -> Option<Statement<'ast>> {
    let rec = &self.ctx.module.import_records[rec_idx];
    // If the non-wrapped forwarding module is emitted in this chunk, its own
    // lowered statement already preserves the required init call in execution
    // order. This fallback is only for barrels that do not execute here.
    if rec.resolved_module.is_some_and(|importee_idx| {
      let importee_linking_info = &self.ctx.linking_infos[importee_idx];
      matches!(importee_linking_info.wrap_kind(), WrapKind::None)
        && importee_linking_info.is_included
        && self.ctx.chunk_graph.module_to_chunk[importee_idx] == Some(self.ctx.chunk_idx)
    }) {
      return None;
    }

    let init_modules = self
      .collect_wrapped_esm_init_modules_for_import_record(rec_idx)
      .into_iter()
      .collect::<Vec<_>>();
    if init_modules.is_empty() {
      return None;
    }

    let init_exprs = init_modules.into_iter().filter_map(|module_idx| {
      if !self.generated_init_esm_importee_ids.insert(module_idx) {
        return None;
      }

      let importee_linking_info = &self.ctx.linking_infos[module_idx];
      let wrapper_ref = importee_linking_info.wrapper_ref?;
      let is_tla_or_contains_tla_dependency =
        importee_linking_info.is_tla_or_contains_tla_dependency;
      let (wrapper_ref_expr, _) = self.finalized_expr_for_symbol_ref(wrapper_ref, false, false);

      let init_call = ast::Expression::CallExpression(self.snippet.builder.alloc_call_expression(
        SPAN,
        wrapper_ref_expr,
        NONE,
        self.snippet.builder.vec(),
        false,
      ));

      Some(if is_tla_or_contains_tla_dependency {
        ast::Expression::AwaitExpression(
          self.snippet.builder.alloc_await_expression(SPAN, init_call),
        )
      } else {
        init_call
      })
    });

    let init_exprs = init_exprs.collect::<Vec<_>>();
    match init_exprs.len() {
      0 => None,
      1 => init_exprs
        .into_iter()
        .next()
        .map(|init_expr| self.snippet.builder.statement_expression(SPAN, init_expr)),
      _ => {
        let builder = self.builder();
        Some(builder.statement_expression(
          SPAN,
          builder.expression_sequence(SPAN, builder.vec_from_iter(init_exprs)),
        ))
      }
    }
  }

  /// If return true the import stmt should be removed,
  /// or transform the import stmt to target form.
  fn transform_or_remove_import_export_stmt(
    &mut self,
    stmt: &mut Statement<'ast>,
    rec_idx: ImportRecordIdx,
  ) -> bool {
    let rec = &self.ctx.module.import_records[rec_idx];
    let Some(resolved_module_idx) = rec.resolved_module else { return true };
    let Module::Normal(importee) = &self.ctx.modules[resolved_module_idx] else {
      return true;
    };
    let importee_linking_info = &self.ctx.linking_infos[importee.idx];
    match importee_linking_info.wrap_kind() {
      WrapKind::None => {
        if let Some(init_stmt) = self.wrapped_esm_init_stmt_for_import_record(rec_idx) {
          *stmt = init_stmt;
          return false;
        }
        // Remove this statement by ignoring it
      }
      WrapKind::Cjs => {
        // Check if this CJS module's namespace can be merged with other imports
        let merge_info = self.ctx.safely_merge_cjs_ns_map.get(&resolved_module_idx);

        // Consider user reference a module use relative path e.g.
        // ```js
        // import React from './node_modules/react/index.js';
        // ```
        if merge_info.is_some() {
          let chunk_idx = self.ctx.chunk_idx;
          if let Some(symbol_ref_to_be_merged) =
            self.ctx.chunk_graph.finalized_cjs_ns_map_idx_vec[chunk_idx].get(&rec.namespace_ref)
          {
            if symbol_ref_to_be_merged != &rec.namespace_ref {
              return true;
            }
          }
        }

        // Replace the statement with something like `var import_foo = __toESM(require_foo())`
        // or `var import_foo = require_foo()` if only named imports are used

        // `require_foo`
        let (importee_wrapper_ref_name, hint) = self.finalized_expr_for_symbol_ref(
          importee_linking_info.wrapper_ref.unwrap(),
          false,
          false,
        );

        let require_call = if hint.contains(FinalizedExprProcessHint::FromCjsWrapKindEntry) {
          importee_wrapper_ref_name
        } else {
          self.snippet.builder.expression_call(
            SPAN,
            importee_wrapper_ref_name,
            NONE,
            self.snippet.builder.vec(),
            false,
          )
        };

        // Check if we need __toESM or can use require_foo() directly
        let needs_toesm = if let Some(info) = merge_info {
          info.needs_interop
        } else {
          import_record_needs_interop(self.ctx.module, rec_idx)
        };
        let init_expr = if needs_toesm {
          // `__toESM`
          let to_esm_fn_name = self.finalized_expr_for_runtime_symbol("__toESM");
          self.snippet.wrap_with_to_esm(
            to_esm_fn_name,
            require_call,
            self.ctx.module.should_consider_node_esm_spec_for_static_import(),
          )
        } else {
          require_call
        };

        // `import_foo`
        let binding_name_for_wrapper_call_ret = self.canonical_name_for(rec.namespace_ref);
        *stmt = self.snippet.var_decl_stmt(binding_name_for_wrapper_call_ret, init_expr);

        if self.transferred_import_record.contains_key(&rec_idx) {
          self.transferred_import_record.insert(rec_idx, stmt.to_source_string());
          return true;
        }
        return false;
      }
      // Replace the import statement with `init_foo()` if `ImportDeclaration` is not a plain import
      // or the importee have side effects.
      WrapKind::Esm => {
        if matches!(
          importee_linking_info.concatenated_wrapped_module_kind,
          ConcatenateWrappedModuleKind::Inner
        ) || self.generated_init_esm_importee_ids.contains(&importee.idx)
        {
          return true;
        }
        self.generated_init_esm_importee_ids.insert(importee.idx);
        // `init_foo`
        let (wrapper_ref_expr, _) = self.finalized_expr_for_symbol_ref(
          importee_linking_info.wrapper_ref.unwrap(),
          false,
          false,
        );

        // `init_foo()`
        let init_call =
          ast::Expression::CallExpression(self.snippet.builder.alloc_call_expression(
            stmt.span(),
            wrapper_ref_expr,
            NONE,
            self.snippet.builder.vec(),
            false,
          ));

        if importee_linking_info.is_tla_or_contains_tla_dependency {
          // `await init_foo()`
          *stmt = self.snippet.builder.statement_expression(
            SPAN,
            ast::Expression::AwaitExpression(
              self.snippet.builder.alloc_await_expression(SPAN, init_call),
            ),
          );
        } else {
          // `init_foo()`
          *stmt = self.snippet.builder.statement_expression(SPAN, init_call);
        }

        if self.transferred_import_record.contains_key(&rec_idx) {
          self.transferred_import_record.insert(rec_idx, stmt.to_source_string());
          return true;
        }
        return false;
      }
    }
    true
  }

  /// `optimize_namespace_alias_transform` is a flag to determine whether optimize interop code with commonjs
  /// e.g.
  /// We could try to rewrite `import_cjs.default.exported` into `import_cjs.exported`
  fn finalized_expr_for_symbol_ref(
    &self,
    symbol_ref: SymbolRef,
    preserve_this_semantic_if_needed: bool,
    optimize_namespace_alias_transform: bool,
  ) -> (ast::Expression<'ast>, FinalizedExprProcessHint) {
    if !symbol_ref.is_declared_in_root_scope(self.ctx.symbol_db) {
      // No fancy things on none root scope symbols
      return (
        self.snippet.id_ref_expr(self.canonical_name_for(symbol_ref), SPAN),
        FinalizedExprProcessHint::empty(),
      );
    }

    let mut canonical_ref = self.ctx.symbol_db.canonical_ref_for(symbol_ref);
    let mut canonical_symbol = self.ctx.symbol_db.get(canonical_ref);
    let namespace_alias = canonical_symbol.namespace_alias.as_ref();
    if let Some(ns_alias) = namespace_alias {
      if let Some(expr) = self.try_inline_constant_from_namespace_alias(symbol_ref, ns_alias) {
        return expr;
      }
      canonical_ref = ns_alias.namespace_ref;
      canonical_symbol = self.ctx.symbol_db.get(canonical_ref);
    }
    if let Some(meta) = self.ctx.constant_value_map.get(&canonical_ref) {
      if !self.ctx.options.optimization.is_inline_const_smart_mode()
        || (self.state.contains(TraverseState::SmartInlineConst) || meta.safe_to_inline)
      {
        return (
          meta.value.to_expression(AstBuilder::new(self.alloc)),
          FinalizedExprProcessHint::empty(),
        );
      }
    }
    let mut hint = FinalizedExprProcessHint::empty();
    let mut expr = if self.ctx.modules[canonical_ref.owner].is_external() {
      // For mixed-mode externals, ESM importers use the node-mode binding name
      if self.ctx.module.should_consider_node_esm_spec_for_static_import() {
        if let Some(node_mode_name) = self.ctx.chunk.node_mode_external_ns_names.get(&canonical_ref)
        {
          self.snippet.id_ref_expr(node_mode_name.as_str(), SPAN)
        } else {
          self.snippet.id_ref_expr(self.canonical_name_for(canonical_ref), SPAN)
        }
      } else {
        self.snippet.id_ref_expr(self.canonical_name_for(canonical_ref), SPAN)
      }
    } else {
      match self.ctx.options.format {
        rolldown_common::OutputFormat::Cjs => {
          let chunk_idx_of_canonical_symbol = canonical_symbol.chunk_idx.unwrap_or_else(|| {
            // Scoped symbols don't get assigned a `ChunkIdx`. There are skipped for performance reason, because they are surely
            // belong to the chunk they are declared in and won't link to other chunks.
            let symbol_name = canonical_ref.name(self.ctx.symbol_db);
            panic!("{canonical_ref:?} {symbol_name:?} is not in any chunk, which is unexpected");
          });
          let cur_chunk_idx = self.ctx.chunk_graph.module_to_chunk[self.ctx.idx]
            .expect("This module should be in a chunk");
          let is_symbol_in_other_chunk = cur_chunk_idx != chunk_idx_of_canonical_symbol;
          if is_symbol_in_other_chunk {
            let (expr, extra_hint) = self.finalized_expr_for_cross_chunk_symbol(
              cur_chunk_idx,
              chunk_idx_of_canonical_symbol,
              canonical_ref,
            );
            hint.insert(extra_hint);
            expr
          } else {
            self.snippet.id_ref_expr(self.canonical_name_for(canonical_ref), SPAN)
          }
        }
        _ => self.snippet.id_ref_expr(self.canonical_name_for(canonical_ref), SPAN),
      }
    };

    if let Some(ns_alias) = namespace_alias {
      if !optimize_namespace_alias_transform {
        expr = ast::Expression::StaticMemberExpression(
          self.snippet.builder.alloc_static_member_expression(
            SPAN,
            expr,
            self.snippet.id_name(&ns_alias.property_name, SPAN),
            false,
          ),
        );
      }

      if preserve_this_semantic_if_needed {
        expr = self.snippet.seq2_in_paren_expr(self.snippet.number_expr(0.0, "0"), expr);
      }
    }

    (expr, hint)
  }

  /// Generates the expression for accessing a symbol from another chunk in CJS output.
  ///
  /// In CJS output, cross-chunk symbol access uses `require()` bindings:
  /// - `import { foo } from 'foo'; console.log(foo);` becomes `console.log(require_foo.foo);`
  ///
  /// Returns the expression and any additional hints for processing.
  ///
  /// ## Cross-Chunk Symbol Resolution Matrix
  ///
  /// See `crates/rolldown/tests/rolldown/topics/exports/README.md` for the full test matrix.
  ///
  /// | # | Chunk Type | WrapKind | OutputExports | Export Name | Result |
  /// |---|------------|----------|---------------|-------------|--------|
  /// | 1 | Entry | Cjs | Default | default | `require_binding` |
  /// | 2 | Entry | Cjs | Named | default | `require_binding.default` |
  /// | 3 | Entry | Cjs | Named | named | `require_binding.default` (access wrapped module) |
  /// | 4 | Entry | Esm | Default | default | N/A (invalid: ESM wrap adds extra exports) |
  /// | 5 | Entry | Esm | Named | default | `require_binding.default` |
  /// | 6 | Entry | Esm | Named | named | `require_binding.exportName` |
  /// | 7 | Entry | None | Default | default | `require_binding` |
  /// | 8 | Entry | None | Named | default | `require_binding.default` |
  /// | 9 | Entry | None | Named | named | `require_binding.exportName` |
  /// | 10-15 | Common | * | Named | * | `require_binding.exportName` |
  fn finalized_expr_for_cross_chunk_symbol(
    &self,
    cur_chunk_idx: ChunkIdx,
    target_chunk_idx: ChunkIdx,
    canonical_ref: SymbolRef,
  ) -> (ast::Expression<'ast>, FinalizedExprProcessHint) {
    let require_binding = &self.ctx.chunk_graph.chunk_table[cur_chunk_idx]
      .require_binding_names_for_other_chunks[&target_chunk_idx];

    let chunk = &self.ctx.chunk_graph.chunk_table[target_chunk_idx];

    // Determine chunk type: Entry (symbol owner is entry module) vs Common
    let is_entry_chunk_for_symbol = chunk.entry_module_idx() == Some(canonical_ref.owner);

    // Get wrap kind for entry chunks
    let wrap_kind = self.ctx.linking_infos[canonical_ref.owner].wrap_kind();

    // For CJS-wrapped entry chunks, we access the wrapped module directly via `require_binding`
    // or `require_binding.default` depending on OutputExports.
    // See https://github.com/rolldown/rolldown/blob/16349a4efa8d841d3b5ca8e2ebabf24a1e1c406f/crates/rolldown/src/utils/chunk/render_chunk_exports.rs?plain=1#L159-L182
    if is_entry_chunk_for_symbol && matches!(wrap_kind, WrapKind::Cjs) {
      // Cases #1-3: Entry + Cjs
      let expr = match chunk.output_exports {
        // Case #1: Entry + Cjs + Default + default → require_binding
        OutputExports::Default => self.snippet.id_ref_expr(require_binding, SPAN),
        // Cases #2-3: Entry + Cjs + Named → require_binding.default (the wrapped module)
        _ => self.snippet.literal_prop_access_member_expr_expr(require_binding, "default"),
      };
      return (expr, FinalizedExprProcessHint::FromCjsWrapKindEntry);
    }

    // All other cases: Entry with Esm/None WrapKind, or Common chunks
    // These use the exported name from exports_to_other_chunks
    let exported_name = &self.ctx.chunk_graph.chunk_table[target_chunk_idx].exports_to_other_chunks
      [&canonical_ref][0];
    let is_default_export = exported_name.as_str() == "default";

    // When OutputExports::Default, the entire module.exports IS the default value directly.
    // See https://github.com/rolldown/rolldown/issues/7833
    let expr = match (&chunk.output_exports, is_default_export) {
      // Case #7: Entry + None + Default + default → require_binding
      (OutputExports::Default, true) => self.snippet.id_ref_expr(require_binding, SPAN),
      // Cases #5, #8, #10, #12, #14: Named + default → require_binding.default
      // Cases #6, #9, #11, #13, #15: Named + named → require_binding.exportName
      _ => self.snippet.literal_prop_access_member_expr_expr(require_binding, exported_name),
    };

    (expr, FinalizedExprProcessHint::empty())
  }

  fn try_inline_constant_from_namespace_alias(
    &self,
    original_ref: SymbolRef,
    namespace_alias: &NamespaceAlias,
  ) -> Option<(ast::Expression<'ast>, FinalizedExprProcessHint)> {
    let inline_options = self.ctx.options.optimization.inline_const?;
    let canonical_ref = self.ctx.symbol_db.canonical_ref_for(original_ref);
    let named_import = self.ctx.module.named_imports.get(&canonical_ref)?;

    if !matches!(&named_import.imported, Specifier::Literal(lit) if lit != "default") {
      return None;
    }

    let import_record = &self.ctx.module.import_records[named_import.record_idx];
    let importee = import_record
      .resolved_module
      .and_then(|module_idx| self.ctx.modules[module_idx].as_normal())?;

    let resolved_export =
      self.ctx.linking_infos[importee.idx].resolved_exports.get(&namespace_alias.property_name)?;

    // Don't inline when there are conflicting CJS sources — the value could differ per branch
    // TODO(hana): Optimize this with conditional inlining
    if resolved_export.cjs_conflicting_symbol_refs.is_some() {
      return None;
    }

    let export_symbol = resolved_export.symbol_ref;
    let canonical_export_ref = self.ctx.symbol_db.canonical_ref_for(export_symbol);

    let constant_meta = self.ctx.constant_value_map.get(&canonical_export_ref)?;

    if matches!(inline_options.mode, InlineConstMode::Smart)
      && (!self.state.contains(TraverseState::SmartInlineConst) || !constant_meta.safe_to_inline)
    {
      return None;
    }
    Some((
      constant_meta.value.to_expression(AstBuilder::new(self.alloc)),
      FinalizedExprProcessHint::empty(),
    ))
  }

  /// Try to inline an enum member access from an expression. Handles:
  /// - `Direction.Up` (static member with identifier object)
  /// - `ns.Direction.Up` (chained static member via namespace import)
  /// - `Direction["Up"]` (computed member with string literal key)
  /// - `Direction?.Up` / `Direction?.["Up"]` (optional chain — enum bindings
  ///   are always defined, so `?.` is equivalent to `.`)
  fn try_inline_enum_access(&self, expr: &ast::Expression<'_>) -> Option<ast::Expression<'ast>> {
    let member = expr.get_member_expr()?;
    let (object, property_name) = match member {
      ast::MemberExpression::StaticMemberExpression(m) => (&m.object, m.property.name.as_str()),
      ast::MemberExpression::ComputedMemberExpression(m) => {
        let ast::Expression::StringLiteral(prop) = &m.expression else { return None };
        (&m.object, prop.value.as_str())
      }
      ast::MemberExpression::PrivateFieldExpression(_) => return None,
    };
    if let ast::Expression::Identifier(ident) = object {
      return self.try_inline_enum_member(ident, property_name);
    }
    // `ns.Direction.Up` — namespace-import resolution. Only for direct (non-chain)
    // static access; the chained-namespace optional case isn't handled.
    if !matches!(expr, ast::Expression::ChainExpression(_))
      && let ast::MemberExpression::StaticMemberExpression(sm) = member
    {
      return self.try_inline_chained_enum_member(sm);
    }
    None
  }

  /// Try to inline an enum member access like `Direction.Up` → `0`.
  /// Resolves the identifier to its canonical symbol, then looks up the enum member
  /// value in the owning module's `enum_member_value_map`.
  fn try_inline_enum_member(
    &self,
    ident: &ast::IdentifierReference<'_>,
    property_name: &str,
  ) -> Option<ast::Expression<'ast>> {
    let ref_id = ident.reference_id.get()?;
    let symbol_id = self.scope.scoping().get_reference(ref_id).symbol_id()?;
    let symbol_ref: SymbolRef = (self.ctx.idx, symbol_id).into();
    self.try_inline_enum_member_by_ref(symbol_ref, property_name)
  }

  /// Try to inline a chained enum member access like `ns.c.x` → `"c"`.
  /// `ns` is a namespace import (`import * as ns`), `c` is a named export (enum), `x` is the member.
  ///
  /// This is separate from `try_rewrite_member_expr` because `resolved_member_expr_refs` resolves
  /// `ns.c` → identifier `c` with `.x` as a remaining prop. The post-rewrite enum check only
  /// matches `Identifier.property` patterns, so by the time `member_expr_or_ident_ref` rebuilds
  /// `c.x`, the inlining window has passed. This method resolves all three levels in one pass.
  fn try_inline_chained_enum_member(
    &self,
    outer_expr: &ast::StaticMemberExpression<'_>,
  ) -> Option<ast::Expression<'ast>> {
    // The object must be a StaticMemberExpression (e.g., `ns.c`)
    let ast::Expression::StaticMemberExpression(inner_expr) = &outer_expr.object else {
      return None;
    };
    // The inner object must be an identifier (e.g., `ns`)
    let ast::Expression::Identifier(ns_ident) = &inner_expr.object else {
      return None;
    };

    // Resolve `ns` to its symbol
    let ref_id = ns_ident.reference_id.get()?;
    let symbol_id = self.scope.scoping().get_reference(ref_id).symbol_id()?;
    let symbol_ref: SymbolRef = (self.ctx.idx, symbol_id).into();
    let canonical_ref = self.ctx.symbol_db.canonical_ref_for(symbol_ref);

    // Find which module this namespace belongs to.
    // For `import * as ns from './enums'`, canonical_ref.owner is the importee module.
    let importee = self.ctx.modules[canonical_ref.owner].as_normal()?;

    // Find the exported symbol for the inner property name (e.g., `c`)
    let resolved_export = self.ctx.linking_infos[importee.idx]
      .resolved_exports
      .get(inner_expr.property.name.as_str())?;

    // Don't inline when there are conflicting CJS sources — the value could differ per branch
    if resolved_export.cjs_conflicting_symbol_refs.is_some() {
      return None;
    }

    let canonical_export = self.ctx.symbol_db.canonical_ref_for(resolved_export.symbol_ref);

    // Now try to inline the outer property (e.g., `x`) as an enum member
    self.try_inline_enum_member_by_ref(canonical_export, outer_expr.property.name.as_str())
  }

  fn try_inline_enum_member_by_ref(
    &self,
    symbol_ref: SymbolRef,
    property_name: &str,
  ) -> Option<ast::Expression<'ast>> {
    let canonical_ref = self.ctx.symbol_db.canonical_ref_for(symbol_ref);
    let module = self.ctx.modules[canonical_ref.owner].as_normal()?;
    let symbol_name = canonical_ref.name(self.ctx.symbol_db);
    let member_map = module.ecma_view.enum_member_value_map.get(symbol_name)?;
    let meta = member_map.get(property_name)?;
    Some(meta.value.to_expression(AstBuilder::new(self.alloc)))
  }

  fn var_declaration_to_expr_seq_and_bindings(
    &self,
    decl: &mut ast::VariableDeclaration<'ast>,
    traverse_state: TraverseState,
  ) -> Option<(Expression<'ast>, Vec<Ident<'ast>>)> {
    let should_hoist = (decl.kind.is_var() && traverse_state.contains(TraverseState::TopLevel))
      || (decl.kind.is_lexical() && traverse_state.contains(TraverseState::IsRootLevel));
    if !should_hoist {
      return None;
    }
    let mut ret = vec![];
    let exprs = decl.declarations.iter_mut().filter_map(|var_decl| {
      ret.extend(var_decl.id.get_binding_identifiers().iter().map(|item| item.name));
      // Turn `var ... = ...` to `... = ...`
      if let Some(ref mut init_expr) = var_decl.init {
        let left = var_decl.id.take_in(self.alloc).into_assignment_target(self.alloc);
        Some(ast::Expression::AssignmentExpression(
          ast::AssignmentExpression {
            left,
            right: init_expr.take_in(self.alloc),
            ..ast::AssignmentExpression::dummy(self.alloc)
          }
          .into_in(self.alloc),
        ))
      } else {
        None
      }
    });
    Some((self.builder().expression_sequence(SPAN, self.builder().vec_from_iter(exprs)), ret))
  }

  fn generate_declaration_of_module_namespace_object(&self) -> Vec<ast::Statement<'ast>> {
    if !self.module_namespace_included {
      return vec![];
    }

    let binding_name_for_namespace_object_ref =
      self.canonical_name_for(self.ctx.module.namespace_object_ref);

    // construct `{ prop_name: () => returned, ... }`
    let mut arg_obj_expr = ast::ObjectExpression::dummy(self.alloc);

    // Even if the module namespace is included, some exports may not be used due to `optimize_facade_dynamic_entry_chunks`
    // https://github.com/rolldown/rolldown/blob/d6d65f9080e427cd9feef56eb7a110fbcf6c1414/crates/rolldown/src/stages/generate_stage/chunk_optimizer.rs#L347-L354
    arg_obj_expr.properties.extend(self.ctx.linking_info.canonical_exports(false).filter_map(
      |(export, resolved_export)| {
        // Even if the symbol is not marked as used (generated inside module),
        // it should be included in the namespace export.
        let is_inlinable_constant = self
          .ctx
          .constant_value_map
          .get(&self.ctx.symbol_db.canonical_ref_for(resolved_export.symbol_ref))
          .is_some_and(|meta| !meta.commonjs_export);
        if !self.ctx.used_symbol_refs.contains(&resolved_export.symbol_ref)
          && !is_inlinable_constant
        {
          return None;
        }
        // prop_name: () => returned
        let prop_name = export;
        let (returned, _) =
          self.finalized_expr_for_symbol_ref(resolved_export.symbol_ref, false, false);
        Some(ast::ObjectPropertyKind::ObjectProperty(
          ast::ObjectProperty {
            // `__proto__` has special semantics in object literals - it sets the prototype
            // instead of creating a property. Use computed property syntax for it.
            key: if is_validate_identifier_name(prop_name) && prop_name != "__proto__" {
              ast::PropertyKey::StaticIdentifier(
                self.snippet.id_name(prop_name, SPAN).into_in(self.alloc),
              )
            } else {
              ast::PropertyKey::StringLiteral(self.snippet.alloc_string_literal(prop_name, SPAN))
            },
            value: self.snippet.only_return_arrow_expr(returned),
            computed: prop_name == "__proto__",
            ..ast::ObjectProperty::dummy(self.alloc)
          }
          .into_in(self.alloc),
        ))
      },
    ));

    // if there is no export, we should generate `var ns = {}` instead of `var ns = __exportAll({})`
    // else construct `__exportAll({ prop_name: () => returned, ... })`
    let module_namespace_rhs =
      if arg_obj_expr.properties.is_empty() && !self.ctx.options.generated_code.symbols {
        Expression::ObjectExpression(self.builder().alloc(arg_obj_expr))
      } else {
        let obj_expr = ast::Argument::ObjectExpression(arg_obj_expr.into_in(self.alloc));
        let args = if self.ctx.options.generated_code.symbols {
          self.snippet.builder.vec_from_iter([obj_expr])
        } else {
          self.snippet.builder.vec_from_iter([
            obj_expr,
            ast::Argument::NumericLiteral(self.snippet.builder.alloc_numeric_literal(
              SPAN,
              1.0,
              None,
              NumberBase::Decimal,
            )),
          ])
        };
        self.snippet.builder.expression_call_with_pure(
          SPAN,
          self.finalized_expr_for_runtime_symbol("__exportAll"),
          NONE,
          args,
          false,
          true,
        )
      };

    // construct `var [binding_name_for_namespace_object_ref] = __exportAll(...)`
    let decl_stmt =
      self.snippet.var_decl_stmt(binding_name_for_namespace_object_ref, module_namespace_rhs);

    let export_all_externals_rec_ids = &self.ctx.linking_info.star_exports_from_external_modules;

    let mut re_export_external_stmts: Option<_> = None;
    if !export_all_externals_rec_ids.is_empty() {
      // construct `__reExport(importer_exports, importee_exports)`
      let re_export_fn_ref = self.finalized_expr_for_runtime_symbol("__reExport");
      match self.ctx.options.format {
        OutputFormat::Esm => {
          let stmts = export_all_externals_rec_ids.iter().copied().flat_map(|idx| {
            let rec = &self.ctx.module.import_records[idx];
            if rec.meta.contains(ImportRecordMeta::EntryLevelExternal)
              && !self
                .ctx
                .linking_info
                .module_namespace_included_reason
                .contains(ModuleNamespaceIncludedReason::Unknown)
            {
              return vec![];
            }
            // importee_exports
            let importee_namespace_name = self.canonical_name_for(rec.namespace_ref);
            let Some(Module::External(module)) =
              rec.resolved_module.and_then(|module_idx| self.ctx.modules.get(module_idx))
            else {
              return vec![];
            };
            let importee_name = &module.get_import_path(self.ctx.chunk, self.ctx.resolved_paths);
            let call_expr = self.snippet.re_export_call_expr(
              re_export_fn_ref.clone_in(self.alloc),
              self.snippet.id_ref_expr(binding_name_for_namespace_object_ref, SPAN),
              self.snippet.id_ref_expr(importee_namespace_name, SPAN),
            );
            vec![
              // Insert `import * as ns from 'ext'`external module in esm format
              self.snippet.import_star_stmt(importee_name, importee_namespace_name),
              // Insert `__reExport(foo_exports, ns)`
              self.snippet.builder.statement_expression(
                SPAN,
                Expression::CallExpression(call_expr.into_in(self.alloc)),
              ),
            ]
          });
          re_export_external_stmts = Some(stmts.collect::<Vec<_>>());
        }
        OutputFormat::Cjs | OutputFormat::Iife | OutputFormat::Umd => {
          let stmts = export_all_externals_rec_ids.iter().copied().filter_map(|idx| {
            // Insert `__reExport(importer_exports, require('ext'))`
            let re_export_fn_ref = self.finalized_expr_for_runtime_symbol("__reExport");
            // importer_exports
            let (importer_namespace_ref_expr, _) = self.finalized_expr_for_symbol_ref(
              self.ctx.module.namespace_object_ref,
              false,
              false,
            );
            let rec = &self.ctx.module.import_records[idx];
            let importee = rec.resolved_module.map(|module_idx| &self.ctx.modules[module_idx])?;

            let re_export_call_expr = self.snippet.re_export_call_expr(
              re_export_fn_ref.clone_in(self.alloc),
              importer_namespace_ref_expr,
              self.snippet.call_expr_with_arg_expr_expr(
                "require",
                self.snippet.string_literal_expr(importee.id().as_str(), SPAN),
              ),
            );

            Some(self.snippet.builder.statement_expression(
              SPAN,
              Expression::CallExpression(re_export_call_expr.into_in(self.alloc)),
            ))
          });
          re_export_external_stmts = Some(stmts.collect());
        }
      }
    }

    let mut ret = vec![decl_stmt];
    ret.extend(re_export_external_stmts.unwrap_or_default());

    ret
  }

  // Handle `import.meta.xxx` expression
  pub fn try_rewrite_import_meta_prop_expr(
    &self,
    member_expr: &ast::StaticMemberExpression<'ast>,
  ) -> Option<Expression<'ast>> {
    if member_expr.object.is_import_meta() {
      let original_expr_span = member_expr.span;
      let is_node_cjs = matches!(
        (self.ctx.options.platform, &self.ctx.options.format),
        (Platform::Node, OutputFormat::Cjs)
      );

      let property_name = member_expr.property.name.as_str();
      match property_name {
        // Try to polyfill `import.meta.url`
        "url" => {
          let new_expr = if is_node_cjs {
            // Replace it with `require('url').pathToFileURL(__filename).href`

            // require('url')
            let require_call = self.snippet.builder.alloc_call_expression(
              SPAN,
              self.snippet.builder.expression_identifier(SPAN, "require"),
              oxc::ast::NONE,
              self.snippet.builder.vec1(ast::Argument::StringLiteral(
                self.snippet.builder.alloc_string_literal(SPAN, "url", None),
              )),
              false,
            );

            // require('url').pathToFileURL
            let require_path_to_file_url = self.snippet.builder.alloc_static_member_expression(
              SPAN,
              ast::Expression::CallExpression(require_call),
              self.snippet.builder.identifier_name(SPAN, "pathToFileURL"),
              false,
            );

            // require('url').pathToFileURL(__filename)
            let require_path_to_file_url_call = self.snippet.builder.alloc_call_expression(
              SPAN,
              ast::Expression::StaticMemberExpression(require_path_to_file_url),
              oxc::ast::NONE,
              self.snippet.builder.vec1(ast::Argument::Identifier(
                self.snippet.builder.alloc_identifier_reference(SPAN, "__filename"),
              )),
              false,
            );

            // require('url').pathToFileURL(__filename).href
            let require_path_to_file_url_href =
              self.snippet.builder.alloc_static_member_expression(
                original_expr_span,
                ast::Expression::CallExpression(require_path_to_file_url_call),
                self.snippet.builder.identifier_name(SPAN, "href"),
                false,
              );
            Some(ast::Expression::StaticMemberExpression(require_path_to_file_url_href))
          } else {
            // If we don't support polyfill `import.meta.url` in this platform and format, we just keep it as it is
            // so users may handle it in their own way.
            None
          };
          return new_expr;
        }
        "dirname" | "filename" => {
          let name = self.snippet.atom(&format!("__{property_name}"));
          return is_node_cjs.then_some(ast::Expression::Identifier(
            self.snippet.builder.alloc_identifier_reference(SPAN, name),
          ));
        }
        _ => {}
      }
      return self.rewrite_rollup_file_url(property_name);
    }
    None
  }

  fn rewrite_rollup_file_url(&self, property_name: &str) -> Option<Expression<'ast>> {
    // rewrite `import.meta.ROLLUP_FILE_URL_<referenceId>`
    if let Some(reference_id) = property_name.strip_prefix("ROLLUP_FILE_URL_") {
      // compute relative path from chunk to asset
      let Ok(asset_file_name) = self.ctx.file_emitter.get_file_name(reference_id) else {
        return None;
      };
      let absolute_asset_file_name = asset_file_name
        .absolutize_with(self.ctx.options.cwd.as_path().join(&self.ctx.options.out_dir));
      let relative_asset_path = &self.ctx.chunk.relative_path_for(&absolute_asset_file_name);

      // new URL({relative_asset_path}, import.meta.url).href
      // TODO: needs import.meta.url polyfill for non esm
      let new_expr = ast::Expression::StaticMemberExpression(
        self.snippet.builder.alloc_static_member_expression(
          SPAN,
          self.snippet.builder.expression_new(
            SPAN,
            self.snippet.builder.expression_identifier(SPAN, "URL"),
            NONE,
            self.snippet.builder.vec_from_array([
              ast::Argument::StringLiteral(self.snippet.builder.alloc_string_literal(
                SPAN,
                self.snippet.builder.str(relative_asset_path),
                None,
              )),
              ast::Argument::StaticMemberExpression(
                self.snippet.builder.alloc_static_member_expression(
                  SPAN,
                  self.snippet.builder.expression_meta_property(
                    SPAN,
                    self.snippet.builder.identifier_name(SPAN, "import"),
                    self.snippet.builder.identifier_name(SPAN, "meta"),
                  ),
                  self.snippet.builder.identifier_name(SPAN, "url"),
                  false,
                ),
              ),
            ]),
          ),
          self.snippet.builder.identifier_name(SPAN, "href"),
          false,
        ),
      );
      return Some(new_expr);
    }
    None
  }

  pub fn handle_new_url_with_string_literal_and_import_meta_url(
    &self,
    expr: &mut ast::NewExpression<'ast>,
  ) -> Option<()> {
    let &rec_idx = self.ctx.module.new_url_references.get(&expr.span())?;
    let rec = &self.ctx.module.import_records[rec_idx];
    let is_callee_global_url = matches!(expr.callee.as_identifier(), Some(ident) if ident.name == "URL" && self.is_global_identifier_reference(ident));

    if !is_callee_global_url {
      return None;
    }

    let is_second_arg_import_meta_url = expr
      .arguments
      .get(1)
      .is_some_and(|arg| arg.as_expression().is_some_and(ExpressionExt::is_import_meta_url));

    if !is_second_arg_import_meta_url {
      return None;
    }

    let first_arg_expr = expr.arguments.first_mut().and_then(|a| a.as_expression_mut())?;
    // bail if not a static string literal
    match &first_arg_expr {
      ast::Expression::StringLiteral(_) => {}
      ast::Expression::TemplateLiteral(tpl) if tpl.is_no_substitution_template() => {}
      _ => return None,
    }

    let importee =
      rec.resolved_module.and_then(|module_idx| self.ctx.modules[module_idx].as_normal())?;

    // Look up the emitted asset filename via the FileEmitter bridge
    let ref_id = self.ctx.file_emitter.file_ref_for_module(&importee.id)?;
    let filename = self.ctx.file_emitter.get_file_name(&ref_id).ok()?;
    let abs_path = self.ctx.options.cwd.join(&self.ctx.options.out_dir).join(filename.as_str());
    let import_path = self.ctx.chunk.relative_path_for(abs_path.as_path());

    *first_arg_expr = self.snippet.string_literal_expr(&import_path, first_arg_expr.span());
    None
  }

  /// try rewrite `foo_exports.bar` or `foo_exports['bar']`  to `bar` directly
  /// try rewrite `import.meta`
  fn try_rewrite_member_expr(
    &self,
    member_expr: &ast::MemberExpression<'ast>,
  ) -> Option<Expression<'ast>> {
    let span = member_expr.span();
    match self.ctx.linking_info.resolved_member_expr_refs.get(&span) {
      Some(MemberExprRefResolution {
        resolved: object_ref,
        prop_and_related_span_list: props,
        target_commonjs_exported_symbol: target_commonjs_exported_symbol_meta,
        ..
      }) => object_ref
        .map(|object_ref| {
          let mut is_inlined_commonjs_export = false;
          let object_ref_expr = if let Some(export_meta) = target_commonjs_exported_symbol_meta
            .and_then(|target_commonjs_exported_symbol_meta| {
              self.ctx.constant_value_map.get(&target_commonjs_exported_symbol_meta.0)
            }) {
            is_inlined_commonjs_export = true;
            export_meta.value.to_expression(AstBuilder::new(self.alloc))
          } else {
            let (object_ref_expr, _) = self.finalized_expr_for_symbol_ref(
              object_ref,
              false,
              target_commonjs_exported_symbol_meta
                .is_some_and(|(_symbol, is_exports_default)| !is_exports_default),
            );
            object_ref_expr
          };
          self.snippet.member_expr_or_ident_ref(
            object_ref_expr,
            // For commonjs member_expr resolving, the resolved ref is always namespace_alias,
            // so the props actually include the exported name, when inline member_expr access of commonjs exported
            // symbol, we should skip the first prop
            &props[usize::from(is_inlined_commonjs_export)..],
            span,
          )
        })
        .or_else(|| Some(self.snippet.member_expr_with_void_zero_object(props, span))),
      _ => {
        let MemberExpression::StaticMemberExpression(static_member_expr) = member_expr else {
          return None;
        };
        self.try_rewrite_import_meta_prop_expr(static_member_expr)
      }
    }
  }

  /// Try to rewrite a member expression assignment target when the object is a default import from CJS.
  /// For `import_src.log = value`, if `import_src` is from a CJS module, we need to rewrite to
  /// `import_src.default.log = value` because __toESM creates getter-only properties.
  fn try_rewrite_cjs_member_expr_assignment_target(
    &self,
    target: &ast::SimpleAssignmentTarget<'ast>,
  ) -> Option<ast::SimpleAssignmentTarget<'ast>> {
    let (id_ref, property) = match target {
      ast::SimpleAssignmentTarget::StaticMemberExpression(member_expr) => {
        let ast::Expression::Identifier(id_ref) = &member_expr.object else {
          return None;
        };
        (id_ref, CjsMemberProperty::Static(member_expr.property.name.as_str()))
      }
      ast::SimpleAssignmentTarget::ComputedMemberExpression(member_expr) => {
        let ast::Expression::Identifier(id_ref) = &member_expr.object else {
          return None;
        };
        (id_ref, CjsMemberProperty::Computed(&member_expr.expression))
      }
      _ => return None,
    };

    // Resolve the identifier to check if it's a CJS default import
    let reference_id = id_ref.reference_id.get()?;
    let symbol_id = self.scope.symbol_id_for(reference_id)?;
    let symbol_ref: SymbolRef = (self.ctx.idx, symbol_id).into();
    let canonical_ref = self.ctx.symbol_db.canonical_ref_for(symbol_ref);
    let symbol = self.ctx.symbol_db.get(canonical_ref);

    // Check if this symbol has a namespace_alias with property_name "default"
    // This indicates it's a default import from a CJS module
    let ns_alias = symbol.namespace_alias.as_ref()?;
    if ns_alias.property_name.as_str() != "default" {
      return None;
    }

    // Build: ns_name.default
    // IMPORTANT: Use SPAN (0-0) for the new member expression to avoid being matched
    // by resolved_member_expr_refs lookup which uses span as key
    let ns_name = self.canonical_name_for(ns_alias.namespace_ref);
    let ns_id_ref = self.snippet.id_ref_expr(ns_name, SPAN);
    let default_access =
      ast::Expression::StaticMemberExpression(self.snippet.builder.alloc_static_member_expression(
        SPAN,
        ns_id_ref,
        self.snippet.id_name("default", SPAN),
        false,
      ));

    // Create: ns_name.default.property or ns_name.default[expression]
    match property {
      CjsMemberProperty::Static(property_name) => {
        let final_access = self.snippet.builder.alloc_static_member_expression(
          SPAN,
          default_access,
          self.snippet.id_name(property_name, SPAN),
          false,
        );
        Some(ast::SimpleAssignmentTarget::StaticMemberExpression(final_access))
      }
      CjsMemberProperty::Computed(expr) => {
        // Finalize the computed key expression (e.g. inline constants) so that an
        // inlined value is emitted instead of a reference to a tree-shaken binding.
        let finalized_expr = match expr {
          ast::Expression::Identifier(ident_ref) => self
            .try_rewrite_identifier_reference_expr(ident_ref, false)
            .unwrap_or_else(|| expr.clone_in(self.alloc)),
          _ => expr.clone_in(self.alloc),
        };
        let final_access = self.snippet.builder.alloc_computed_member_expression(
          SPAN,
          default_access,
          finalized_expr,
          false,
        );
        Some(ast::SimpleAssignmentTarget::ComputedMemberExpression(final_access))
      }
    }
  }

  /// Returns `(original_name, canonical_name)` for keep_names processing.
  /// Returns `Some` only if the name has been deconflicted (renamed).
  fn get_keep_name_info(&self, id: KeepNameId) -> Option<(&'me str, &'me str)> {
    let symbol_ref: SymbolRef = match id {
      KeepNameId::SymbolId(symbol_id) => (self.ctx.idx, symbol_id).into(),
      KeepNameId::ReferenceId(reference_id) => {
        let symbol_id = self.scope.symbol_id_for(reference_id)?;
        (self.ctx.idx, symbol_id).into()
      }
      KeepNameId::CompactStr(_) => {
        return None;
      }
    };

    let original_name = symbol_ref.name(self.ctx.symbol_db);
    let canonical_name = self.canonical_name_for(symbol_ref);
    (original_name != canonical_name).then_some((original_name, canonical_name))
  }

  /// rewrite toplevel `class ClassName {}` to `var ClassName = class {}`
  fn get_transformed_class_decl(
    &self,
    class: &mut allocator::Box<'ast, ast::Class<'ast>>,
  ) -> Option<ast::Declaration<'ast>> {
    let scope_id = class.scope_id.get()?;

    if self.scope.scoping().scope_parent_id(scope_id) != Some(self.scope.scoping().root_scope_id())
    {
      return None;
    }

    let id = class.id.take()?;

    if let Some(symbol_id) = id.symbol_id.get() {
      if self.ctx.module.self_referenced_class_decl_symbol_ids.contains(&symbol_id) {
        // class T { static a = new T(); }
        // needs to rewrite to `var T = class T { static a = new T(); }`
        let mut id = id.clone();
        let new_name = self.canonical_name_for((self.ctx.idx, symbol_id).into());
        id.name = self.snippet.atom(new_name).into();
        class.id = Some(id);
      }
    }
    Some(self.snippet.builder.declaration_variable(
      class.span,
      VariableDeclarationKind::Var,
      self.snippet.builder.vec1(self.snippet.builder.variable_declarator(
        SPAN,
        VariableDeclarationKind::Var,
        ast::BindingPattern::BindingIdentifier(self.snippet.builder.alloc(id)),
        NONE,
        Some(Expression::ClassExpression(ArenaBox::new_in(
          class.as_mut().take_in(self.alloc),
          self.alloc,
        ))),
        false,
      )),
      false,
    ))
  }

  fn try_rewrite_global_require_call(
    &self,
    call_expr: &mut ast::CallExpression<'ast>,
  ) -> Option<Expression<'ast>> {
    if call_expr.is_global_require_call(self.scope) && !call_expr.span.is_unspanned() {
      //  `require` calls that can't be recognized by rolldown are ignored in scanning, so they were not stored in `NormalModule#imports`.
      //  we just keep these `require` calls as it is
      if let Some(rec_idx) = self.ctx.module.imports.get(&call_expr.span).copied() {
        let rec = &self.ctx.module.import_records[rec_idx];
        let module_idx = rec.resolved_module?;
        // use `__require` instead of `require`
        if rec.meta.contains(ImportRecordMeta::CallRuntimeRequire) {
          *call_expr.callee.get_inner_expression_mut() =
            self.finalized_expr_for_runtime_symbol("__require");
        }
        let rewrite_ast = match &self.ctx.modules[module_idx] {
          Module::Normal(importee) => {
            match importee.module_type {
              ModuleType::Json => {
                // Nodejs treats json files as an esm module with a default export and rolldown follows this behavior.
                // And to make sure the runtime behavior is correct, we need to rewrite `require('xxx.json')` to `require('xxx.json').default` to align with the runtime behavior of nodejs.

                // Rewrite `require(...)` to `require_xxx(...)` or `(init_xxx(), __toCommonJS(xxx_exports).default)`
                let importee_linking_info = &self.ctx.linking_infos[importee.idx];
                let (wrap_ref_expr, hint) = self.finalized_expr_for_symbol_ref(
                  importee_linking_info.wrapper_ref.unwrap(),
                  false,
                  false,
                );
                if matches!(importee.exports_kind, ExportsKind::CommonJs) {
                  if hint.contains(FinalizedExprProcessHint::FromCjsWrapKindEntry) {
                    Some(wrap_ref_expr)
                  } else {
                    Some(ast::Expression::CallExpression(
                      self.snippet.alloc_simple_call_expr(wrap_ref_expr),
                    ))
                  }
                } else {
                  let (ns_name, _) =
                    self.finalized_expr_for_symbol_ref(importee.namespace_object_ref, false, false);
                  let to_commonjs_ref_name = self.finalized_expr_for_runtime_symbol("__toCommonJS");
                  Some(
                    self.snippet.seq2_in_paren_expr(
                      ast::Expression::CallExpression(
                        self.snippet.alloc_simple_call_expr(wrap_ref_expr),
                      ),
                      ast::Expression::StaticMemberExpression(
                        ast::StaticMemberExpression {
                          object: self.snippet.call_expr_with_arg_expr(
                            to_commonjs_ref_name,
                            ns_name,
                            false,
                          ),
                          property: self.snippet.id_name("default", SPAN),
                          ..ast::StaticMemberExpression::dummy(self.alloc)
                        }
                        .into_in(self.alloc),
                      ),
                    ),
                  )
                }
              }
              _ => {
                // Rewrite `require(...)` to `require_xxx(...)` or `(init_xxx(), __toCommonJS(xxx_exports))`
                let importee_linking_info = &self.ctx.linking_infos[importee.idx];
                // `init_xxx` or `require_xxx`
                let (wrap_ref_expr, hint) = self.finalized_expr_for_symbol_ref(
                  importee_linking_info.wrapper_ref.unwrap(),
                  false,
                  false,
                );

                // `init_xxx()` or `require_xxx()` or `require_xxx`
                let wrap_ref_call_expr =
                  if hint.contains(FinalizedExprProcessHint::FromCjsWrapKindEntry) {
                    wrap_ref_expr
                  } else {
                    ast::Expression::CallExpression(self.snippet.builder.alloc_call_expression(
                      SPAN,
                      wrap_ref_expr,
                      NONE,
                      self.snippet.builder.vec(),
                      false,
                    ))
                  };

                if matches!(importee.exports_kind, ExportsKind::CommonJs)
                  || rec.meta.contains(ImportRecordMeta::IsRequireUnused)
                {
                  // `init_xxx()`
                  Some(wrap_ref_call_expr)
                } else {
                  // `xxx_exports`
                  let (namespace_object_ref_expr, _) =
                    self.finalized_expr_for_symbol_ref(importee.namespace_object_ref, false, false);

                  let is_json_module = rec.meta.contains(ImportRecordMeta::JsonModule);

                  // `__toCommonJS`
                  let to_commonjs_expr = self.finalized_expr_for_runtime_symbol("__toCommonJS");
                  // `__toCommonJS(xxx_exports)`
                  let to_commonjs_call_expr =
                    ast::Expression::CallExpression(self.snippet.builder.alloc_call_expression(
                      SPAN,
                      to_commonjs_expr,
                      NONE,
                      self.snippet.builder.vec1(ast::Argument::from(namespace_object_ref_expr)),
                      false,
                    ));

                  let final_expr = if is_json_module {
                    // `__toCommonJS(xxx_exports).default`
                    Expression::from(self.snippet.builder.member_expression_static(
                      SPAN,
                      to_commonjs_call_expr,
                      self.snippet.id_name("default", SPAN),
                      false,
                    ))
                  } else {
                    to_commonjs_call_expr
                  };

                  // `(init_xxx(), __toCommonJS(xxx_exports))`
                  Some(self.snippet.seq2_in_paren_expr(wrap_ref_call_expr, final_expr))
                }
              }
            }
          }
          Module::External(importee) => {
            let request_path =
              call_expr.arguments.get_mut(0).expect("require should have an argument");
            // Rewrite `require('xxx')` to `require('fs')`, if there is an alias that maps 'xxx' to 'fs'
            *request_path = ast::Argument::StringLiteral(self.snippet.alloc_string_literal(
              &importee.get_import_path(self.ctx.chunk, self.ctx.resolved_paths),
              request_path.span(),
            ));
            None
          }
        };
        return rewrite_ast;
      }
    }
    None
  }

  fn try_rewrite_inline_dynamic_import_expr(
    &self,
    import_expr: &oxc::allocator::Box<'ast, ImportExpression<'ast>>,
  ) -> Option<Expression<'ast>> {
    let rec_idx = self.ctx.module.imports.get(&import_expr.span)?;
    let rec = &self.ctx.module.import_records[*rec_idx];
    let importee_id = rec.resolved_module?;

    if rec.meta.contains(ImportRecordMeta::DeadDynamicImport) {
      return Some(
        self
          .snippet
          .promise_resolve_then_call_expr(self.snippet.object_freeze_dynamic_import_polyfill()),
      );
    }

    if self.ctx.options.code_splitting.is_disabled() {
      match &self.ctx.modules[importee_id] {
        Module::Normal(importee) => {
          let importee_linking_info = &self.ctx.linking_infos[importee_id];
          let new_expr = match importee_linking_info.wrap_kind() {
            WrapKind::Esm => {
              // Rewrite `import('./foo.mjs')` to `(init_foo(), foo_exports)`
              let importee_linking_info = &self.ctx.linking_infos[importee_id];

              // `init_foo`
              let importee_wrapper_ref_name =
                self.canonical_name_for(importee_linking_info.wrapper_ref.unwrap());

              // `foo_exports`
              let importee_namespace_name = self.canonical_name_for(importee.namespace_object_ref);

              if importee_linking_info.is_tla_or_contains_tla_dependency {
                // `init_foo().then(function() { return foo_exports })`
                Some(self.snippet.callee_then_call_expr(
                  self.snippet.call_expr_expr(importee_wrapper_ref_name),
                  self.snippet.id_ref_expr(importee_namespace_name, SPAN),
                ))
              } else {
                //  Promise.resolve().then(function() { return (init_foo(), foo_exports) })
                Some(self.snippet.promise_resolve_then_call_expr(self.snippet.seq2_in_paren_expr(
                  self.snippet.call_expr_expr(importee_wrapper_ref_name),
                  self.snippet.id_ref_expr(importee_namespace_name, SPAN),
                )))
              }
            }
            WrapKind::Cjs => {
              //  `__toESM(require_foo())`
              let to_esm_fn_name = self.canonical_name_for_runtime("__toESM");
              let importee_wrapper_ref_name =
                self.canonical_name_for(importee_linking_info.wrapper_ref.unwrap());
              Some(
                self.snippet.promise_resolve_then_call_expr(
                  self.snippet.wrap_with_to_esm(
                    self
                      .snippet
                      .builder
                      .expression_identifier(SPAN, self.snippet.builder.str(to_esm_fn_name)),
                    self.snippet.call_expr_expr(importee_wrapper_ref_name),
                    self.ctx.module.should_consider_node_esm_spec_for_dynamic_import(),
                  ),
                ),
              )
            }
            WrapKind::None => {
              // The nature of `import()` is to load the module dynamically/lazily, so imported modules would
              // must be wrapped, so we could make sure the module is executed lazily.
              if cfg!(debug_assertions) {
                unreachable!()
              }
              None
            }
          };
          return new_expr;
        }
        Module::External(_) => {
          // iife format doesn't support external module
        }
      }
    }
    None
  }

  #[expect(clippy::too_many_lines)]
  fn remove_unused_top_level_stmt(&mut self, program: &mut ast::Program<'ast>) -> usize {
    let mut last_import_stmt_idx = None;

    let old_body = program.body.take_in(self.alloc);
    // the first statement info is the namespace variable declaration
    // skip first statement info to make sure `program.body` has same index as `stmt_infos`
    old_body.into_iter().enumerate().zip(self.ctx.stmt_infos.iter_enumerated().skip(1)).for_each(
      |((_top_stmt_idx, mut top_stmt), (stmt_info_idx, _stmt_info))| {
        let is_stmt_included = self.ctx.linking_info.stmt_info_included.has_bit(stmt_info_idx);

        if !is_stmt_included {
          // For ESM-wrapped modules, excluded re-export statements still need
          // init calls for correct initialization order.
          if matches!(self.ctx.linking_info.wrap_kind(), WrapKind::Esm) {
            let rec_idx = if let Some(export_all) = top_stmt.as_export_all_declaration() {
              Some(self.ctx.module.imports[&export_all.span])
            } else if let Some(named_decl) = top_stmt.as_export_named_declaration() {
              named_decl.source.as_ref().map(|_| self.ctx.module.imports[&named_decl.span])
            } else {
              None
            };
            if let Some(importee_idx) =
              rec_idx.and_then(|idx| self.ctx.module.import_records[idx].resolved_module)
            {
              self.generate_transitive_esm_init(importee_idx, &mut program.body);
            }
          }
          return;
        }

        let is_module_decl = is_stmt_included && top_stmt.is_module_declaration_with_source();

        if let Some(import_decl) = top_stmt.as_import_declaration() {
          let span = import_decl.span;
          let rec_idx = self.ctx.module.imports[&import_decl.span];
          if self.transform_or_remove_import_export_stmt(&mut top_stmt, rec_idx) {
            for comment in &mut program.comments {
              if comment.attached_to == span.start {
                comment.attached_to = 0;
              }
              if comment.attached_to > span.start {
                break;
              }
            }
            return;
          }
        } else if let Some(export_all_decl) = top_stmt.as_export_all_declaration() {
          let rec_idx = self.ctx.module.imports[&export_all_decl.span];
          // "export * as ns from 'path'"
          if let Some(_alias) = &export_all_decl.exported {
            if self.transform_or_remove_import_export_stmt(&mut top_stmt, rec_idx) {
              return;
            }
          } else {
            // "export * from 'path'"
            let rec = &self.ctx.module.import_records[rec_idx];
            let Some(module_idx) = rec.resolved_module else { return };
            match &self.ctx.modules[module_idx] {
              Module::Normal(importee) => {
                let importee_linking_info = &self.ctx.linking_infos[importee.idx];
                if matches!(importee_linking_info.wrap_kind(), WrapKind::None)
                  && let Some(init_stmt) = self.wrapped_esm_init_stmt_for_import_record(rec_idx)
                {
                  program.body.push(init_stmt);
                }

                if matches!(importee_linking_info.wrap_kind(), WrapKind::Esm)
                // If it is a inner concatenated module, we should not call its wrapper here
                  && !matches!(
                    importee_linking_info.concatenated_wrapped_module_kind,
                    ConcatenateWrappedModuleKind::Inner
                  )
                {
                  let wrapper_ref_name =
                    self.canonical_name_for(importee_linking_info.wrapper_ref.unwrap());
                  let mut init_expr = self.snippet.call_expr_expr(wrapper_ref_name);
                  if importee_linking_info.is_tla_or_contains_tla_dependency {
                    init_expr = ast::Expression::AwaitExpression(
                      self.snippet.builder.alloc_await_expression(SPAN, init_expr),
                    );
                  }
                  program.body.push(self.snippet.builder.statement_expression(SPAN, init_expr));
                }

                match importee.exports_kind {
                  ExportsKind::Esm => {
                    if importee_linking_info.has_dynamic_exports {
                      let re_export_fn_ref = self.finalized_expr_for_runtime_symbol("__reExport");
                      // exports
                      let (importer_namespace_ref, _) = self.finalized_expr_for_symbol_ref(
                        self.ctx.module.namespace_object_ref,
                        false,
                        false,
                      );
                      // otherExports
                      let (importee_namespace_ref, _) = self.finalized_expr_for_symbol_ref(
                        importee.namespace_object_ref,
                        false,
                        false,
                      );

                      let call_expr = self.snippet.re_export_call_expr(
                        re_export_fn_ref,
                        importer_namespace_ref,
                        importee_namespace_ref,
                      );
                      // __reExport(exports, otherExports)
                      let stmt = ast::Statement::ExpressionStatement(
                        self.builder().alloc_expression_statement(
                          SPAN,
                          Expression::CallExpression(call_expr.into_in(self.alloc)),
                        ),
                      );
                      program.body.push(stmt);
                    }
                  }
                  ExportsKind::CommonJs => {
                    // If **commonjs** treeshake is enabled, the module_namespace is included on
                    // demand, we should skip generate related `__reExport` statements
                    // See: https://github.com/rolldown/rolldown/blob/60fc81ada3955ce84b38a5edbb33a169d1f89f15/crates/rolldown/src/stages/link_stage/reference_needed_symbols.rs?plain=1#L148-L150
                    if !self.module_namespace_included {
                      return;
                    }

                    let re_export_fn_name = self.finalized_expr_for_runtime_symbol("__reExport");

                    // importer_exports
                    let (importer_namespace_ref, _) = self.finalized_expr_for_symbol_ref(
                      self.ctx.module.namespace_object_ref,
                      false,
                      false,
                    );

                    // __toESM
                    let to_esm_fn_ref = self.finalized_expr_for_runtime_symbol("__toESM");

                    // require_foo
                    let (importee_wrapper_ref_expr, _) = self.finalized_expr_for_symbol_ref(
                      importee_linking_info.wrapper_ref.unwrap(),
                      false,
                      false,
                    );

                    let call_expr = self.snippet.re_export_call_expr(
                      re_export_fn_name,
                      importer_namespace_ref,
                      self.snippet.wrap_with_to_esm(
                        to_esm_fn_ref,
                        ast::Expression::CallExpression(
                          self.snippet.builder.alloc_call_expression(
                            SPAN,
                            importee_wrapper_ref_expr,
                            NONE,
                            self.snippet.builder.vec(),
                            false,
                          ),
                        ),
                        self.ctx.module.should_consider_node_esm_spec_for_static_import(),
                      ),
                    );

                    // __reExport(importer_exports, __toESM(require_foo()))
                    let stmt = ast::Statement::ExpressionStatement(
                      self.builder().alloc_expression_statement(
                        SPAN,
                        Expression::CallExpression(call_expr.into_in(self.alloc)),
                      ),
                    );
                    program.body.push(stmt);
                  }
                  ExportsKind::None => {}
                }
              }
              Module::External(_importee) => {
                match self.ctx.options.format {
                  rolldown_common::OutputFormat::Esm
                  | rolldown_common::OutputFormat::Iife
                  | rolldown_common::OutputFormat::Umd
                  | rolldown_common::OutputFormat::Cjs => {
                    // Just remove the statement
                    return;
                  }
                }
              }
            }

            return;
          }
        } else if let Some(default_decl) = top_stmt.as_export_default_declaration_mut() {
          use ast::ExportDefaultDeclarationKind;
          let default_decl_span = default_decl.span;
          match &mut default_decl.declaration {
            // Special case: when exporting an identifier that's already the default export symbol
            ast::ExportDefaultDeclarationKind::Identifier(id)
              if self.scope.scoping().get_reference(id.reference_id()).symbol_id().is_some_and(
                |symbol_id| symbol_id == self.ctx.module.default_export_ref.symbol,
              ) =>
            {
              // "let a = ..;export default a" => "let a = ..;" (no transformation needed)
              return;
            }
            decl @ ast::match_expression!(ExportDefaultDeclarationKind) => {
              let expr = decl.to_expression_mut();
              let canonical_name_for_default_export_ref =
                self.canonical_name_for(self.ctx.module.default_export_ref);

              // Check if we need to add __name() helper for anonymous function/class expressions or arrow functions
              let mut init_expr = expr.take_in(self.alloc);
              if self.ctx.options.keep_names {
                let inner_expr = init_expr.without_parentheses_mut();
                let needs_inline_name = match inner_expr {
                  ast::Expression::FunctionExpression(func) if func.id.is_none() => true,
                  ast::Expression::ClassExpression(class_expression)
                    if class_expression.id.is_none() =>
                  {
                    if let Some(element) = self.keep_name_helper_for_class(
                      Some(KeepNameId::CompactStr(&CompactStr::from("default"))),
                      &class_expression.body,
                    ) {
                      class_expression.body.body.insert(0, element);
                    }
                    false
                  }
                  ast::Expression::ArrowFunctionExpression(_) => true,
                  _ => false,
                };

                if needs_inline_name {
                  // Wrap the expression inline: `__name(<expr>, "default")`
                  // This matches esbuild's output and allows tree-shaking with PURE annotation
                  let name_ref = self.canonical_ref_for_runtime("__name");
                  let (finalized_callee, _) =
                    self.finalized_expr_for_symbol_ref(name_ref, false, false);
                  init_expr = self.snippet.keep_name_call_expr(
                    "default",
                    init_expr,
                    finalized_callee,
                    true, // pure annotation for tree-shaking
                  );
                }
              }

              top_stmt =
                self.snippet.var_decl_stmt(canonical_name_for_default_export_ref, init_expr);
            }
            ast::ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
              // "export default function() {}" => "function default() {}"
              // "export default function foo() {}" => "function foo() {}"
              if func.id.is_none() {
                let canonical_name_for_default_export_ref =
                  self.canonical_name_for(self.ctx.module.default_export_ref);
                func.id = Some(self.snippet.id(canonical_name_for_default_export_ref, SPAN));

                // When keep_names is enabled, preserve "default" as the function name
                if self.ctx.options.keep_names {
                  // current statement will be pushed to program.body, so the insert position is program.body.len() + 1
                  let insert_position = program.body.len() + 1;
                  self.keep_name_statement_to_insert.push((
                    insert_position,
                    CompactStr::new("default"),
                    CompactStr::new(canonical_name_for_default_export_ref),
                  ));
                }
              }
              let func = func.as_mut().take_in(self.alloc);
              top_stmt = ast::Statement::FunctionDeclaration(ArenaBox::new_in(func, self.alloc));
            }
            ast::ExportDefaultDeclarationKind::ClassDeclaration(class) => {
              // "export default class {}" => "class default {}"
              // "export default class Foo {}" => "class Foo {}"
              if class.id.is_none() {
                let canonical_name_for_default_export_ref =
                  self.canonical_name_for(self.ctx.module.default_export_ref);
                class.id = Some(self.snippet.id(canonical_name_for_default_export_ref, SPAN));

                // When keep_names is enabled, preserve "default" as the class name
                // Skip if class has static name property
                if self.ctx.options.keep_names {
                  let default_name = CompactStr::from("default");
                  if let Some(element) = self.keep_name_helper_for_class(
                    Some(KeepNameId::CompactStr(&default_name)),
                    &class.body,
                  ) {
                    class.body.body.insert(0, element);
                  }
                }
              }

              // Class should be handled specially, because the `ClassDecl` will be transformed again.
              let mut class = class.as_mut().take_in(self.alloc);
              class.span = default_decl_span;
              top_stmt = ast::Statement::ClassDeclaration(ArenaBox::new_in(class, self.alloc));
            }
            _ => {}
          }

          // Transfer span of ExportDefaultDeclaration to FunctionDeclaration to preserve the
          // comments
          *top_stmt.span_mut() = default_decl_span;
        } else if let Some(named_decl) = top_stmt.as_export_named_declaration_mut() {
          if named_decl.source.is_none() {
            let named_decl_span = named_decl.span;
            if let Some(decl) = &mut named_decl.declaration {
              // `export var foo = 1` => `var foo = 1`
              // `export function foo() {}` => `function foo() {}`
              // `export class Foo {}` => `class Foo {}`

              *decl.span_mut() = named_decl_span;
              top_stmt = ast::Statement::from(decl.take_in(self.alloc));
            } else {
              // `export { foo }`
              // Remove this statement by ignoring it
              return;
            }
          } else {
            // `export { foo } from 'path'`
            let rec_idx = self.ctx.module.imports[&named_decl.span];
            if self.transform_or_remove_import_export_stmt(&mut top_stmt, rec_idx) {
              return;
            }
          }
        }

        if self.ctx.options.top_level_var {
          if let Statement::VariableDeclaration(var_decl) = &mut top_stmt {
            var_decl.kind = ast::VariableDeclarationKind::Var;
            for decl in &mut var_decl.declarations {
              decl.kind = VariableDeclarationKind::Var;
            }
          }
          if let Statement::ClassDeclaration(class_decl) = &mut top_stmt {
            if let Some(mut decl) = self.get_transformed_class_decl(class_decl) {
              top_stmt = Statement::from(decl.take_in(self.alloc));
            }
          }
        }
        program.body.push(top_stmt);
        if is_module_decl {
          last_import_stmt_idx = Some(program.body.len());
        }
      },
    );
    last_import_stmt_idx.unwrap_or(0)
  }

  fn process_fn(
    &self,
    symbol_binding_id: Option<KeepNameId>,
    name_binding_id: Option<KeepNameId>,
  ) -> Option<(usize, CompactStr, CompactStr)> {
    if !self.ctx.options.keep_names {
      return None;
    }
    let (original_name, _) = self.get_keep_name_info(name_binding_id?)?;
    let (_, canonical_name) = self.get_keep_name_info(symbol_binding_id?)?;
    let original_name: CompactStr = CompactStr::new(original_name);
    let new_name = CompactStr::new(canonical_name);
    let insert_position = self.cur_stmt_index + 1;
    Some((insert_position, original_name, new_name))
  }

  fn process_keep_name_for_expression(
    &self,
    keep_name_id: Option<KeepNameId>,
    expr: &mut ast::Expression<'ast>,
  ) {
    // Don't rewrite `__name` runtime helper itself.
    if !self.ctx.options.keep_names || self.ctx.runtime.id() == self.ctx.idx {
      return;
    }

    match expr {
      ast::Expression::ClassExpression(class_expression) => {
        // Named class expressions are handled in visit_expression
        if class_expression.id.is_some() {
          return;
        }
        if let Some(element) = self.keep_name_helper_for_class(keep_name_id, &class_expression.body)
        {
          class_expression.body.body.insert(0, element);
        }
      }
      ast::Expression::FunctionExpression(fn_expression) => {
        // Named function expressions are handled in visit_expression
        if fn_expression.id.is_some() {
          return;
        }
        if let Some((_insert_position, original_name, _)) =
          self.process_fn(keep_name_id, keep_name_id)
        {
          let fn_expr = expr.take_in(self.alloc);
          let name_ref = self.canonical_ref_for_runtime("__name");
          let (finalized_callee, _) = self.finalized_expr_for_symbol_ref(name_ref, false, false);
          *expr = self.snippet.keep_name_call_expr(&original_name, fn_expr, finalized_callee, true);
        }
      }
      ast::Expression::ArrowFunctionExpression(_fn_expr) => {
        if let Some((_insert_position, original_name, _)) =
          self.process_fn(keep_name_id, keep_name_id)
        {
          let fn_expr = expr.take_in(self.alloc);
          let name_ref = self.canonical_ref_for_runtime("__name");
          let (finalized_callee, _) = self.finalized_expr_for_symbol_ref(name_ref, false, false);
          *expr = self.snippet.keep_name_call_expr(&original_name, fn_expr, finalized_callee, true);
        }
      }
      _ => {}
    }
  }

  fn keep_name_helper_for_class(
    &self,
    id: Option<KeepNameId>,
    class_body: &ast::ClassBody<'ast>,
  ) -> Option<ClassElement<'ast>> {
    if !self.ctx.options.keep_names {
      return None;
    }
    let keep_name_id = id?;
    // Skip if the class already has a static `name` property/method
    if Self::class_body_has_static_name(class_body) {
      return None;
    }
    let original_name = match keep_name_id {
      KeepNameId::CompactStr(name) => {
        // CompactStr variant doesn't need conflict resolution - it's already a direct name
        name.clone()
      }
      KeepNameId::SymbolId(_) | KeepNameId::ReferenceId(_) => {
        let (original_name, _) = self.get_keep_name_info(keep_name_id)?;
        let original_name: CompactStr = CompactStr::new(original_name);
        original_name
      }
    };

    let name_ref = self.canonical_ref_for_runtime("__name");
    let (finalized_callee, _) = self.finalized_expr_for_symbol_ref(name_ref, false, false);
    Some(self.snippet.static_block_keep_name_helper(&original_name, finalized_callee))
  }

  /// Check if a class body has a static `name` property, method, or accessor.
  fn class_body_has_static_name(body: &ast::ClassBody<'ast>) -> bool {
    body.body.iter().any(|element| match element {
      ClassElement::MethodDefinition(method) => {
        method.r#static && method.key.static_name().is_some_and(|name| name == "name")
      }
      ClassElement::PropertyDefinition(prop) => {
        prop.r#static && prop.key.static_name().is_some_and(|name| name == "name")
      }
      ClassElement::AccessorProperty(accessor) => {
        accessor.r#static && accessor.key.static_name().is_some_and(|name| name == "name")
      }
      _ => false,
    })
  }

  /// Inserts `__name()` call statements for keeping function/class names.
  /// This method processes the pending keep_name insertions in reverse order.
  fn insert_keep_name_statements(
    &self,
    statements: &mut allocator::Vec<'ast, ast::Statement<'ast>>,
  ) {
    for (stmt_index, original_name, new_name) in self.keep_name_statement_to_insert.iter().rev() {
      let name_ref = self.canonical_ref_for_runtime("__name");
      let (finalized_callee, _) = self.finalized_expr_for_symbol_ref(name_ref, false, false);
      let target =
        self.snippet.builder.expression_identifier(SPAN, self.snippet.builder.str(new_name));
      statements.insert(
        *stmt_index,
        self.snippet.builder.statement_expression(
          SPAN,
          self.snippet.keep_name_call_expr(original_name, target, finalized_callee, false),
        ),
      );
    }
  }

  /// Rewrites a dynamic import expression when the importee is a merged user defined chunk or a common chunk.
  ///
  /// This handles two cases:
  /// 1. If the importer and importee are in the same chunk:
  ///    Convert `import('./some-module.js')` to `Promise.resolve().then(() => importee_namespace)`
  /// 2. If the importee is in a different chunk:
  ///    Convert `import('./some-module.js')` to `import('./some-module.js').then(n => n.ns)`
  ///
  /// Returns `Some(Expression)` if the import was rewritten, `None` otherwise.
  fn rewrite_dynamic_import_for_merged_entry(
    &self,
    expr: &mut ast::ImportExpression<'ast>,
    importee: &NormalModule,
    importee_chunk: &Chunk,
    importee_chunk_idx: ChunkIdx,
  ) -> Option<Expression<'ast>> {
    let importee_idx = importee.idx;
    // to make sure the semantic is correct after chunk merging optimization.
    let needs_namespace_extraction = self
      .ctx
      .chunk_graph
      .common_chunk_exported_facade_chunk_namespace
      .get(&importee_chunk_idx)
      .is_some_and(|set| set.contains(&importee_idx));

    if !needs_namespace_extraction {
      return None;
    }

    let is_importer_importee_in_same_chunk = importee_chunk.modules.contains(&self.ctx.idx);
    if is_importer_importee_in_same_chunk {
      let importee_meta = &self.ctx.linking_infos[importee.idx];

      let finalized_expr = match importee_meta.wrap_kind() {
        WrapKind::Cjs => {
          let importee_wrapper_ref = self.ctx.linking_infos[importee.idx].wrapper_ref.unwrap();

          let (finalized_importee_wrapper_ref, _) =
            self.finalized_expr_for_symbol_ref(importee_wrapper_ref, false, false);

          let finalized_to_esm = self.finalized_expr_for_runtime_symbol("__toESM");

          // require_xxx()
          let wrapper_ref_call_expr = self.snippet.builder.expression_call(
            SPAN,
            finalized_importee_wrapper_ref,
            NONE,
            self.snippet.builder.vec(),
            false,
          );

          // __toESM(require_xxx(), isNodeMode)
          self.snippet.wrap_with_to_esm(
            finalized_to_esm,
            wrapper_ref_call_expr,
            self.ctx.module.should_consider_node_esm_spec_for_dynamic_import(),
          )
        }
        WrapKind::Esm => {
          // (init_xxx(), namespace_exports)
          let importee_wrapper_ref = self.ctx.linking_infos[importee.idx].wrapper_ref.unwrap();

          let (finalized_importee_wrapper_ref, _) =
            self.finalized_expr_for_symbol_ref(importee_wrapper_ref, false, false);

          let (finalized_namespace, _) =
            self.finalized_expr_for_symbol_ref(importee.namespace_object_ref, false, false);

          // init_xxx()
          let wrapper_call_expr = ast::Expression::CallExpression(
            self.snippet.alloc_simple_call_expr(finalized_importee_wrapper_ref),
          );

          // (init_xxx(), namespace_exports)
          self.snippet.seq2_in_paren_expr(wrapper_call_expr, finalized_namespace)
        }
        WrapKind::None => {
          let (finalized_expr, _) =
            self.finalized_expr_for_symbol_ref(importee.namespace_object_ref, false, false);
          finalized_expr
        }
      };

      Some(self.snippet.promise_resolve_then_call_expr(finalized_expr))
    } else {
      // If the dynamic entry point is merged into another common chunk, we should
      // convert `import('./some-module.js')` to `import('./some-module.js').then(n => n.ns)`
      //                                                                                 ^^ points to the dynamic entry module namespace
      // For CJS format, convert to `Promise.resolve().then(() => require('./some-module.js')).then(n => n.ns)`
      // For CJS modules with wrap_kind Cjs, convert to `import('./chunk.js').then(n => __toESM(n.require_xxx()))`
      // For ESM modules with wrap_kind Esm, convert to `import('./chunk.js').then(n => (n.init_xxx(), n.namespace))`
      let importee_meta = &self.ctx.linking_infos[importee_idx];
      let wrap_kind = importee_meta.wrap_kind();

      // For wrapped modules (CJS/ESM), look up the wrapper_ref; for others, look up the namespace symbol
      let primary_export_symbol = match wrap_kind {
        WrapKind::Cjs | WrapKind::Esm => importee_meta.wrapper_ref,
        WrapKind::None => self.ctx.modules[importee_idx].namespace_object_ref(),
      };

      let primary_export_name = primary_export_symbol.and_then(|sym| {
        importee_chunk.exports_to_other_chunks.get(&sym).and_then(|names| names.first())
      });

      // For ESM wrapped modules, we also need the namespace symbol
      let namespace_export_name = if matches!(wrap_kind, WrapKind::Esm) {
        self.ctx.modules[importee_idx].namespace_object_ref().and_then(|ns_ref| {
          importee_chunk.exports_to_other_chunks.get(&ns_ref).and_then(|names| names.first())
        })
      } else {
        None
      };

      match primary_export_name {
        Some(name) => {
          let base_expr = if matches!(self.ctx.options.format, OutputFormat::Cjs) {
            let import_path = self.ctx.chunk.import_path_for(importee_chunk);
            // require('./some-module.js')
            let require_call_expr =
              ast::Expression::CallExpression(self.snippet.builder.alloc_call_expression(
                SPAN,
                self.snippet.builder.expression_identifier(SPAN, "require"),
                NONE,
                self.snippet.builder.vec1(ast::Argument::StringLiteral(
                  self.snippet.alloc_string_literal(&import_path, expr.span),
                )),
                false,
              ));
            // Promise.resolve().then(() => require('./some-module.js'))
            self.snippet.promise_resolve_then_call_expr(require_call_expr)
          } else {
            let import_expr = expr.take_in_box(self.builder().allocator);
            Expression::ImportExpression(import_expr)
          };

          match wrap_kind {
            WrapKind::Cjs => {
              // For CJS modules: import('./chunk.js').then(n => __toESM(n.require_xxx()))
              let finalized_to_esm = self.finalized_expr_for_runtime_symbol("__toESM");
              let call_expr = self.snippet.then_call_cjs_wrapper_with_to_esm(
                base_expr,
                name,
                finalized_to_esm,
                self.ctx.module.should_consider_node_esm_spec_for_dynamic_import(),
              );
              Some(Expression::CallExpression(call_expr))
            }
            WrapKind::Esm => {
              // For ESM modules: import('./chunk.js').then(n => (n.init_xxx(), n.namespace))
              if let Some(ns_name) = namespace_export_name {
                let call_expr =
                  self.snippet.then_call_esm_wrapper_with_namespace(base_expr, name, ns_name);
                Some(Expression::CallExpression(call_expr))
              } else {
                tracing::warn!(
                  "ESM wrapped module {:?} in chunk {:?} has wrapper but no namespace export.",
                  importee_idx,
                  importee_chunk_idx
                );
                None
              }
            }
            WrapKind::None => {
              let call_expr = self.snippet.then_extract_property(base_expr, name);
              Some(Expression::CallExpression(call_expr))
            }
          }
        }
        None => {
          tracing::warn!(
            "Merged dynamic entry module {:?} in chunk {:?} has no export name in exports_to_other_chunks. \
            This indicates an inconsistent state in the chunk graph where the module is marked as merged \
            but its namespace export is not properly tracked.",
            importee_idx,
            importee_chunk_idx
          );
          None
        }
      }
    }
  }

  fn try_rewrite_import_expression(&self, node: &mut ast::Expression<'ast>) -> bool {
    let ast::Expression::ImportExpression(expr) = node else {
      return false;
    };
    if expr.options.is_some() {
      return false;
    }

    let (Some(str), Some(rec_idx)) =
      (expr.source.as_static_module_request(), self.ctx.module.imports.get(&expr.span))
    else {
      if matches!(self.ctx.options.format, OutputFormat::Cjs)
        && !self.ctx.options.dynamic_import_in_cjs
      {
        // Transform `import(expr)` to `Promise.resolve().then(() => __toESM(require(expr)))`
        let source = expr.source.take_in(self.alloc);
        let require_call = self.snippet.call_expr_with_arg_expr_expr("require", source);
        let to_esm_fn_name = self.finalized_expr_for_runtime_symbol("__toESM");
        let wrapped = self.snippet.wrap_with_to_esm(
          to_esm_fn_name,
          require_call,
          self.ctx.module.should_consider_node_esm_spec_for_dynamic_import(),
        );
        *node = self.snippet.promise_resolve_then_call_expr(wrapped);
        return true;
      }
      return false;
    };

    let mut needs_to_esm_helper = false;
    let rec = &self.ctx.module.import_records[*rec_idx];
    let Some(importee_idx) = rec.resolved_module else { return true };

    match &self.ctx.modules[importee_idx] {
      Module::Normal(importee) => {
        let Some(&importee_chunk_idx) =
          self.ctx.chunk_graph.entry_module_to_entry_chunk.get(&importee_idx)
        else {
          // TODO: probably we should add the reason why it is replaced with `void 0`(just like webpack) when upstream support codegen with specific operation
          *node = self.snippet.builder.void_0(SPAN);
          return true;
        };
        let Some(importee_chunk) = self.ctx.chunk_graph.chunk_table.get(importee_chunk_idx) else {
          return false;
        };

        let import_path = self.ctx.chunk.import_path_for(importee_chunk);
        expr.source = Expression::StringLiteral(
          self.snippet.alloc_string_literal(&import_path, expr.source.span()),
        );

        if let Some(rewritten_expr) = self.rewrite_dynamic_import_for_merged_entry(
          expr,
          importee,
          importee_chunk,
          importee_chunk_idx,
        ) {
          // the `toESM` is properly handled inside `rewrite_dynamic_import_for_merged_entry`
          *node = rewritten_expr;
          return true;
        }

        // Convert `import('./foo.mjs')` to `Promise.resolve().then(function() { return require('foo.mjs') })`
        // when format is CJS
        if matches!(self.ctx.options.format, OutputFormat::Cjs) {
          // require('foo.mjs')
          let mut require_call_expr =
            ast::Expression::CallExpression(self.snippet.builder.alloc_call_expression(
              SPAN,
              self.snippet.builder.expression_identifier(SPAN, "require"),
              NONE,
              self.snippet.builder.vec1(ast::Argument::StringLiteral(
                self.snippet.alloc_string_literal(&import_path, expr.span),
              )),
              false,
            ));

          if importee.exports_kind.is_commonjs() {
            // Inline __toDynamicImportESM: __toESM(require('foo.mjs').default, isNodeMode)
            let to_esm_fn_name = self.finalized_expr_for_runtime_symbol("__toESM");

            // require('foo.mjs').default
            let require_default_expr = ast::Expression::StaticMemberExpression(
              self.snippet.builder.alloc_static_member_expression(
                SPAN,
                require_call_expr,
                self.snippet.builder.identifier_name(SPAN, "default"),
                false,
              ),
            );

            // __toESM(require('foo.mjs').default, isNodeMode)
            require_call_expr = self.snippet.wrap_with_to_esm(
              to_esm_fn_name,
              require_default_expr,
              self.ctx.module.should_consider_node_esm_spec_for_dynamic_import(),
            );
          }

          *node = self.snippet.promise_resolve_then_call_expr(require_call_expr);
          return true;
        }

        needs_to_esm_helper = importee.exports_kind.is_commonjs();
      }
      Module::External(importee) => {
        let import_path = importee.get_import_path(self.ctx.chunk, self.ctx.resolved_paths);
        if str != import_path {
          expr.source = Expression::StringLiteral(
            self.snippet.alloc_string_literal(&import_path, expr.source.span()),
          );
        }
        // Convert `import("external")` to `Promise.resolve().then(() => __toESM(require("external")))`
        // when format is CJS and dynamicImportInCjs is false
        if matches!(self.ctx.options.format, OutputFormat::Cjs)
          && !self.ctx.options.dynamic_import_in_cjs
        {
          let source = expr.source.take_in(self.alloc);
          let require_call = self.snippet.call_expr_with_arg_expr_expr("require", source);
          let to_esm_fn_name = self.finalized_expr_for_runtime_symbol("__toESM");
          let wrapped = self.snippet.wrap_with_to_esm(
            to_esm_fn_name,
            require_call,
            self.ctx.module.should_consider_node_esm_spec_for_dynamic_import(),
          );
          *node = self.snippet.promise_resolve_then_call_expr(wrapped);
          return true;
        }
      }
    }

    if needs_to_esm_helper {
      // Turn `import('./some-cjs-module.js')` into `import('./some-cjs-module.js').then((m) => __toESM(m.default, isNodeMode))`
      // Inline __toDynamicImportESM

      // `import('./some-cjs-module.js')`
      let original_import_expr = node.take_in(self.alloc);

      // __toESM
      let to_esm_fn_name = self.finalized_expr_for_runtime_symbol("__toESM");

      // Build arrow function: (m) => __toESM(m.default, isNodeMode)
      // m.default
      let m_default_expr = ast::Expression::StaticMemberExpression(
        self.snippet.builder.alloc_static_member_expression(
          SPAN,
          self.snippet.builder.expression_identifier(SPAN, "m"),
          self.snippet.builder.identifier_name(SPAN, "default"),
          false,
        ),
      );

      // __toESM(m.default, isNodeMode)
      let to_esm_call = self.snippet.wrap_with_to_esm(
        to_esm_fn_name,
        m_default_expr,
        self.ctx.module.should_consider_node_esm_spec_for_dynamic_import(),
      );

      // (m) => __toESM(m.default, isNodeMode)
      let arrow_fn = self.snippet.builder.alloc_arrow_function_expression(
        SPAN,
        true,  // expression
        false, // async
        NONE,
        self.snippet.builder.formal_parameters(
          SPAN,
          ast::FormalParameterKind::ArrowFormalParameters,
          self.snippet.builder.vec1(
            self.snippet.builder.formal_parameter(
              SPAN,
              self.snippet.builder.vec(),
              self
                .snippet
                .builder
                .binding_pattern_binding_identifier(SPAN, self.snippet.builder.str("m")),
              NONE,
              NONE,
              false,
              None,
              false,
              false,
            ),
          ),
          NONE,
        ),
        NONE,
        self.snippet.builder.function_body(
          SPAN,
          self.snippet.builder.vec(),
          self.snippet.builder.vec1(self.snippet.builder.statement_expression(SPAN, to_esm_call)),
        ),
      );

      // `import('./some-cjs-module.js').then
      let callee = self.snippet.builder.alloc_static_member_expression(
        SPAN,
        original_import_expr,
        self.snippet.builder.identifier_name(SPAN, "then"),
        false,
      );

      // `import('./some-cjs-module.js').then((m) => __toESM(m.default, isNodeMode))`
      let call_expr = self.snippet.builder.alloc_call_expression(
        SPAN,
        ast::Expression::StaticMemberExpression(callee),
        NONE,
        self.snippet.builder.vec1(ast::Argument::ArrowFunctionExpression(arrow_fn)),
        false,
      );

      *node = ast::Expression::CallExpression(call_expr);
    }

    true
  }

  /// if the json module prop needs to inline, we would just rewrite the inlined prop to
  /// `EmptyStatement`
  fn try_inline_json_module_prop(&mut self, it: &mut Statement<'ast>) -> Option<()> {
    let json_module_inlined_prop = self.json_module_inlined_prop.as_mut()?;
    let decl = it.as_declaration_mut()?;
    let ast::Declaration::VariableDeclaration(var_decl) = decl else {
      return None;
    };
    let first_decl = var_decl.declarations.first_mut()?;
    let init = first_decl.init.as_mut()?;
    // For synthesis json module, only last symbol of var stmt is `None`, since it is a generated
    // manually.
    let id = first_decl.id.get_binding_identifier()?.symbol_id.get();
    match id {
      Some(id) => {
        let symbol_ref: SymbolRef = (self.ctx.idx, id).into();
        if !self
          .ctx
          .module
          .json_module_none_self_reference_included_symbol
          .as_ref()?
          .contains(&symbol_ref)
        {
          json_module_inlined_prop.insert(id, init.take_in(self.alloc));
          *it = self.snippet.builder.statement_empty(SPAN);
        }
      }
      None => {
        // It is `json export default stmt`. e.g.
        // ```js
        // ...snip
        // export default { foo, bar };
        // ```
        //
        let Expression::ObjectExpression(obj_expr) = init else {
          return None;
        };

        for ele in &mut obj_expr.properties {
          let ObjectPropertyKind::ObjectProperty(prop) = ele else {
            continue;
          };
          let Some(identifier) = prop.value.as_identifier() else {
            continue;
          };
          let reference_id = identifier.reference_id();
          let Some(symbol_id) = self.scope.symbol_id_for(reference_id) else {
            continue;
          };
          let Some(replaced_expr) = json_module_inlined_prop.remove(&symbol_id) else {
            continue;
          };
          prop.value = replaced_expr;
        }
      }
    }

    Some(())
  }
}