File size: 32,497 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 |
use std::{borrow::Cow, collections::hash_map::Entry};
use anyhow::{Ok, Result};
use either::Either;
use next_core::{
next_client_reference::{
ClientReference, ClientReferenceGraphResult, ClientReferenceType, ServerEntries,
find_server_entries,
},
next_dynamic::NextDynamicEntryModule,
next_manifests::ActionLayer,
};
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{
CollectiblesSource, FxIndexMap, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt,
ValueToString, Vc,
};
use turbo_tasks_fs::FileSystemPath;
use turbopack::css::{CssModuleAsset, ModuleCssAsset};
use turbopack_core::{
context::AssetContext,
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
module::Module,
module_graph::{GraphTraversalAction, ModuleGraph, SingleModuleGraph},
};
use crate::{
client_references::{ClientManifestEntryType, ClientReferenceManifest, map_client_references},
dynamic_imports::{DynamicImportEntries, DynamicImportEntriesMapType, map_next_dynamic},
server_actions::{AllActions, AllModuleActions, map_server_actions, to_rsc_context},
};
#[turbo_tasks::value]
pub struct NextDynamicGraph {
is_single_page: bool,
graph: ResolvedVc<SingleModuleGraph>,
/// list of NextDynamicEntryModules
data: ResolvedVc<DynamicImportEntries>,
}
#[turbo_tasks::value(transparent)]
pub struct DynamicImportEntriesWithImporter(
pub Vec<(
ResolvedVc<NextDynamicEntryModule>,
Option<ClientReferenceType>,
)>,
);
#[turbo_tasks::value_impl]
impl NextDynamicGraph {
#[turbo_tasks::function]
pub async fn new_with_entries(
graph: ResolvedVc<SingleModuleGraph>,
is_single_page: bool,
) -> Result<Vc<Self>> {
let mapped = map_next_dynamic(*graph);
Ok(NextDynamicGraph {
is_single_page,
graph,
data: mapped.to_resolved().await?,
}
.cell())
}
#[turbo_tasks::function]
pub async fn get_next_dynamic_imports_for_endpoint(
&self,
entry: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<DynamicImportEntriesWithImporter>> {
let span = tracing::info_span!("collect next/dynamic imports for endpoint");
async move {
let data = &*self.data.await?;
let graph = &*self.graph.await?;
#[derive(Clone, PartialEq, Eq)]
enum VisitState {
Entry,
InClientReference(ClientReferenceType),
}
let entries = if !self.is_single_page {
if !graph.has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(Vc::cell(vec![]));
}
Either::Left(std::iter::once(entry))
} else {
Either::Right(graph.entry_modules())
};
let mut result = vec![];
// module -> the client reference entry (if any)
let mut state_map = FxHashMap::default();
graph.traverse_edges_from_entries(entries, |parent_info, node| {
let module = node.module;
let Some((parent_node, _)) = parent_info else {
state_map.insert(module, VisitState::Entry);
return GraphTraversalAction::Continue;
};
let parent_module = parent_node.module;
let module_type = data.get(&module);
let parent_state = state_map.get(&parent_module).unwrap().clone();
let parent_client_reference =
if let Some(DynamicImportEntriesMapType::ClientReference(module)) = module_type
{
Some(ClientReferenceType::EcmascriptClientReference(*module))
} else if let VisitState::InClientReference(ty) = parent_state {
Some(ty)
} else {
None
};
match module_type {
Some(DynamicImportEntriesMapType::DynamicEntry(dynamic_entry)) => {
result.push((*dynamic_entry, parent_client_reference));
state_map.insert(module, parent_state);
GraphTraversalAction::Skip
}
Some(DynamicImportEntriesMapType::ClientReference(client_reference)) => {
state_map.insert(
module,
VisitState::InClientReference(
ClientReferenceType::EcmascriptClientReference(*client_reference),
),
);
GraphTraversalAction::Continue
}
None => {
state_map.insert(module, parent_state);
GraphTraversalAction::Continue
}
}
})?;
Ok(Vc::cell(result))
}
.instrument(span)
.await
}
}
#[turbo_tasks::value]
pub struct ServerActionsGraph {
is_single_page: bool,
graph: ResolvedVc<SingleModuleGraph>,
/// (Layer, RSC or Browser module) -> list of actions
data: ResolvedVc<AllModuleActions>,
}
#[turbo_tasks::value_impl]
impl ServerActionsGraph {
#[turbo_tasks::function]
pub async fn new_with_entries(
graph: ResolvedVc<SingleModuleGraph>,
is_single_page: bool,
) -> Result<Vc<Self>> {
let mapped = map_server_actions(*graph);
Ok(ServerActionsGraph {
is_single_page,
graph,
data: mapped.to_resolved().await?,
}
.cell())
}
#[turbo_tasks::function]
pub async fn get_server_actions_for_endpoint(
&self,
entry: ResolvedVc<Box<dyn Module>>,
rsc_asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<AllActions>> {
let span = tracing::info_span!("collect server actions for endpoint");
async move {
let data = &*self.data.await?;
let data = if self.is_single_page {
// The graph contains the page (= `entry`) only, no need to filter.
Cow::Borrowed(data)
} else {
// The graph contains the whole app, traverse and collect all reachable imports.
let graph = &*self.graph.await?;
if !graph.has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(Vc::cell(Default::default()));
}
let mut result = FxIndexMap::default();
graph.traverse_from_entry(entry, |node| {
if let Some(node_data) = data.get(&node.module) {
result.insert(node.module, *node_data);
}
})?;
Cow::Owned(result)
};
let actions = data
.iter()
.map(|(module, (layer, actions))| async move {
let actions = actions.await?;
actions
.actions
.iter()
.map(async |(hash, name)| {
Ok((
hash.to_string(),
(
*layer,
name.to_string(),
if *layer == ActionLayer::Rsc {
*module
} else {
to_rsc_context(
**module,
&actions.entry_path,
&actions.entry_query,
rsc_asset_context,
)
.await?
},
),
))
})
.try_join()
.await
})
.try_flat_join()
.await?;
Ok(Vc::cell(actions.into_iter().collect()))
}
.instrument(span)
.await
}
}
#[turbo_tasks::value]
pub struct ClientReferencesGraph {
is_single_page: bool,
graph: ResolvedVc<SingleModuleGraph>,
/// List of client references (modules that entries into the client graph)
data: ResolvedVc<ClientReferenceManifest>,
}
#[turbo_tasks::value_impl]
impl ClientReferencesGraph {
#[turbo_tasks::function]
pub async fn new_with_entries(
graph: ResolvedVc<SingleModuleGraph>,
is_single_page: bool,
) -> Result<Vc<Self>> {
// TODO if is_single_page, then perform the graph traversal below in map_client_references
// already, which saves us a traversal.
let mapped = map_client_references(*graph);
Ok(Self {
is_single_page,
graph,
data: mapped.to_resolved().await?,
}
.cell())
}
#[turbo_tasks::function]
async fn get_client_references_for_endpoint(
&self,
entry: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ClientReferenceGraphResult>> {
let span = tracing::info_span!("collect client references for endpoint");
async move {
let data = &*self.data.await?;
let graph = &*self.graph.await?;
let entries = if !self.is_single_page {
if !graph.has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(ClientReferenceGraphResult::default().cell());
}
Either::Left(std::iter::once(entry))
} else {
Either::Right(graph.entry_modules())
};
// Because we care about 'evaluation order' we need to collect client references in the
// post_order callbacks which is the same as evaluation order
let mut client_references = Vec::new();
let mut client_reference_modules = Vec::new();
let mut server_components = FxHashSet::default();
// Track how we reached each client reference. This way if a client reference is
// referenced by the root and by a server component we don't only associate it with the
// server component.
#[derive(PartialEq, Eq, Copy, Clone)]
enum ParentType {
ServerComponent,
Page,
Both,
}
impl ParentType {
fn merge(left: Self, right: Self) -> Self {
if left == right {
left
} else {
// One is Both or one is ServerComponent and the other is Page, which means
// Both
Self::Both
}
}
}
// Perform a DFS traversal to collect all client references and the set of server
// components for each module.
graph.traverse_edges_from_entries_dfs(
entries,
// state_map is `module -> ParentType` to track whether the module is reachable
// directly from an entry point.
&mut FxHashMap::default(),
|parent_info, node, state_map| {
let module = node.module();
let module_type = data.manifest.get(&module);
let parent_type =
if let Some(ClientManifestEntryType::ServerComponent(_)) = module_type {
ParentType::ServerComponent
} else if let Some((parent_node, _)) = parent_info {
*state_map.get(&parent_node.module).unwrap()
} else {
// a root node
ParentType::Page
};
match state_map.entry(module) {
Entry::Occupied(mut occupied_entry) => {
let current = occupied_entry.get_mut();
let merged = ParentType::merge(*current, parent_type);
if merged != parent_type {
*current = merged;
}
}
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(parent_type);
}
}
Ok(match module_type {
Some(
ClientManifestEntryType::EcmascriptClientReference { .. }
| ClientManifestEntryType::CssClientReference { .. },
) => GraphTraversalAction::Skip,
_ => GraphTraversalAction::Continue,
})
},
|_, node, state_map| {
let module = node.module();
let Some(module_type) = data.manifest.get(&module) else {
return Ok(());
};
let ty = match module_type {
ClientManifestEntryType::EcmascriptClientReference {
module,
ssr_module: _,
} => ClientReferenceType::EcmascriptClientReference(*module),
ClientManifestEntryType::CssClientReference(module) => {
ClientReferenceType::CssClientReference(*module)
}
ClientManifestEntryType::ServerComponent(sc) => {
server_components.insert(*sc);
return Ok(());
}
};
if *state_map.get(&module).unwrap() == ParentType::ServerComponent {
// This is only reachable through server components, we need to wait to
// compute the client references until we have seen all server components
// reachable by this entrypoint, then we can intersect that with the set of
// server components that depend on this client reference
client_reference_modules.push((module, ty));
} else {
// Otherwise there is some path from the root directly to the reference,
// just associate it with the root.
client_references.push(ClientReference {
server_component: None,
ty,
})
}
Ok(())
},
)?;
// Now compute all the parent components for each client reference module reachable from
// server components
client_references.extend(client_reference_modules.into_iter().flat_map(
|(module, ty)| {
data.server_components_for_client_reference(module)
.filter(|sc| server_components.contains(sc))
.map(move |sc| ClientReference {
server_component: Some(sc),
ty,
})
},
));
Ok(ClientReferenceGraphResult {
client_references: client_references.into_iter().collect(),
server_utils: vec![],
server_component_entries: vec![],
}
.cell())
}
.instrument(span)
.await
}
}
#[turbo_tasks::value(shared)]
struct CssGlobalImportIssue {
parent_module: ResolvedVc<Box<dyn Module>>,
module: ResolvedVc<Box<dyn Module>>,
}
impl CssGlobalImportIssue {
fn new(
parent_module: ResolvedVc<Box<dyn Module>>,
module: ResolvedVc<Box<dyn Module>>,
) -> Self {
Self {
parent_module,
module,
}
}
}
#[turbo_tasks::value_impl]
impl Issue for CssGlobalImportIssue {
#[turbo_tasks::function]
async fn title(&self) -> Vc<StyledString> {
StyledString::Stack(vec![
StyledString::Text("Failed to compile".into()),
StyledString::Text(
"Global CSS cannot be imported from files other than your Custom <App>. Due to \
the Global nature of stylesheets, and to avoid conflicts, Please move all \
first-party global CSS imports to pages/_app.js. Or convert the import to \
Component-Level CSS (CSS Modules)."
.into(),
),
StyledString::Text("Read more: https://nextjs.org/docs/messages/css-global".into()),
])
.cell()
}
#[turbo_tasks::function]
async fn description(&self) -> Result<Vc<OptionStyledString>> {
let parent_path = self.parent_module.ident().path().owned().await?;
let module_path = self.module.ident().path().owned().await?;
let relative_import_location = parent_path.parent();
let import_path = match relative_import_location.get_relative_path_to(&module_path) {
Some(path) => path,
None => module_path.path.clone(),
};
let cleaned_import_path =
if import_path.ends_with(".scss.css") || import_path.ends_with(".sass.css") {
RcStr::from(import_path.trim_end_matches(".css"))
} else {
import_path
};
Ok(Vc::cell(Some(
StyledString::Stack(vec![
StyledString::Text(format!("Location: {}", parent_path.path).into()),
StyledString::Text(format!("Import path: {cleaned_import_path}",).into()),
])
.resolved_cell(),
)))
}
fn severity(&self) -> IssueSeverity {
IssueSeverity::Error
}
#[turbo_tasks::function]
fn file_path(&self) -> Vc<FileSystemPath> {
self.parent_module.ident().path()
}
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::ProcessModule.into()
}
// TODO(PACK-4879): compute the source information by following the module references
}
type FxModuleNameMap = FxIndexMap<ResolvedVc<Box<dyn Module>>, RcStr>;
#[turbo_tasks::value(transparent)]
struct ModuleNameMap(pub FxModuleNameMap);
#[turbo_tasks::function]
async fn validate_pages_css_imports(
graph: Vc<SingleModuleGraph>,
is_single_page: bool,
entry: Vc<Box<dyn Module>>,
app_module: ResolvedVc<Box<dyn Module>>,
module_name_map: ResolvedVc<ModuleNameMap>,
) -> Result<()> {
let graph = &*graph.await?;
let entry = entry.to_resolved().await?;
let module_name_map = module_name_map.await?;
let entries = if !is_single_page {
if !graph.has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(());
}
Either::Left(std::iter::once(entry))
} else {
Either::Right(graph.entry_modules())
};
graph.traverse_edges_from_entries(entries, |parent_info, node| {
let module = node.module;
// If the module being imported isn't a global css module, there is nothing to validate.
let module_is_global_css =
ResolvedVc::try_downcast_type::<CssModuleAsset>(module).is_some();
if !module_is_global_css {
return GraphTraversalAction::Continue;
}
// We allow imports of global CSS files which are inside of `node_modules`.
let module_name_contains_node_modules = module_name_map
.get(&module)
.is_some_and(|s| s.contains("node_modules"));
if module_name_contains_node_modules {
return GraphTraversalAction::Continue;
}
// If we're at a root node, there is nothing importing this module and we can skip
// any further validations.
let Some((parent_node, _)) = parent_info else {
return GraphTraversalAction::Continue;
};
let parent_module = parent_node.module;
let parent_is_css_module = ResolvedVc::try_downcast_type::<ModuleCssAsset>(parent_module)
.is_some()
|| ResolvedVc::try_downcast_type::<CssModuleAsset>(parent_module).is_some();
// We also always allow .module css/scss/sass files to import global css files as well.
if parent_is_css_module {
return GraphTraversalAction::Continue;
}
// If all of the above invariants have been checked, we look to see if the parent module is
// the same as the app module. If it isn't we know it isn't a valid place to import global
// css.
if parent_module != app_module {
CssGlobalImportIssue::new(parent_module, module)
.resolved_cell()
.emit();
}
GraphTraversalAction::Continue
})?;
Ok(())
}
/// The consumers of this shouldn't need to care about the exact contents since it's abstracted away
/// by the accessor functions, but
/// - In dev, contains information about the modules of the current endpoint only
/// - In prod, there is a single `GlobalBuildInformation` for the whole app, containing all pages
#[turbo_tasks::value]
pub struct GlobalBuildInformation {
next_dynamic: Vec<ResolvedVc<NextDynamicGraph>>,
server_actions: Vec<ResolvedVc<ServerActionsGraph>>,
client_references: Vec<ResolvedVc<ClientReferencesGraph>>,
// Data for some more ad-hoc operations
bare_graphs: ResolvedVc<ModuleGraph>,
is_single_page: bool,
}
#[turbo_tasks::value_impl]
impl GlobalBuildInformation {
#[turbo_tasks::function]
pub async fn new(graphs: Vc<ModuleGraph>, is_single_page: bool) -> Result<Vc<Self>> {
let graphs_ref = &graphs.await?.graphs;
let next_dynamic = async {
graphs_ref
.iter()
.map(|graph| {
NextDynamicGraph::new_with_entries(**graph, is_single_page).to_resolved()
})
.try_join()
.await
}
.instrument(tracing::info_span!("generating next/dynamic graphs"));
let server_actions = async {
graphs_ref
.iter()
.map(|graph| {
ServerActionsGraph::new_with_entries(**graph, is_single_page).to_resolved()
})
.try_join()
.await
}
.instrument(tracing::info_span!("generating server actions graphs"));
let client_references = async {
graphs_ref
.iter()
.map(|graph| {
ClientReferencesGraph::new_with_entries(**graph, is_single_page).to_resolved()
})
.try_join()
.await
}
.instrument(tracing::info_span!("generating client references graphs"));
let (next_dynamic, server_actions, client_references) =
futures::join!(next_dynamic, server_actions, client_references);
Ok(Self {
next_dynamic: next_dynamic?,
server_actions: server_actions?,
client_references: client_references?,
bare_graphs: graphs.to_resolved().await?,
is_single_page,
}
.cell())
}
/// Returns the next/dynamic-ally imported (client) modules (from RSC and SSR modules) for the
/// given endpoint.
#[turbo_tasks::function]
pub async fn get_next_dynamic_imports_for_endpoint(
&self,
entry: Vc<Box<dyn Module>>,
) -> Result<Vc<DynamicImportEntriesWithImporter>> {
let span = tracing::info_span!("collect all next/dynamic imports for endpoint");
async move {
if let [graph] = &self.next_dynamic[..] {
// Just a single graph, no need to merge results
Ok(graph.get_next_dynamic_imports_for_endpoint(entry))
} else {
let result = self
.next_dynamic
.iter()
.map(|graph| async move {
Ok(graph
.get_next_dynamic_imports_for_endpoint(entry)
.await?
.into_iter()
.map(|(k, v)| (*k, *v))
// TODO remove this collect and return an iterator instead
.collect::<Vec<_>>())
})
.try_flat_join()
.await?;
Ok(Vc::cell(result.into_iter().collect()))
}
}
.instrument(span)
.await
}
/// Returns the server actions for the given page.
#[turbo_tasks::function]
pub async fn get_server_actions_for_endpoint(
&self,
entry: Vc<Box<dyn Module>>,
rsc_asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<AllActions>> {
let span = tracing::info_span!("collect all server actions for endpoint");
async move {
if let [graph] = &self.server_actions[..] {
// Just a single graph, no need to merge results
Ok(graph.get_server_actions_for_endpoint(entry, rsc_asset_context))
} else {
let result = self
.server_actions
.iter()
.map(|graph| async move {
graph
.get_server_actions_for_endpoint(entry, rsc_asset_context)
.owned()
.await
})
.try_flat_join()
.await?;
Ok(Vc::cell(result.into_iter().collect()))
}
}
.instrument(span)
.await
}
/// Returns the client references for the given page.
#[turbo_tasks::function]
pub async fn get_client_references_for_endpoint(
&self,
entry: Vc<Box<dyn Module>>,
has_layout_segments: bool,
include_traced: bool,
) -> Result<Vc<ClientReferenceGraphResult>> {
let span = tracing::info_span!("collect all client references for endpoint");
async move {
let mut result = if let [graph] = &self.client_references[..] {
// Just a single graph, no need to merge results
graph
.get_client_references_for_endpoint(entry)
.owned()
.await?
} else {
let results = self
.client_references
.iter()
.map(|graph| graph.get_client_references_for_endpoint(entry))
.try_join()
.await?;
let mut iter = results.into_iter();
let mut result = ReadRef::into_owned(iter.next().unwrap());
for r in iter {
result.extend(&r);
}
result
};
// TODO(luke.sandberg): at least in the whole_app_module_graph case we should be able to
// collect server components and server utilities during the above traversals in the
// correct order. `find_server_entries returns them in reverse topological order (root
// layout first, page last) but the above traversals find them in DFS post
// order which means we would need to reverse it.
// For server_utils the order is irrelevant.
if has_layout_segments {
// Do this separately for now, because the graph traversal order messes up the order
// of the server_component_entries.
let ServerEntries {
server_utils,
server_component_entries,
} = &*find_server_entries(entry, include_traced).await?;
result.server_utils = server_utils.clone();
result.server_component_entries = server_component_entries.clone();
}
Ok(result.cell())
}
.instrument(span)
.await
}
#[turbo_tasks::function]
/// Validates that the global CSS/SCSS/SASS imports are only valid imports with the following
/// rules:
/// * The import is made from a `node_modules` package
/// * The import is made from a `.module.css` file
/// * The import is made from the `pages/_app.js`, or equivalent file.
pub async fn validate_pages_css_imports(
&self,
entry: Vc<Box<dyn Module>>,
app_module: Vc<Box<dyn Module>>,
) -> Result<()> {
let span = tracing::info_span!("validate pages css imports");
async move {
let graphs = &self.bare_graphs.await?.graphs;
// We need to collect the module names here to pass into the
// `validate_pages_css_imports` function. This is because the function is
// called for each graph, and we need to know the module names of the parent
// modules to determine if the import is valid. We can't do this in the
// called function because it's within a closure that can't resolve turbo tasks.
let graph_to_module_ident_tuples = async |graph: &ResolvedVc<SingleModuleGraph>| {
graph
.await?
.graph
.node_weights()
.map(async |n| Ok((n.module(), n.module().ident().to_string().owned().await?)))
.try_join()
.await
};
let identifier_map = graphs
.iter()
.map(graph_to_module_ident_tuples)
.try_join()
.await?
.into_iter()
.flatten()
.collect::<FxIndexMap<_, _>>();
let identifier_map = ModuleNameMap(identifier_map).cell();
graphs
.iter()
.map(|graph| {
validate_pages_css_imports(
**graph,
self.is_single_page,
entry,
app_module,
identifier_map,
)
.as_side_effect()
})
.try_join()
.await?;
Ok(())
}
.instrument(span)
.await
}
}
#[turbo_tasks::function(operation)]
fn get_global_information_for_endpoint_inner_operation(
module_graph: ResolvedVc<ModuleGraph>,
is_single_page: bool,
) -> Vc<GlobalBuildInformation> {
GlobalBuildInformation::new(*module_graph, is_single_page)
}
/// Generates a [GlobalBuildInformation] for the given project and endpoint containing information
/// that is either global (module ids, chunking) or computed globally as a performance optimization
/// (client references, etc).
#[turbo_tasks::function]
pub async fn get_global_information_for_endpoint(
module_graph: ResolvedVc<ModuleGraph>,
is_single_page: bool,
) -> Result<Vc<GlobalBuildInformation>> {
// TODO get rid of this function once everything inside of
// `get_global_information_for_endpoint_inner` calls `take_collectibles()` when needed
let result_op =
get_global_information_for_endpoint_inner_operation(module_graph, is_single_page);
let result_vc = if !is_single_page {
let result_vc = result_op.resolve_strongly_consistent().await?;
let _issues = result_op.take_collectibles::<Box<dyn Issue>>();
*result_vc
} else {
result_op.connect()
};
Ok(result_vc)
}
|