File size: 67,270 Bytes
1e92f2d |
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 |
use std::{fmt, hash::Hash};
use petgraph::{
Direction, Graph,
algo::{condensation, has_path_connecting},
graph::NodeIndex,
graphmap::GraphMap,
prelude::DiGraphMap,
visit::EdgeRef,
};
use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{
common::{BytePos, DUMMY_SP, Spanned, SyntaxContext, comments::Comments, util::take::Take},
ecma::{
ast::{
ClassDecl, Decl, DefaultDecl, EsReserved, ExportAll, ExportDecl, ExportNamedSpecifier,
ExportSpecifier, Expr, ExprStmt, FnDecl, Id, Ident, IdentName, ImportDecl,
ImportNamedSpecifier, ImportSpecifier, ImportStarAsSpecifier, KeyValueProp, Lit,
Module, ModuleDecl, ModuleExportName, ModuleItem, NamedExport, ObjectLit, Prop,
PropName, PropOrSpread, Stmt, Str, VarDecl, VarDeclKind, VarDeclarator, op,
},
atoms::Atom,
utils::{ExprCtx, ExprExt, find_pat_ids, quote_ident},
},
};
use turbo_rcstr::RcStr;
use turbo_tasks::FxIndexSet;
use super::{
Key, TURBOPACK_PART_IMPORT_SOURCE,
util::{
Vars, collect_top_level_decls, ids_captured_by, ids_used_by, ids_used_by_ignoring_nested,
},
};
use crate::{magic_identifier, tree_shake::optimizations::GraphOptimizer};
/// The id of an item
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum ItemId {
Item { index: usize, kind: ItemIdItemKind },
Group(ItemIdGroupKind),
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum ItemIdGroupKind {
/// Used only for testing
#[cfg(test)]
ModuleEvaluation,
/// `(local, export_name)``
Export(Id, Atom),
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum ItemIdItemKind {
Normal,
ImportOfModule,
/// Imports are split as multiple items.
///
/// Note that this item is not actually present in the module, and rather a phantom node.
/// We only need this node to create an unique identifier for each binding in an import
/// declaration.
ImportBinding(u32),
/// Reexport of a binding
ReexportBinding(u32),
VarDeclarator(u32),
}
impl ItemId {
/// Returns true if this item is a phantom node.
///
/// A phantom node is a node that is not actually present in the module, and rather a
/// placeholder to create an unique identifier.
pub fn is_phantom(&self) -> bool {
matches!(
self,
ItemId::Item {
kind: ItemIdItemKind::ImportBinding(..),
..
}
)
}
}
impl fmt::Debug for ItemId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ItemId::Group(kind) => {
write!(f, "ItemId({kind:?})")
}
ItemId::Item { index, kind } => {
write!(f, "ItemId({index}, {kind:?})")
}
}
}
}
/// Data about a module item
pub(crate) struct ItemData {
/// Is the module item hoisted?
pub is_hoisted: bool,
/// TODO(PACK-3166): We can use this field to optimize tree shaking
#[allow(unused)]
pub pure: bool,
/// Variables declared or bound by this module item
pub var_decls: FxIndexSet<Id>,
/// Variables read by this module item during evaluation
pub read_vars: FxIndexSet<Id>,
/// Variables read by this module item eventually
///
/// - e.g. variables read in the body of function declarations are considered as eventually
/// read
/// - This is only used when reads are not trigger directly by this module item, but require a
/// side effect to be triggered. We don’t know when this is executed.
/// - Note: This doesn’t mean they are only read “after” initial evaluation. They might also be
/// read “during” initial evaluation on any module item with SIDE_EFFECTS. This kind of
/// interaction is handled by the module item with SIDE_EFFECTS.
pub eventual_read_vars: FxIndexSet<Id>,
/// Side effects that are triggered on local variables during evaluation
pub write_vars: FxIndexSet<Id>,
/// Side effects that are triggered on local variables eventually
pub eventual_write_vars: FxIndexSet<Id>,
/// Any other unknown side effects that are trigger during evaluation
pub side_effects: bool,
pub content: ModuleItem,
pub export: Option<Atom>,
/// This value denotes the module specifier of the [ImportDecl] that declares this
/// [ItemId].
///
/// Used to optimize `ImportBinding`.
pub binding_source: Option<(Str, ImportSpecifier)>,
/// Explicit dependencies of this item.
///
/// Used to depend from import binding to side-effect-import without additional analysis.
///
/// - Note: ImportBinding should depend on actual import statements because those imports may
/// have side effects.
///
/// See https://github.com/vercel/next.js/pull/71234#issuecomment-2409810084 for the problematic
/// test case.
pub explicit_deps: Vec<ItemId>,
pub is_module_evaluation: bool,
}
impl fmt::Debug for ItemData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ItemData")
.field("is_hoisted", &self.is_hoisted)
.field("pure", &self.pure)
.field("var_decls", &self.var_decls)
.field("read_vars", &self.read_vars)
.field("eventual_read_vars", &self.eventual_read_vars)
.field("write_vars", &self.write_vars)
.field("eventual_write_vars", &self.eventual_write_vars)
.field("side_effects", &self.side_effects)
.field("export", &self.export)
.field("explicit_deps", &self.explicit_deps)
.field("is_module_evaluation", &self.is_module_evaluation)
.finish()
}
}
impl Default for ItemData {
fn default() -> Self {
Self {
is_hoisted: Default::default(),
var_decls: Default::default(),
read_vars: Default::default(),
eventual_read_vars: Default::default(),
write_vars: Default::default(),
eventual_write_vars: Default::default(),
side_effects: Default::default(),
content: ModuleItem::dummy(),
pure: Default::default(),
export: Default::default(),
binding_source: Default::default(),
explicit_deps: Default::default(),
is_module_evaluation: Default::default(),
}
}
}
#[derive(Debug, Clone)]
pub struct InternedGraph<T>
where
T: Eq + Hash + Clone,
{
pub(super) idx_graph: DiGraphMap<u32, Dependency>,
pub(super) graph_ix: FxIndexSet<T>,
}
#[derive(Debug, Clone, Copy)]
pub enum Dependency {
Strong,
Weak,
}
impl<T> Default for InternedGraph<T>
where
T: Eq + Hash + Clone,
{
fn default() -> Self {
Self {
idx_graph: Default::default(),
graph_ix: Default::default(),
}
}
}
impl<T> InternedGraph<T>
where
T: Eq + Hash + Clone,
{
pub(super) fn node(&mut self, id: &T) -> u32 {
self.graph_ix.get_index_of(id).unwrap_or_else(|| {
let ix = self.graph_ix.len();
self.graph_ix.insert_full(id.clone());
ix
}) as _
}
/// Panics if `id` is not found.
pub(super) fn get_node(&self, id: &T) -> u32 {
self.graph_ix.get_index_of(id).unwrap() as _
}
}
#[derive(Debug, Clone, Default)]
pub struct DepGraph {
pub(super) g: InternedGraph<ItemId>,
}
#[derive(Debug, Clone, Copy)]
pub(super) enum Mode {
#[allow(dead_code)]
Development,
Production,
}
pub(super) struct SplitModuleResult {
pub entrypoints: FxHashMap<Key, u32>,
/// Dependency between parts.
pub part_deps: FxHashMap<u32, Vec<PartId>>,
pub modules: Vec<Module>,
pub star_reexports: Vec<ExportAll>,
}
impl DepGraph {
/// Weak imports are imports only if it is referenced strongly. But this
/// is production-only, and weak dependencies are treated as strong
/// dependencies in development mode.
pub(super) fn handle_weak(&mut self, mode: Mode) {
if !matches!(mode, Mode::Production) {
return;
}
for start in self.g.graph_ix.iter() {
let start = self.g.get_node(start);
for end in self.g.graph_ix.iter() {
let end = self.g.get_node(end);
if let Some(Dependency::Weak) = self.g.idx_graph.edge_weight(start, end) {
self.g.idx_graph.remove_edge(start, end);
}
}
}
}
/// Split modules into parts. Additionally, this function adds imports to
/// _connect_ variables.
///
/// _connect_ here means if a variable is declared in a different part than
/// a usage side, `import` and `export` will be added.
///
/// Note: ESM imports are immutable, but we do not handle it.
pub(super) fn split_module(
&mut self,
directives: &[ModuleItem],
data: &FxHashMap<ItemId, ItemData>,
) -> SplitModuleResult {
let groups = self.finalize(data);
let mut outputs = FxHashMap::default();
let mut part_deps = FxHashMap::<_, Vec<PartId>>::default();
let star_reexports: Vec<_> = data
.values()
.filter_map(|v| v.content.as_module_decl()?.as_export_all())
.cloned()
.collect();
let mut modules = vec![];
let mut exports_module = Module::dummy();
exports_module.body.extend(directives.iter().cloned());
if groups.graph_ix.is_empty() {
// If there's no dependency, all nodes are in the module evaluaiotn group.
modules.push(Module {
span: DUMMY_SP,
body: data.values().map(|v| v.content.clone()).collect(),
shebang: None,
});
outputs.insert(Key::ModuleEvaluation, 0);
}
// See https://github.com/vercel/next.js/pull/71234#issuecomment-2409810084
// ImportBinding should depend on actual import statements because those imports may have
// side effects.
let mut importer = FxHashMap::default();
let mut declarator = FxHashMap::default();
for (ix, group) in groups.graph_ix.iter().enumerate() {
for id in group {
let item = data.get(id).unwrap();
for var in item.var_decls.iter() {
declarator.entry(var.clone()).or_insert_with(|| ix as u32);
}
if let ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
specifiers,
src,
..
})) = &item.content
&& specifiers.is_empty()
{
importer.insert(src.value.clone(), ix as u32);
}
}
}
let mut mangle_count = 0;
let mut mangled_vars = FxHashMap::default();
let mut mangle = |var: &Id| {
mangled_vars
.entry(var.clone())
.or_insert_with(|| encode_base54(&mut mangle_count, true))
.clone()
};
let mut module_evaluation_ix = None;
for (ix, group) in groups.graph_ix.iter().enumerate() {
let mut chunk = Module {
span: DUMMY_SP,
body: directives.to_vec(),
shebang: None,
};
let mut part_deps_done = FxHashSet::default();
let mut required_vars = group
.iter()
.flat_map(|id| {
let data = data.get(id).unwrap();
data.read_vars
.iter()
.chain(data.write_vars.iter())
.chain(data.eventual_read_vars.iter())
.chain(data.eventual_write_vars.iter())
})
.collect::<FxIndexSet<_>>();
for id in group {
if id.is_phantom() {
continue;
}
let data = data.get(id).unwrap();
for var in data.var_decls.iter() {
required_vars.swap_remove(var);
}
// Depend on import statements from 'ImportBinding'
if let ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
specifiers,
src,
..
})) = &data.content
&& !specifiers.is_empty()
&& let Some(dep) = importer.get(&src.value)
&& *dep != ix as u32
&& part_deps_done.insert(*dep)
{
part_deps
.entry(ix as u32)
.or_default()
.push(PartId::Internal(*dep, true));
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP,
specifiers: vec![],
src: Box::new(TURBOPACK_PART_IMPORT_SOURCE.into()),
type_only: false,
with: Some(Box::new(create_turbopack_part_id_assert(
PartId::Internal(*dep, true),
))),
phase: Default::default(),
})));
}
}
for item_id in group {
match item_id {
ItemId::Group(ItemIdGroupKind::Export(..)) => {
if let Some(export) = &data[item_id].export {
outputs.insert(Key::Export(export.as_str().into()), ix as u32);
let s = ExportSpecifier::Named(ExportNamedSpecifier {
span: DUMMY_SP,
orig: ModuleExportName::Ident(Ident::new(
export.clone(),
DUMMY_SP,
Default::default(),
)),
exported: None,
is_type_only: false,
});
exports_module.body.push(ModuleItem::ModuleDecl(
ModuleDecl::ExportNamed(NamedExport {
span: DUMMY_SP,
specifiers: vec![s],
src: Some(Box::new(TURBOPACK_PART_IMPORT_SOURCE.into())),
type_only: false,
with: Some(Box::new(create_turbopack_part_id_assert(
PartId::Export(export.as_str().into()),
))),
}),
));
}
}
_ => {
if data[item_id].is_module_evaluation {
debug_assert_eq!(module_evaluation_ix, None);
module_evaluation_ix = Some(ix as u32);
outputs.insert(Key::ModuleEvaluation, ix as u32);
}
}
}
}
for dep in groups
.idx_graph
.neighbors_directed(ix as u32, Direction::Outgoing)
{
if dep == ix as u32 {
continue;
}
let dep_item_ids = groups.graph_ix.get_index(dep as usize).unwrap();
for dep_item_id in dep_item_ids {
let ItemId::Group(ItemIdGroupKind::Export(var, export)) = dep_item_id else {
continue;
};
if !export.starts_with("$$RSC_SERVER_") {
continue;
}
required_vars.swap_remove(var);
let dep_part_id = PartId::Export(export.as_str().into());
let specifiers = vec![ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local: var.clone().into(),
imported: None,
is_type_only: false,
})];
part_deps
.entry(ix as u32)
.or_default()
.push(dep_part_id.clone());
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP,
specifiers,
src: Box::new(TURBOPACK_PART_IMPORT_SOURCE.into()),
type_only: false,
with: Some(Box::new(create_turbopack_part_id_assert(dep_part_id))),
phase: Default::default(),
})));
}
}
// Import variables
for &var in &required_vars {
let Some(&dep) = declarator.get(var) else {
continue;
};
if dep == ix as u32 {
continue;
}
part_deps_done.insert(dep);
let dep_item_ids = groups.graph_ix.get_index(dep as usize).unwrap();
// Optimization & workaround for `ImportBinding` fragments.
// Instead of importing the import binding fragment, we import the original module.
// In this way, we can preserve the import statement so that the other code analysis
// can work.
if dep_item_ids.len() == 1 {
let dep_item_id = &dep_item_ids[0];
let dep_item_data = data.get(dep_item_id).unwrap();
if let Some((module_specifier, import_specifier)) =
&dep_item_data.binding_source
{
// Preserve the order of the side effects by importing the
// side-effect-import fragment first.
if let Some(import_dep) = importer.get(&module_specifier.value)
&& *import_dep != ix as u32
{
part_deps
.entry(ix as u32)
.or_default()
.push(PartId::Internal(*import_dep, true));
chunk.body.push(ModuleItem::ModuleDecl(ModuleDecl::Import(
ImportDecl {
span: DUMMY_SP,
specifiers: vec![],
src: Box::new(TURBOPACK_PART_IMPORT_SOURCE.into()),
type_only: false,
with: Some(Box::new(create_turbopack_part_id_assert(
PartId::Internal(*import_dep, true),
))),
phase: Default::default(),
},
)));
}
let specifiers = vec![import_specifier.clone()];
part_deps_done.insert(dep);
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP,
specifiers,
src: Box::new(module_specifier.clone()),
type_only: false,
with: None,
phase: Default::default(),
})));
continue;
}
}
let specifiers = vec![ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local: var.clone().into(),
imported: Some(ModuleExportName::Ident(Ident::new_no_ctxt(
mangle(var),
DUMMY_SP,
))),
is_type_only: false,
})];
part_deps
.entry(ix as u32)
.or_default()
.push(PartId::Internal(dep, false));
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP,
specifiers,
src: Box::new(TURBOPACK_PART_IMPORT_SOURCE.into()),
type_only: false,
with: Some(Box::new(create_turbopack_part_id_assert(PartId::Internal(
dep, false,
)))),
phase: Default::default(),
})));
}
// Depend on direct dependencies so that they are executed before this module.
for dep in groups
.idx_graph
.neighbors_directed(ix as u32, petgraph::Direction::Outgoing)
{
if dep == ix as u32 {
continue;
}
if !part_deps_done.insert(dep) {
continue;
}
part_deps
.entry(ix as u32)
.or_default()
.push(PartId::Internal(dep, true));
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP,
specifiers: vec![],
src: Box::new(TURBOPACK_PART_IMPORT_SOURCE.into()),
type_only: false,
with: Some(Box::new(create_turbopack_part_id_assert(PartId::Internal(
dep, true,
)))),
phase: Default::default(),
})));
}
for g in group {
if g.is_phantom() {
continue;
}
// Skip directives, as we copy them to each modules.
if let ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: box Expr::Lit(Lit::Str(s)),
..
})) = &data[g].content
&& s.value.starts_with("use ")
{
continue;
}
// Do not store export * in internal part fragments.
if let ModuleItem::ModuleDecl(ModuleDecl::ExportAll(export)) = &data[g].content {
// Preserve side effects of import caused by export *
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: export.span,
specifiers: Default::default(),
src: export.src.clone(),
type_only: false,
with: export.with.clone(),
phase: Default::default(),
})));
continue;
}
chunk.body.push(data[g].content.clone());
}
for g in group {
if g.is_phantom() {
continue;
}
let data = data.get(g).unwrap();
// Emit `export { foo }`
for var in data.var_decls.iter() {
let assertion_prop =
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: quote_ident!("__turbopack_var__").into(),
value: Box::new(true.into()),
})));
chunk
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
NamedExport {
span: DUMMY_SP,
specifiers: vec![ExportSpecifier::Named(ExportNamedSpecifier {
span: DUMMY_SP,
orig: ModuleExportName::Ident(var.clone().into()),
exported: Some(ModuleExportName::Ident(Ident::new_no_ctxt(
mangle(var),
DUMMY_SP,
))),
is_type_only: false,
})],
src: if cfg!(test) {
Some(Box::new("__TURBOPACK_VAR__".into()))
} else {
None
},
type_only: false,
with: Some(Box::new(ObjectLit {
span: DUMMY_SP,
props: vec![assertion_prop],
})),
},
)));
}
}
if chunk.body.is_empty() {
continue;
}
modules.push(chunk);
}
outputs.insert(Key::Exports, modules.len() as u32);
for star in &star_reexports {
exports_module
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportAll(star.clone())));
}
modules.push(exports_module);
// Currently we need to have `Key::ModuleEvaluation` in the outputs
// even if it is empty.
if module_evaluation_ix.is_none() {
outputs.insert(Key::ModuleEvaluation, modules.len() as u32);
module_evaluation_ix = Some(modules.len() as u32);
modules.push(Module {
span: DUMMY_SP,
body: vec![],
shebang: None,
});
}
// Push `export {}` to the module evaluation to make it module.
modules[module_evaluation_ix.unwrap() as usize]
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
NamedExport {
span: DUMMY_SP,
specifiers: Default::default(),
src: None,
type_only: false,
with: None,
},
)));
if !star_reexports.is_empty() {
let mut module = Module::dummy();
outputs.insert(Key::StarExports, modules.len() as u32);
for star in &star_reexports {
module
.body
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportAll(star.clone())));
}
modules.push(module);
}
SplitModuleResult {
entrypoints: outputs,
part_deps,
modules,
star_reexports,
}
}
/// Merges a dependency group between [ModuleItem]s into a dependency graph
/// of [Module]s.
///
/// Note that [ModuleItem] and [Module] are represented as [ItemId] for
/// performance.
pub(super) fn finalize(
&mut self,
data: &FxHashMap<ItemId, ItemData>,
) -> InternedGraph<Vec<ItemId>> {
let mut graph = self.g.idx_graph.clone().into_graph::<u32>();
self.workaround_server_action(&mut graph, data);
let mut condensed = condensation(graph, true);
let optimizer = GraphOptimizer {
graph_ix: &self.g.graph_ix,
};
while optimizer.merge_single_incoming_nodes(&mut condensed)
|| optimizer.merge_nodes_with_same_starting_point(&mut condensed)
{}
let mut new_graph = InternedGraph::default();
// Sort the items to match the order of the original code.
for node in condensed.node_weights() {
let mut item_ids = node
.iter()
.map(|&ix| self.g.graph_ix[ix as usize].clone())
.collect::<Vec<_>>();
item_ids.sort();
debug_assert!(!item_ids.is_empty());
new_graph.node(&item_ids);
}
new_graph.graph_ix.sort_by(|a, b| a[0].cmp(&b[0]));
debug_assert_eq!(new_graph.idx_graph.node_count(), 0);
debug_assert_eq!(new_graph.idx_graph.edge_count(), 0);
let mut done = FxHashSet::default();
let mapped = condensed.map(
|_, node| {
let mut item_ids = node
.iter()
.map(|&ix| {
done.insert(ix);
self.g.graph_ix[ix as usize].clone()
})
.collect::<Vec<_>>();
item_ids.sort();
new_graph.node(&item_ids)
},
|_, edge| *edge,
);
let map = GraphMap::from_graph(mapped);
// Insert nodes without any edges
for node in self.g.graph_ix.iter() {
let ix = self.g.get_node(node);
if !done.contains(&ix) {
if data[node].pure {
continue;
}
let item_ids = vec![node.clone()];
new_graph.node(&item_ids);
}
}
InternedGraph {
idx_graph: map,
graph_ix: new_graph.graph_ix,
}
}
/// Fills information per module items
pub(super) fn init(
&mut self,
module: &Module,
comments: &dyn Comments,
unresolved_ctxt: SyntaxContext,
top_level_ctxt: SyntaxContext,
) -> (Vec<ItemId>, FxHashMap<ItemId, ItemData>) {
let top_level_vars = collect_top_level_decls(module);
let mut exports = vec![];
let mut items = FxHashMap::default();
let mut ids = vec![];
for (index, item) in module.body.iter().enumerate() {
// Fill exports
if let ModuleItem::ModuleDecl(item) = item {
match item {
ModuleDecl::ExportDecl(item) => match &item.decl {
Decl::Fn(FnDecl { ident, .. }) | Decl::Class(ClassDecl { ident, .. }) => {
exports.push((ident.to_id(), ident.sym.clone()));
}
Decl::Var(v) => {
for decl in &v.decls {
let ids: Vec<Id> = find_pat_ids(&decl.name);
for id in ids {
exports.push((id.clone(), id.0));
}
}
}
_ => {}
},
ModuleDecl::ExportNamed(item) => {
let import_id = if let Some(src) = &item.src {
// One item for the import for re-export
let import_id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportOfModule,
};
ids.push(import_id.clone());
items.insert(
import_id.clone(),
ItemData {
is_hoisted: true,
side_effects: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(
ImportDecl {
specifiers: Default::default(),
src: src.clone(),
..ImportDecl::dummy()
},
)),
..Default::default()
},
);
Some(import_id)
} else {
None
};
for (si, s) in item.specifiers.iter().enumerate() {
let (orig, mut local, exported) = match s {
ExportSpecifier::Named(s) => (
Some(s.orig.clone()),
match &s.orig {
ModuleExportName::Ident(i) => i.clone(),
ModuleExportName::Str(..) => quote_ident!("_tmp").into(),
},
s.exported.clone().unwrap_or_else(|| s.orig.clone()),
),
ExportSpecifier::Default(s) => (
Some(ModuleExportName::Ident(Ident::new(
"default".into(),
DUMMY_SP,
Default::default(),
))),
quote_ident!("default").into(),
ModuleExportName::Ident(s.exported.clone()),
),
ExportSpecifier::Namespace(s) => (
None,
match &s.name {
ModuleExportName::Ident(i) => i.clone(),
ModuleExportName::Str(..) => quote_ident!("_tmp").into(),
},
s.name.clone(),
),
};
if item.src.is_some() {
local.sym =
magic_identifier::mangle(&format!("reexport {}", local.sym))
.into();
local = local.into_private();
}
exports.push((local.to_id(), exported.atom().clone()));
if let Some(src) = &item.src {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ReexportBinding(si as _),
};
ids.push(id.clone());
let import = match s {
ExportSpecifier::Namespace(..) => {
ImportSpecifier::Namespace(ImportStarAsSpecifier {
span: DUMMY_SP,
local: local.clone(),
})
}
_ => ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local: local.clone(),
imported: orig,
is_type_only: false,
}),
};
items.insert(
id,
ItemData {
is_hoisted: true,
var_decls: [local.to_id()].into_iter().collect(),
pure: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(
ImportDecl {
span: DUMMY_SP,
specifiers: vec![import],
src: src.clone(),
type_only: false,
with: None,
phase: Default::default(),
},
)),
explicit_deps: vec![import_id.clone().unwrap()],
..Default::default()
},
);
}
}
}
ModuleDecl::ExportDefaultDecl(export) => {
let id = match &export.decl {
DefaultDecl::Class(c) => c.ident.clone(),
DefaultDecl::Fn(f) => f.ident.clone(),
DefaultDecl::TsInterfaceDecl(_) => unreachable!(),
};
// Mirror what `EsmModuleItem::code_generation` does, these are live
// bindings if the class/function has an identifier.
let default_var = id.unwrap_or_else(|| {
Ident::new(
magic_identifier::mangle("default export").into(),
DUMMY_SP,
Default::default(),
)
});
{
let mut used_ids = if export.decl.is_fn_expr() {
ids_used_by_ignoring_nested(
&export.decl,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
)
} else {
ids_used_by(
&export.decl,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
)
};
used_ids.read.swap_remove(&default_var.to_id());
used_ids.write.insert(default_var.to_id());
let mut captured_ids = if export.decl.is_fn_expr() {
ids_captured_by(
&export.decl,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
)
} else {
Vars::default()
};
captured_ids.read.swap_remove(&default_var.to_id());
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
var_decls: [default_var.to_id()].into_iter().collect(),
content: ModuleItem::Stmt(Stmt::Decl(match &export.decl {
DefaultDecl::Class(c) => Decl::Class(ClassDecl {
ident: default_var.clone(),
declare: false,
class: c.class.clone(),
}),
DefaultDecl::Fn(f) => Decl::Fn(FnDecl {
ident: default_var.clone(),
declare: false,
function: f.function.clone(),
}),
DefaultDecl::TsInterfaceDecl(_) => unreachable!(),
})),
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
exports.push((default_var.to_id(), "default".into()));
}
ModuleDecl::ExportDefaultExpr(export) => {
// Mirror what `EsmModuleItem::code_generation` does, these are live
// bindings if the class/function has an identifier.
let default_var = Ident::new(
magic_identifier::mangle("default export").into(),
DUMMY_SP,
Default::default(),
);
{
// For
// let __TURBOPACK_default_export__ = expr;
let mut used_ids = ids_used_by_ignoring_nested(
&export.expr,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
let captured_ids = ids_captured_by(
&export.expr,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
used_ids.write.insert(default_var.to_id());
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
var_decls: [default_var.to_id()].into_iter().collect(),
side_effects: true,
content: ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Const,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: default_var.clone().into(),
init: Some(export.expr.clone()),
definite: false,
}],
..Default::default()
},
)))),
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
{
// For export default __TURBOPACK__default__export__
exports.push((default_var.to_id(), "default".into()));
}
}
ModuleDecl::ExportAll(item) => {
// One item for the import for re-export
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportOfModule,
};
ids.push(id.clone());
items.insert(
id,
ItemData {
is_hoisted: true,
side_effects: true,
content: ModuleItem::ModuleDecl(ModuleDecl::ExportAll(
item.clone(),
)),
..Default::default()
},
);
}
_ => {}
}
}
match item {
ModuleItem::ModuleDecl(ModuleDecl::Import(item)) => {
// We create multiple items for each import.
// One item for the import itself
let import_id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportOfModule,
};
ids.push(import_id.clone());
items.insert(
import_id.clone(),
ItemData {
is_hoisted: true,
side_effects: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
specifiers: Default::default(),
..item.clone()
})),
..Default::default()
},
);
// One per binding
for (si, s) in item.specifiers.iter().enumerate() {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::ImportBinding(si as _),
};
ids.push(id.clone());
let local = s.local().to_id();
items.insert(
id,
ItemData {
is_hoisted: true,
var_decls: [local].into_iter().collect(),
pure: true,
content: ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
specifiers: vec![s.clone()],
..item.clone()
})),
binding_source: if item.with.is_none() {
// Optimize by directly binding to the source
Some((*item.src.clone(), s.clone()))
} else {
None
},
explicit_deps: vec![import_id.clone()],
..Default::default()
},
);
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Fn(f),
..
}))
| ModuleItem::Stmt(Stmt::Decl(Decl::Fn(f))) => {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
let vars = ids_used_by(
&f.function,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
let var_decls = {
let mut v = FxIndexSet::with_capacity_and_hasher(1, Default::default());
v.insert(f.ident.to_id());
v
};
items.insert(
id,
ItemData {
is_hoisted: true,
eventual_read_vars: vars.read,
eventual_write_vars: vars.write,
write_vars: var_decls.clone(),
var_decls,
content: ModuleItem::Stmt(Stmt::Decl(Decl::Fn(f.clone()))),
..Default::default()
},
);
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Class(c),
..
}))
| ModuleItem::Stmt(Stmt::Decl(Decl::Class(c))) => {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
let mut vars =
ids_used_by(&c.class, unresolved_ctxt, top_level_ctxt, &top_level_vars);
let var_decls = {
let mut v = FxIndexSet::with_capacity_and_hasher(1, Default::default());
v.insert(c.ident.to_id());
v
};
vars.write.insert(c.ident.to_id());
items.insert(
id,
ItemData {
read_vars: vars.read,
write_vars: vars.write,
var_decls,
content: ModuleItem::Stmt(Stmt::Decl(Decl::Class(c.clone()))),
..Default::default()
},
);
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Var(v),
..
}))
| ModuleItem::Stmt(Stmt::Decl(Decl::Var(v))) => {
for (i, decl) in v.decls.iter().enumerate() {
let id = ItemId::Item {
index,
kind: ItemIdItemKind::VarDeclarator(i as _),
};
ids.push(id.clone());
let has_explicit_pure = match &decl.init {
Some(e) => {
e.span().lo == BytePos::PURE
|| comments.has_flag(e.span().lo, "PURE")
}
_ => false,
};
let decl_ids: Vec<Id> = find_pat_ids(&decl.name);
let mut vars = ids_used_by_ignoring_nested(
&decl.init,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
let mut eventual_vars = ids_captured_by(
&decl.init,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
vars.read.retain(|id| !decl_ids.contains(id));
eventual_vars.read.retain(|id| !decl_ids.contains(id));
let side_effects = !has_explicit_pure
&& (vars.found_unresolved
|| decl.init.as_deref().is_some_and(|e| {
e.may_have_side_effects(ExprCtx {
unresolved_ctxt,
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 4,
})
}));
let var_decl = Box::new(VarDecl {
decls: vec![decl.clone()],
..*v.clone()
});
vars.write.extend(decl_ids.iter().cloned());
let content = ModuleItem::Stmt(Stmt::Decl(Decl::Var(var_decl)));
items.insert(
id,
ItemData {
pure: has_explicit_pure,
var_decls: decl_ids.clone().into_iter().collect(),
read_vars: vars.read,
write_vars: if has_explicit_pure {
Default::default()
} else {
vars.write
},
eventual_read_vars: eventual_vars.read,
eventual_write_vars: eventual_vars.write,
content,
side_effects,
..Default::default()
},
);
}
}
ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: box Expr::Assign(assign),
..
})) => {
let mut used_ids = ids_used_by_ignoring_nested(
item,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
let captured_ids =
ids_captured_by(item, unresolved_ctxt, top_level_ctxt, &top_level_vars);
if assign.op != op!("=") {
let ids_used_by_left = ids_used_by_ignoring_nested(
&assign.left,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
used_ids.read.extend(used_ids.write.iter().cloned());
used_ids.read.extend(ids_used_by_left.read);
used_ids.write.extend(ids_used_by_left.write);
}
let side_effects = used_ids.found_unresolved;
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
content: item.clone(),
side_effects,
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
ModuleItem::ModuleDecl(
ModuleDecl::ExportDefaultDecl(..)
| ModuleDecl::ExportDefaultExpr(..)
| ModuleDecl::ExportNamed(NamedExport { .. })
| ModuleDecl::ExportAll(..),
) => {}
_ => {
// Default to normal
let used_ids = ids_used_by_ignoring_nested(
item,
unresolved_ctxt,
top_level_ctxt,
&top_level_vars,
);
let captured_ids =
ids_captured_by(item, unresolved_ctxt, top_level_ctxt, &top_level_vars);
let data = ItemData {
read_vars: used_ids.read,
eventual_read_vars: captured_ids.read,
write_vars: used_ids.write,
eventual_write_vars: captured_ids.write,
side_effects: true,
content: item.clone(),
..Default::default()
};
let id = ItemId::Item {
index,
kind: ItemIdItemKind::Normal,
};
ids.push(id.clone());
items.insert(id, data);
}
}
}
for (local, export_name) in exports {
let id = ItemId::Group(ItemIdGroupKind::Export(local.clone(), export_name.clone()));
ids.push(id.clone());
items.insert(
id.clone(),
ItemData {
content: ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport {
span: DUMMY_SP,
specifiers: vec![ExportSpecifier::Named(ExportNamedSpecifier {
span: DUMMY_SP,
orig: ModuleExportName::Ident(local.clone().into()),
exported: if local.0 == export_name {
None
} else {
Some(ModuleExportName::Ident(export_name.clone().into()))
},
is_type_only: false,
})],
src: None,
type_only: false,
with: None,
})),
read_vars: [local.clone()].into_iter().collect(),
export: Some(export_name),
..Default::default()
},
);
}
(ids, items)
}
pub(super) fn add_strong_deps<'a, T>(&mut self, from: &ItemId, to: T)
where
T: IntoIterator<Item = &'a ItemId>,
{
// This value cannot be lazily initialized because we need to ensure that
// ModuleEvaluation exists even if there's no side effect.
let from = self.g.node(from);
for to in to {
let to = self.g.node(to);
self.g.idx_graph.add_edge(from, to, Dependency::Strong);
}
}
pub(super) fn add_weak_deps<'a, T>(&mut self, from: &ItemId, to: T)
where
T: IntoIterator<Item = &'a ItemId>,
{
let from = self.g.node(from);
for to in to {
let to = self.g.node(to);
if let Some(Dependency::Strong) = self.g.idx_graph.edge_weight(from, to) {
continue;
}
self.g.idx_graph.add_edge(from, to, Dependency::Weak);
}
}
pub(crate) fn has_dep(&mut self, id: &ItemId, dep: &ItemId, only_strong: bool) -> bool {
let from = self.g.node(id);
let to = self.g.node(dep);
self.g
.idx_graph
.edge_weight(from, to)
.map(|d| matches!(d, Dependency::Strong) || !only_strong)
.unwrap_or(false)
}
pub(crate) fn has_path_connecting(&mut self, from: &ItemId, to: &ItemId) -> bool {
let from = self.g.node(from);
let to = self.g.node(to);
has_path_connecting(&self.g.idx_graph, from, to, None)
}
/// Workaround for implicit export issue of server actions.
///
/// Inline server actions require the generated `$$RSC_SERVER_0` to be **exported**.
///
/// But tree shaking works by removing unused code, and the **export** of $$RSC_SERVER_0
/// is clearly not used from the external module as it does not exist at all
/// in the user code.
///
/// So we need to add an import for $$RSC_SERVER_0 to the module, so that the export is
/// preserved.
fn workaround_server_action(
&mut self,
g: &mut Graph<u32, Dependency>,
data: &FxHashMap<ItemId, ItemData>,
) {
fn collect_deps(
g: &Graph<u32, Dependency>,
done: &mut FxHashSet<NodeIndex>,
node: NodeIndex,
) -> Vec<NodeIndex> {
let direct_deps = g
.edges_directed(node, Direction::Outgoing)
.map(|e| e.target())
.collect::<Vec<_>>();
if direct_deps.iter().all(|dep| done.contains(dep)) {
return direct_deps;
}
direct_deps
.into_iter()
.flat_map(|dep| {
let mut v = if !done.insert(dep) {
vec![]
} else {
collect_deps(g, done, dep)
};
v.push(dep);
v
})
.collect()
}
let mut server_action_decls = FxHashMap::default();
let mut server_action_exports = FxHashMap::default();
for node in g.node_indices() {
let Some(ix) = g.node_weight(node) else {
continue;
};
let item_id = self.g.graph_ix.get_index(*ix as _).unwrap();
if let ItemId::Group(ItemIdGroupKind::Export(v, name)) = item_id
&& name.starts_with("$$RSC_SERVER_")
{
server_action_exports.insert(v.0.clone(), node);
}
let item_data = &data[item_id];
for v in item_data.var_decls.iter() {
if v.0.starts_with("$$RSC_SERVER_") {
server_action_decls.insert(node, v.0.clone());
}
}
}
if server_action_decls.is_empty() || server_action_exports.is_empty() {
return;
}
let mut queue = vec![];
for node in g.node_indices() {
let Some(ix) = g.node_weight(node) else {
continue;
};
let is_export_node = {
let item_id = self.g.graph_ix.get_index(*ix as _).unwrap();
matches!(item_id, ItemId::Group(ItemIdGroupKind::Export(..)))
};
if !is_export_node {
continue;
}
// If an export uses $$RSC_SERVER_0, depend on "export $$RSC_SERVER_0"
let mut done = FxHashSet::default();
let dependencies = collect_deps(g, &mut done, node);
for &dependency in dependencies.iter() {
if dependency == node {
continue;
}
let Some(action_item_id) = server_action_decls.get(&dependency) else {
continue;
};
let Some(action_export_node) = server_action_exports.get(action_item_id) else {
continue;
};
queue.push((node, *action_export_node));
}
}
for (export_node, dep) in queue {
g.add_edge(export_node, dep, Dependency::Strong);
}
}
}
const ASSERT_CHUNK_KEY: &str = "__turbopack_part__";
#[derive(Debug, Clone)]
pub(crate) enum PartId {
ModuleEvaluation,
Exports,
Export(RcStr),
/// `(part_id, is_for_eval)`
Internal(u32, bool),
}
pub(crate) fn create_turbopack_part_id_assert(dep: PartId) -> ObjectLit {
// We can't use quote! as `with` is not standard yet
ObjectLit {
span: DUMMY_SP,
props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new(ASSERT_CHUNK_KEY.into(), DUMMY_SP)),
value: match dep {
PartId::ModuleEvaluation => "module evaluation".into(),
PartId::Exports => "exports".into(),
PartId::Export(e) => format!("export {e}").into(),
PartId::Internal(dep, is_for_eval) => {
let v = dep as f64;
if is_for_eval { v } else { -v }
}
.into(),
},
})))],
}
}
pub(crate) fn find_turbopack_part_id_in_asserts(asserts: &ObjectLit) -> Option<PartId> {
asserts.props.iter().find_map(|prop| match prop {
PropOrSpread::Prop(box Prop::KeyValue(KeyValueProp {
key: PropName::Ident(key),
value: box Expr::Lit(Lit::Num(chunk_id)),
})) if &*key.sym == ASSERT_CHUNK_KEY => Some(PartId::Internal(
chunk_id.value.abs() as u32,
chunk_id.value.is_sign_positive(),
)),
PropOrSpread::Prop(box Prop::KeyValue(KeyValueProp {
key: PropName::Ident(key),
value: box Expr::Lit(Lit::Str(s)),
})) if &*key.sym == ASSERT_CHUNK_KEY => match &*s.value {
"module evaluation" => Some(PartId::ModuleEvaluation),
"exports" => Some(PartId::Exports),
_ if s.value.starts_with("export ") => Some(PartId::Export(s.value[7..].into())),
_ => None,
},
_ => None,
})
}
/// givin a number, return a base54 encoded string
/// `usize -> [a-zA-Z$_][a-zA-Z$_0-9]*`
pub(crate) fn encode_base54(init: &mut usize, skip_reserved: bool) -> Atom {
static BASE54_CHARS: &[u8; 64] =
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
let mut n = *init;
*init += 1;
let mut base = 54;
while n >= base {
n -= base;
base <<= 6;
}
// Not sure if this is ideal, but it's safe
let mut ret = Vec::with_capacity(14);
base /= 54;
let mut c = BASE54_CHARS[n / base];
ret.push(c);
while base > 1 {
n %= base;
base >>= 6;
c = BASE54_CHARS[n / base];
ret.push(c);
}
let s = unsafe {
// Safety: We are only using ascii characters
// Safety: The stack memory for ret is alive while creating Atom
Atom::from(std::str::from_utf8_unchecked(&ret))
};
if skip_reserved
&& (s.is_reserved() || s.is_reserved_in_strict_bind() || s.is_reserved_in_strict_mode(true))
{
return encode_base54(init, skip_reserved);
}
s
}
|