Unverified Commit 16d009ef authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

separate chunking per layout parts (#60569)

### What?

* creates a separate chunk group for client components per layout
segment (before it was per page)

### Why?

This fixes a bug with css loading on client transitions as next.js
assumes that the chunk group for the unchanged layout segments are
already loaded (fixes PACK-2163)


Closes PACK-2232
parent 4597ff35
...@@ -19,9 +19,7 @@ use next_core::{ ...@@ -19,9 +19,7 @@ use next_core::{
get_client_module_options_context, get_client_resolve_options_context, get_client_module_options_context, get_client_resolve_options_context,
get_client_runtime_entries, ClientContextType, RuntimeEntries, get_client_runtime_entries, ClientContextType, RuntimeEntries,
}, },
next_client_reference::{ next_client_reference::{ClientReferenceGraph, NextEcmascriptClientReferenceTransition},
ClientReferenceGraph, ClientReferenceType, NextEcmascriptClientReferenceTransition,
},
next_dynamic::NextDynamicTransition, next_dynamic::NextDynamicTransition,
next_edge::route_regex::get_named_middleware_regex, next_edge::route_regex::get_named_middleware_regex,
next_manifests::{ next_manifests::{
...@@ -611,10 +609,6 @@ impl AppEndpoint { ...@@ -611,10 +609,6 @@ impl AppEndpoint {
// )) // ))
// .await?; // .await?;
let app_entry_client_references = client_reference_graph
.entry(Vc::upcast(app_entry.rsc_entry))
.await?;
let runtime = app_entry.config.await?.runtime.unwrap_or_default(); let runtime = app_entry.config.await?.runtime.unwrap_or_default();
if ssr_and_client { if ssr_and_client {
...@@ -626,8 +620,7 @@ impl AppEndpoint { ...@@ -626,8 +620,7 @@ impl AppEndpoint {
}; };
let client_references_chunks = get_app_client_references_chunks( let client_references_chunks = get_app_client_references_chunks(
app_entry.rsc_entry.ident(), client_references,
client_reference_types,
this.app_project.project().client_chunking_context(), this.app_project.project().client_chunking_context(),
ssr_chunking_context, ssr_chunking_context,
); );
...@@ -636,13 +629,23 @@ impl AppEndpoint { ...@@ -636,13 +629,23 @@ impl AppEndpoint {
let mut entry_client_chunks = IndexSet::new(); let mut entry_client_chunks = IndexSet::new();
// TODO(alexkirsz) In which manifest does this go? // TODO(alexkirsz) In which manifest does this go?
let mut entry_ssr_chunks = IndexSet::new(); let mut entry_ssr_chunks = IndexSet::new();
for client_reference in app_entry_client_references.iter() { for chunks in client_references_chunks_ref
let client_reference_chunks = client_references_chunks_ref .layout_segment_client_chunks
.get(client_reference.ty()) .values()
.context("client reference should have corresponding chunks")?; {
entry_client_chunks entry_client_chunks.extend(chunks.await?.iter().copied());
.extend(client_reference_chunks.client_chunks.await?.iter().copied()); }
entry_ssr_chunks.extend(client_reference_chunks.ssr_chunks.await?.iter().copied()); for chunks in client_references_chunks_ref
.client_component_client_chunks
.values()
{
client_assets.extend(chunks.await?.iter().copied());
}
for chunks in client_references_chunks_ref
.client_component_ssr_chunks
.values()
{
entry_ssr_chunks.extend(chunks.await?.iter().copied());
} }
client_assets.extend(entry_client_chunks.iter().copied()); client_assets.extend(entry_client_chunks.iter().copied());
...@@ -718,12 +721,13 @@ impl AppEndpoint { ...@@ -718,12 +721,13 @@ impl AppEndpoint {
// initialization // initialization
let client_references_chunks = &*client_references_chunks.await?; let client_references_chunks = &*client_references_chunks.await?;
for (ty, chunks) in client_references_chunks { for &ssr_chunks in client_references_chunks
if matches!(ty, ClientReferenceType::EcmascriptClientReference(..)) { .client_component_ssr_chunks
let ssr_chunks = &*chunks.ssr_chunks.await?; .values()
{
let ssr_chunks = ssr_chunks.await?;
middleware_assets.extend(ssr_chunks); middleware_assets.extend(ssr_chunks);
}
} }
} }
} }
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc};
debug::ValueDebugFormat, trace::TraceRawVcs, TryFlatJoinIterExt, TryJoinIterExt, Vc,
};
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{chunk::ChunkingContextExt, ident::AssetIdent, module::Module, output::OutputAssets}, core::{
chunk::{availability_info::AvailabilityInfo, ChunkingContext, ChunkingContextExt},
module::Module,
output::OutputAssets,
},
ecmascript::chunk::EcmascriptChunkingContext, ecmascript::chunk::EcmascriptChunkingContext,
}; };
use super::include_modules_module::IncludeModulesModule; use super::include_modules_module::IncludeModulesModule;
use crate::next_client_reference::{ClientReferenceType, ClientReferenceTypes}; use crate::{
next_client_reference::{
/// Contains the chunks corresponding to a client reference. visit_client_reference::ClientReferenceGraphResult, ClientReferenceType,
#[derive( ClientReferenceTypes,
Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, },
)] next_server_component::server_component_module::NextServerComponentModule,
pub struct ClientReferenceChunks { };
/// Chunks to be loaded on the client.
pub client_chunks: Vc<OutputAssets>, #[turbo_tasks::function]
/// Chunks to be loaded on the server for SSR. fn client_modules_modifier() -> Vc<String> {
pub ssr_chunks: Vc<OutputAssets>, Vc::cell("client modules".to_string())
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::function]
pub struct ClientReferencesChunks(IndexMap<ClientReferenceType, ClientReferenceChunks>); fn client_modules_ssr_modifier() -> Vc<String> {
Vc::cell("client modules ssr".to_string())
}
#[turbo_tasks::value]
pub struct ClientReferencesChunks {
pub client_component_client_chunks: IndexMap<ClientReferenceType, Vc<OutputAssets>>,
pub client_component_ssr_chunks: IndexMap<ClientReferenceType, Vc<OutputAssets>>,
pub layout_segment_client_chunks: IndexMap<Vc<NextServerComponentModule>, Vc<OutputAssets>>,
}
/// Computes all client references chunks. /// Computes all client references chunks.
/// ///
...@@ -33,115 +43,231 @@ pub struct ClientReferencesChunks(IndexMap<ClientReferenceType, ClientReferenceC ...@@ -33,115 +43,231 @@ pub struct ClientReferencesChunks(IndexMap<ClientReferenceType, ClientReferenceC
/// type needs to load. /// type needs to load.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_app_client_references_chunks( pub async fn get_app_client_references_chunks(
base_ident: Vc<AssetIdent>, app_client_references: Vc<ClientReferenceGraphResult>,
app_client_reference_types: Vc<ClientReferenceTypes>,
client_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>, client_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
ssr_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>, ssr_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
) -> Result<Vc<ClientReferencesChunks>> { ) -> Result<Vc<ClientReferencesChunks>> {
async move { async move {
// TODO Reconsider this. Maybe it need to be true in production. // TODO Reconsider this. Maybe it need to be true in production.
let separate_chunk_group_per_client_reference = false; let separate_chunk_group_per_client_reference = false;
let app_client_reference_types = app_client_reference_types.await?; let app_client_references = app_client_references.await?;
if separate_chunk_group_per_client_reference { if separate_chunk_group_per_client_reference {
let app_client_references_chunks: IndexMap<_, _> = app_client_reference_types let app_client_references_chunks: Vec<(_, (_, Option<_>))> = app_client_references
.client_references
.iter() .iter()
.map(|client_reference_ty| async move { .map(|client_reference| async move {
let client_reference_ty = client_reference.ty();
Ok(( Ok((
*client_reference_ty, client_reference_ty,
match client_reference_ty { match client_reference_ty {
ClientReferenceType::EcmascriptClientReference( ClientReferenceType::EcmascriptClientReference(
ecmascript_client_reference, ecmascript_client_reference,
) => { ) => {
let ecmascript_client_reference_ref = let ecmascript_client_reference_ref =
ecmascript_client_reference.await?; ecmascript_client_reference.await?;
ClientReferenceChunks { (
client_chunks: client_chunking_context.root_chunk_group_assets( client_chunking_context.root_chunk_group_assets(Vc::upcast(
Vc::upcast(ecmascript_client_reference_ref.client_module), ecmascript_client_reference_ref.client_module,
), )),
ssr_chunks: ssr_chunking_context.root_chunk_group_assets( Some(ssr_chunking_context.root_chunk_group_assets(Vc::upcast(
Vc::upcast(ecmascript_client_reference_ref.ssr_module), ecmascript_client_reference_ref.ssr_module,
), ))),
} )
} }
ClientReferenceType::CssClientReference(css_client_reference) => { ClientReferenceType::CssClientReference(css_client_reference) => {
let css_client_reference_ref = css_client_reference.await?; let css_client_reference_ref = css_client_reference.await?;
ClientReferenceChunks { (
client_chunks: client_chunking_context.root_chunk_group_assets( client_chunking_context.root_chunk_group_assets(Vc::upcast(
Vc::upcast(css_client_reference_ref.client_module), css_client_reference_ref.client_module,
), )),
ssr_chunks: OutputAssets::empty(), None,
} )
} }
}, },
)) ))
}) })
.try_join() .try_join()
.await? .await?;
.into_iter()
.collect();
Ok(Vc::cell(app_client_references_chunks)) Ok(ClientReferencesChunks {
client_component_client_chunks: app_client_references_chunks
.iter()
.map(|&(client_reference_ty, (client_chunks, _))| {
(client_reference_ty, client_chunks)
})
.collect(),
client_component_ssr_chunks: app_client_references_chunks
.iter()
.flat_map(|&(client_reference_ty, (_, ssr_chunks))| {
ssr_chunks.map(|ssr_chunks| (client_reference_ty, ssr_chunks))
})
.collect(),
layout_segment_client_chunks: IndexMap::new(),
}
.cell())
} else { } else {
let ssr_modules = app_client_reference_types let mut client_references_by_server_component: IndexMap<_, Vec<_>> = IndexMap::new();
.iter() let mut framework_reference_types = Vec::new();
.map(|client_reference_ty| async move { for &server_component in app_client_references.server_component_entries.iter() {
Ok(match client_reference_ty { client_references_by_server_component
ClientReferenceType::EcmascriptClientReference( .entry(server_component)
ecmascript_client_reference, .or_default();
) => { }
let ecmascript_client_reference_ref = for client_reference in app_client_references.client_references.iter() {
ecmascript_client_reference.await?; if let Some(server_component) = client_reference.server_component() {
Some(Vc::upcast(ecmascript_client_reference_ref.ssr_module)) client_references_by_server_component
} .entry(server_component)
_ => None, .or_default()
.push(client_reference.ty());
} else {
framework_reference_types.push(client_reference.ty());
}
}
// Framework components need to go into first layout segment
if let Some((_, list)) = client_references_by_server_component.first_mut() {
list.extend(framework_reference_types);
}
let mut current_client_availability_info = AvailabilityInfo::Root;
let mut current_client_chunks = OutputAssets::empty();
let mut current_ssr_availability_info = AvailabilityInfo::Root;
let mut current_ssr_chunks = OutputAssets::empty();
let mut layout_segment_client_chunks = IndexMap::new();
let mut client_component_ssr_chunks = IndexMap::new();
let mut client_component_client_chunks = IndexMap::new();
for (server_component, client_reference_types) in
client_references_by_server_component.into_iter()
{
let base_ident = server_component.ident();
let server_path = server_component.server_path();
let is_layout = server_path.file_stem().await?.as_deref() == Some("layout");
let server_component_path = server_path.to_string().await?;
let ssr_modules = client_reference_types
.iter()
.map(|client_reference_ty| async move {
Ok(match client_reference_ty {
ClientReferenceType::EcmascriptClientReference(
ecmascript_client_reference,
) => {
let ecmascript_client_reference_ref =
ecmascript_client_reference.await?;
Some(Vc::upcast(ecmascript_client_reference_ref.ssr_module))
}
_ => None,
})
}) })
}) .try_flat_join()
.try_flat_join() .await?;
.await?; let ssr_chunk_group = if !ssr_modules.is_empty() {
let ssr_entry_module = IncludeModulesModule::new( let ssr_entry_module = IncludeModulesModule::new(
base_ident.with_modifier(Vc::cell("client modules ssr".to_string())), base_ident.with_modifier(client_modules_ssr_modifier()),
Vc::cell(ssr_modules), ssr_modules,
); );
let client_modules = app_client_reference_types let _span = tracing::info_span!(
.iter() "server side rendering",
.map(|client_reference_ty| async move { layout_segment = display(&server_component_path),
Ok(match client_reference_ty { )
ClientReferenceType::EcmascriptClientReference( .entered();
ecmascript_client_reference, Some(ssr_chunking_context.chunk_group(
) => { Vc::upcast(ssr_entry_module),
let ecmascript_client_reference_ref = Value::new(current_ssr_availability_info),
ecmascript_client_reference.await?; ))
Vc::upcast(ecmascript_client_reference_ref.client_module) } else {
None
};
let client_modules = client_reference_types
.iter()
.map(|client_reference_ty| async move {
Ok(match client_reference_ty {
ClientReferenceType::EcmascriptClientReference(
ecmascript_client_reference,
) => {
let ecmascript_client_reference_ref =
ecmascript_client_reference.await?;
Vc::upcast(ecmascript_client_reference_ref.client_module)
}
ClientReferenceType::CssClientReference(css_client_reference) => {
let css_client_reference_ref = css_client_reference.await?;
Vc::upcast(css_client_reference_ref.client_module)
}
})
})
.try_join()
.await?;
let client_chunk_group = if !client_modules.is_empty() {
let client_entry_module = IncludeModulesModule::new(
base_ident.with_modifier(client_modules_modifier()),
client_modules,
);
let _span = tracing::info_span!(
"client side rendering",
layout_segment = display(&server_component_path),
)
.entered();
Some(client_chunking_context.chunk_group(
Vc::upcast(client_entry_module),
Value::new(current_client_availability_info),
))
} else {
None
};
if let Some(client_chunk_group) = client_chunk_group {
let client_chunk_group = client_chunk_group.await?;
let client_chunks =
current_client_chunks.concatenate(client_chunk_group.assets);
let client_chunks = client_chunks.resolve().await?;
if is_layout {
current_client_availability_info = client_chunk_group.availability_info;
current_client_chunks = client_chunks;
}
layout_segment_client_chunks.insert(server_component, client_chunks);
for &client_reference_ty in client_reference_types.iter() {
if let ClientReferenceType::EcmascriptClientReference(_) =
client_reference_ty
{
client_component_client_chunks
.insert(client_reference_ty, client_chunks);
} }
ClientReferenceType::CssClientReference(css_client_reference) => { }
let css_client_reference_ref = css_client_reference.await?; }
Vc::upcast(css_client_reference_ref.client_module)
if let Some(ssr_chunk_group) = ssr_chunk_group {
let ssr_chunk_group = ssr_chunk_group.await?;
let ssr_chunks = current_ssr_chunks.concatenate(ssr_chunk_group.assets);
let ssr_chunks = ssr_chunks.resolve().await?;
if is_layout {
current_ssr_availability_info = ssr_chunk_group.availability_info;
current_ssr_chunks = ssr_chunks;
}
for &client_reference_ty in client_reference_types.iter() {
if let ClientReferenceType::EcmascriptClientReference(_) =
client_reference_ty
{
client_component_ssr_chunks.insert(client_reference_ty, ssr_chunks);
} }
}) }
}) }
.try_join() }
.await?;
let client_entry_module = IncludeModulesModule::new(
base_ident.with_modifier(Vc::cell("client modules".to_string())),
Vc::cell(client_modules),
);
let global_entry_module = ClientReferenceChunks {
client_chunks: {
let _span = tracing::info_span!("client side rendering").entered();
client_chunking_context.root_chunk_group_assets(Vc::upcast(client_entry_module))
},
ssr_chunks: {
let _span = tracing::info_span!("server side rendering").entered();
ssr_chunking_context.root_chunk_group_assets(Vc::upcast(ssr_entry_module))
},
};
let app_client_references_chunks: IndexMap<_, _> = app_client_reference_types
.iter()
.map(move |&client_reference_ty| (client_reference_ty, global_entry_module.clone()))
.collect();
Ok(Vc::cell(app_client_references_chunks)) Ok(ClientReferencesChunks {
client_component_client_chunks,
client_component_ssr_chunks,
layout_segment_client_chunks,
}
.cell())
} }
} }
.instrument(tracing::info_span!("process client references")) .instrument(tracing::info_span!("process client references"))
......
...@@ -5,7 +5,7 @@ use turbopack_binding::turbopack::{ ...@@ -5,7 +5,7 @@ use turbopack_binding::turbopack::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkableModuleReference, ChunkingContext}, chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkableModuleReference, ChunkingContext},
ident::AssetIdent, ident::AssetIdent,
module::{Module, Modules}, module::Module,
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences},
resolve::ModuleResolveResult, resolve::ModuleResolveResult,
}, },
...@@ -20,13 +20,13 @@ use turbopack_binding::turbopack::{ ...@@ -20,13 +20,13 @@ use turbopack_binding::turbopack::{
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct IncludeModulesModule { pub struct IncludeModulesModule {
ident: Vc<AssetIdent>, ident: Vc<AssetIdent>,
modules: Vc<Modules>, modules: Vec<Vc<Box<dyn Module>>>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl IncludeModulesModule { impl IncludeModulesModule {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(ident: Vc<AssetIdent>, modules: Vc<Modules>) -> Vc<Self> { pub fn new(ident: Vc<AssetIdent>, modules: Vec<Vc<Box<dyn Module>>>) -> Vc<Self> {
Self { ident, modules }.cell() Self { ident, modules }.cell()
} }
} }
...@@ -48,7 +48,6 @@ impl Module for IncludeModulesModule { ...@@ -48,7 +48,6 @@ impl Module for IncludeModulesModule {
async fn references(&self) -> Result<Vc<ModuleReferences>> { async fn references(&self) -> Result<Vc<ModuleReferences>> {
Ok(Vc::cell( Ok(Vc::cell(
self.modules self.modules
.await?
.iter() .iter()
.map(|&module| async move { .map(|&module| async move {
Ok(Vc::upcast( Ok(Vc::upcast(
......
...@@ -16,9 +16,7 @@ use serde::{Deserialize, Serialize}; ...@@ -16,9 +16,7 @@ use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TaskInput}; use turbo_tasks::{trace::TraceRawVcs, TaskInput};
pub use crate::next_app::{ pub use crate::next_app::{
app_client_references_chunks::{ app_client_references_chunks::{get_app_client_references_chunks, ClientReferencesChunks},
get_app_client_references_chunks, ClientReferenceChunks, ClientReferencesChunks,
},
app_client_shared_chunks::get_app_client_shared_chunks, app_client_shared_chunks::get_app_client_shared_chunks,
app_entry::AppEntry, app_entry::AppEntry,
app_page_entry::get_app_page_entry, app_page_entry::get_app_page_entry,
......
...@@ -8,6 +8,6 @@ pub use ecmascript_client_reference::{ ...@@ -8,6 +8,6 @@ pub use ecmascript_client_reference::{
ecmascript_client_reference_transition::NextEcmascriptClientReferenceTransition, ecmascript_client_reference_transition::NextEcmascriptClientReferenceTransition,
}; };
pub use visit_client_reference::{ pub use visit_client_reference::{
ClientReference, ClientReferenceGraph, ClientReferenceType, ClientReferenceTypes, ClientReference, ClientReferenceGraph, ClientReferenceGraphResult, ClientReferenceType,
ClientReferences, ClientReferenceTypes,
}; };
...@@ -30,12 +30,12 @@ pub struct ClientReference { ...@@ -30,12 +30,12 @@ pub struct ClientReference {
} }
impl ClientReference { impl ClientReference {
pub fn server_component(&self) -> Option<&Vc<NextServerComponentModule>> { pub fn server_component(&self) -> Option<Vc<NextServerComponentModule>> {
self.server_component.as_ref() self.server_component
} }
pub fn ty(&self) -> &ClientReferenceType { pub fn ty(&self) -> ClientReferenceType {
&self.ty self.ty
} }
} }
...@@ -47,8 +47,11 @@ pub enum ClientReferenceType { ...@@ -47,8 +47,11 @@ pub enum ClientReferenceType {
CssClientReference(Vc<CssClientReferenceModule>), CssClientReference(Vc<CssClientReferenceModule>),
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value]
pub struct ClientReferences(Vec<ClientReference>); pub struct ClientReferenceGraphResult {
pub client_references: Vec<ClientReference>,
pub server_component_entries: Vec<Vc<NextServerComponentModule>>,
}
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct ClientReferenceTypes(IndexSet<ClientReferenceType>); pub struct ClientReferenceTypes(IndexSet<ClientReferenceType>);
...@@ -101,12 +104,13 @@ impl ClientReferenceGraph { ...@@ -101,12 +104,13 @@ impl ClientReferenceGraph {
for node in this.graph.reverse_topological() { for node in this.graph.reverse_topological() {
match &node.ty { match &node.ty {
VisitClientReferenceNodeType::Internal(_asset, _) => { VisitClientReferenceNodeType::Internal(..)
| VisitClientReferenceNodeType::ServerComponentEntry(..) => {
// No-op. These nodes are only useful during graph // No-op. These nodes are only useful during graph
// traversal. // traversal.
} }
VisitClientReferenceNodeType::ClientReference(client_reference, _) => { VisitClientReferenceNodeType::ClientReference(client_reference, _) => {
client_reference_types.insert(*client_reference.ty()); client_reference_types.insert(client_reference.ty());
} }
} }
} }
...@@ -115,9 +119,13 @@ impl ClientReferenceGraph { ...@@ -115,9 +119,13 @@ impl ClientReferenceGraph {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn entry(self: Vc<Self>, entry: Vc<Box<dyn Module>>) -> Result<Vc<ClientReferences>> { pub async fn entry(
self: Vc<Self>,
entry: Vc<Box<dyn Module>>,
) -> Result<Vc<ClientReferenceGraphResult>> {
let this = self.await?; let this = self.await?;
let mut entry_client_references = vec![]; let mut client_references = vec![];
let mut server_component_entries = vec![];
for node in this for node in this
.graph .graph
...@@ -132,12 +140,19 @@ impl ClientReferenceGraph { ...@@ -132,12 +140,19 @@ impl ClientReferenceGraph {
// traversal. // traversal.
} }
VisitClientReferenceNodeType::ClientReference(client_reference, _) => { VisitClientReferenceNodeType::ClientReference(client_reference, _) => {
entry_client_references.push(*client_reference); client_references.push(*client_reference);
}
VisitClientReferenceNodeType::ServerComponentEntry(server_component, _) => {
server_component_entries.push(*server_component);
} }
} }
} }
Ok(Vc::cell(entry_client_references)) Ok(ClientReferenceGraphResult {
client_references,
server_component_entries,
}
.cell())
} }
} }
...@@ -156,6 +171,7 @@ struct VisitClientReferenceNode { ...@@ -156,6 +171,7 @@ struct VisitClientReferenceNode {
)] )]
enum VisitClientReferenceNodeType { enum VisitClientReferenceNodeType {
ClientReference(ClientReference, ReadRef<String>), ClientReference(ClientReference, ReadRef<String>),
ServerComponentEntry(Vc<NextServerComponentModule>, ReadRef<String>),
Internal(Vc<Box<dyn Module>>, ReadRef<String>), Internal(Vc<Box<dyn Module>>, ReadRef<String>),
} }
...@@ -168,84 +184,85 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference { ...@@ -168,84 +184,85 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference {
match edge.ty { match edge.ty {
VisitClientReferenceNodeType::ClientReference(..) => VisitControlFlow::Skip(edge), VisitClientReferenceNodeType::ClientReference(..) => VisitControlFlow::Skip(edge),
VisitClientReferenceNodeType::Internal(..) => VisitControlFlow::Continue(edge), VisitClientReferenceNodeType::Internal(..) => VisitControlFlow::Continue(edge),
VisitClientReferenceNodeType::ServerComponentEntry(..) => {
VisitControlFlow::Continue(edge)
}
} }
} }
fn edges(&mut self, node: &VisitClientReferenceNode) -> Self::EdgesFuture { fn edges(&mut self, node: &VisitClientReferenceNode) -> Self::EdgesFuture {
let node = node.clone(); let node = node.clone();
async move { async move {
match node.ty { let module = match node.ty {
// This should never occur since we always skip visiting these // This should never occur since we always skip visiting these
// nodes' edges. // nodes' edges.
VisitClientReferenceNodeType::ClientReference(..) => Ok(vec![]), VisitClientReferenceNodeType::ClientReference(..) => return Ok(vec![]),
VisitClientReferenceNodeType::Internal(module, _) => { VisitClientReferenceNodeType::Internal(module, _) => module,
let referenced_modules = primary_referenced_modules(module).await?; VisitClientReferenceNodeType::ServerComponentEntry(module, _) => Vc::upcast(module),
};
let referenced_modules = referenced_modules.iter().map(|module| async move {
let module = module.resolve().await?; let referenced_modules = primary_referenced_modules(module).await?;
if let Some(client_reference_module) =
Vc::try_resolve_downcast_type::<EcmascriptClientReferenceModule>(module) let referenced_modules = referenced_modules.iter().map(|module| async move {
.await? let module = module.resolve().await?;
{ if let Some(client_reference_module) =
return Ok(VisitClientReferenceNode { Vc::try_resolve_downcast_type::<EcmascriptClientReferenceModule>(module).await?
{
return Ok(VisitClientReferenceNode {
server_component: node.server_component,
ty: VisitClientReferenceNodeType::ClientReference(
ClientReference {
server_component: node.server_component, server_component: node.server_component,
ty: VisitClientReferenceNodeType::ClientReference( ty: ClientReferenceType::EcmascriptClientReference(
ClientReference { client_reference_module,
server_component: node.server_component,
ty: ClientReferenceType::EcmascriptClientReference(
client_reference_module,
),
},
client_reference_module.ident().to_string().await?,
), ),
}); },
} client_reference_module.ident().to_string().await?,
),
if let Some(css_client_reference_asset) = });
Vc::try_resolve_downcast_type::<CssClientReferenceModule>(module) }
.await?
{ if let Some(css_client_reference_asset) =
return Ok(VisitClientReferenceNode { Vc::try_resolve_downcast_type::<CssClientReferenceModule>(module).await?
{
return Ok(VisitClientReferenceNode {
server_component: node.server_component,
ty: VisitClientReferenceNodeType::ClientReference(
ClientReference {
server_component: node.server_component, server_component: node.server_component,
ty: VisitClientReferenceNodeType::ClientReference( ty: ClientReferenceType::CssClientReference(
ClientReference { css_client_reference_asset,
server_component: node.server_component,
ty: ClientReferenceType::CssClientReference(
css_client_reference_asset,
),
},
css_client_reference_asset.ident().to_string().await?,
),
});
}
if let Some(server_component_asset) =
Vc::try_resolve_downcast_type::<NextServerComponentModule>(module)
.await?
{
return Ok(VisitClientReferenceNode {
server_component: Some(server_component_asset),
ty: VisitClientReferenceNodeType::Internal(
module,
module.ident().to_string().await?,
), ),
}); },
} css_client_reference_asset.ident().to_string().await?,
),
Ok(VisitClientReferenceNode {
server_component: node.server_component,
ty: VisitClientReferenceNodeType::Internal(
module,
module.ident().to_string().await?,
),
})
}); });
}
let assets = referenced_modules.try_join().await?; if let Some(server_component_asset) =
Vc::try_resolve_downcast_type::<NextServerComponentModule>(module).await?
Ok(assets) {
return Ok(VisitClientReferenceNode {
server_component: Some(server_component_asset),
ty: VisitClientReferenceNodeType::ServerComponentEntry(
server_component_asset,
server_component_asset.ident().to_string().await?,
),
});
} }
}
Ok(VisitClientReferenceNode {
server_component: node.server_component,
ty: VisitClientReferenceNodeType::Internal(
module,
module.ident().to_string().await?,
),
})
});
let assets = referenced_modules.try_join().await?;
Ok(assets)
} }
} }
...@@ -257,6 +274,9 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference { ...@@ -257,6 +274,9 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference {
VisitClientReferenceNodeType::Internal(_, name) => { VisitClientReferenceNodeType::Internal(_, name) => {
tracing::info_span!("module", name = **name) tracing::info_span!("module", name = **name)
} }
VisitClientReferenceNodeType::ServerComponentEntry(_, name) => {
tracing::info_span!("layout segment", name = **name)
}
} }
} }
} }
use anyhow::{Context, Result}; use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
...@@ -15,7 +15,7 @@ use turbopack_binding::turbopack::{ ...@@ -15,7 +15,7 @@ use turbopack_binding::turbopack::{
use super::{ClientReferenceManifest, ManifestNode, ManifestNodeEntry, ModuleId}; use super::{ClientReferenceManifest, ManifestNode, ManifestNodeEntry, ModuleId};
use crate::{ use crate::{
next_app::ClientReferencesChunks, next_app::ClientReferencesChunks,
next_client_reference::{ClientReferenceType, ClientReferences}, next_client_reference::{ClientReferenceGraphResult, ClientReferenceType},
util::NextRuntime, util::NextRuntime,
}; };
...@@ -26,7 +26,7 @@ impl ClientReferenceManifest { ...@@ -26,7 +26,7 @@ impl ClientReferenceManifest {
node_root: Vc<FileSystemPath>, node_root: Vc<FileSystemPath>,
client_relative_path: Vc<FileSystemPath>, client_relative_path: Vc<FileSystemPath>,
entry_name: String, entry_name: String,
client_references: Vc<ClientReferences>, client_references: Vc<ClientReferenceGraphResult>,
client_references_chunks: Vc<ClientReferencesChunks>, client_references_chunks: Vc<ClientReferencesChunks>,
client_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>, client_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
ssr_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>, ssr_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
...@@ -44,180 +44,154 @@ impl ClientReferenceManifest { ...@@ -44,180 +44,154 @@ impl ClientReferenceManifest {
let client_relative_path = client_relative_path.await?; let client_relative_path = client_relative_path.await?;
let node_root_ref = node_root.await?; let node_root_ref = node_root.await?;
for app_client_reference in client_references.await?.iter() { for app_client_reference in client_references.await?.client_references.iter() {
let app_client_reference_ty = app_client_reference.ty(); let app_client_reference_ty = app_client_reference.ty();
let app_client_reference_chunks = client_references_chunks // An client component need to be emitted into the client reference manifest
.get(app_client_reference.ty()) if let ClientReferenceType::EcmascriptClientReference(ecmascript_client_reference) =
.context("client reference chunks not found")?; app_client_reference_ty
{
let ecmascript_client_reference = ecmascript_client_reference.await?;
let client_reference_chunks = client_references_chunks let server_path = ecmascript_client_reference
.get(app_client_reference_ty) .server_ident
.context("client reference chunks not found")?; .path()
let client_chunks = &client_reference_chunks.client_chunks.await?;
let client_chunks_paths = client_chunks
.iter()
.map(|chunk| chunk.ident().path())
.try_join()
.await?;
if let Some(server_component) = app_client_reference.server_component() {
let server_component_name = server_component
.server_path()
.with_extension("".to_string())
.to_string() .to_string()
.await?; .await?;
let entry_css_files = entry_manifest let client_module_id = ecmascript_client_reference
.entry_css_files .client_module
.entry(server_component_name.clone_value()) .as_chunk_item(Vc::upcast(client_chunking_context))
.or_default(); .id()
.await?;
let entry_js_files = entry_manifest
.entry_js_files
.entry(server_component_name.clone_value())
.or_default();
match app_client_reference_ty {
ClientReferenceType::CssClientReference(_) => {
entry_css_files.extend(
client_chunks_paths
.iter()
.filter_map(|chunk_path| {
if chunk_path.extension_ref() == Some("css") {
client_relative_path.get_path_to(chunk_path)
} else {
None
}
})
.map(ToString::to_string),
);
entry_js_files.extend(
client_chunks_paths
.iter()
.filter_map(|chunk_path| {
if chunk_path.extension_ref() != Some("css") {
client_relative_path.get_path_to(chunk_path)
} else {
None
}
})
.map(ToString::to_string),
);
}
ClientReferenceType::EcmascriptClientReference(_) => {
// TODO should this be removed? does it make sense?
entry_css_files.extend(
client_chunks_paths
.iter()
.filter_map(|chunk_path| {
if chunk_path.extension_ref() == Some("css") {
client_relative_path.get_path_to(chunk_path)
} else {
None
}
})
.map(ToString::to_string),
);
}
}
}
match app_client_reference_ty {
ClientReferenceType::CssClientReference(_) => {}
ClientReferenceType::EcmascriptClientReference(ecmascript_client_reference) => {
let client_chunks = &app_client_reference_chunks.client_chunks.await?;
let ssr_chunks = &app_client_reference_chunks.ssr_chunks.await?;
let ecmascript_client_reference = ecmascript_client_reference.await?;
let client_module_id = ecmascript_client_reference
.client_module
.as_chunk_item(Vc::upcast(client_chunking_context))
.id()
.await?;
let ssr_module_id = ecmascript_client_reference
.ssr_module
.as_chunk_item(Vc::upcast(ssr_chunking_context))
.id()
.await?;
let server_path = ecmascript_client_reference
.server_ident
.path()
.to_string()
.await?;
let client_chunks_paths = if let Some(client_chunks) = client_references_chunks
.client_component_client_chunks
.get(&app_client_reference_ty)
{
let client_chunks = client_chunks.await?;
let client_chunks_paths = client_chunks let client_chunks_paths = client_chunks
.iter() .iter()
.map(|chunk| chunk.ident().path()) .map(|chunk| chunk.ident().path())
.try_join() .try_join()
.await?; .await?;
let client_chunks_paths: Vec<String> = client_chunks_paths
client_chunks_paths
.iter() .iter()
.filter_map(|chunk_path| client_relative_path.get_path_to(chunk_path)) .filter_map(|chunk_path| client_relative_path.get_path_to(chunk_path))
.map(ToString::to_string) .map(ToString::to_string)
// It's possible that a chunk also emits CSS files, that will // It's possible that a chunk also emits CSS files, that will
// be handled separatedly. // be handled separatedly.
.filter(|path| path.ends_with(".js")) .filter(|path| path.ends_with(".js"))
.collect::<Vec<_>>(); .collect::<Vec<_>>()
} else {
Vec::new()
};
entry_manifest.client_modules.module_exports.insert(
get_client_reference_module_key(&server_path, "*"),
ManifestNodeEntry {
name: "*".to_string(),
id: (&*client_module_id).into(),
chunks: client_chunks_paths,
// TODO(WEB-434)
r#async: false,
},
);
let ssr_module_id = ecmascript_client_reference
.ssr_module
.as_chunk_item(Vc::upcast(ssr_chunking_context))
.id()
.await?;
let ssr_chunks_paths = if runtime == NextRuntime::Edge {
// the chunks get added to the middleware-manifest.json instead
// of this file because the
// edge runtime doesn't support dynamically
// loading chunks.
Vec::new()
} else if let Some(ssr_chunks) = client_references_chunks
.client_component_ssr_chunks
.get(&app_client_reference_ty)
{
let ssr_chunks = ssr_chunks.await?;
let ssr_chunks_paths = ssr_chunks let ssr_chunks_paths = ssr_chunks
.iter() .iter()
.map(|chunk| chunk.ident().path()) .map(|chunk| chunk.ident().path())
.try_join() .try_join()
.await?; .await?;
let ssr_chunks_paths = ssr_chunks_paths
ssr_chunks_paths
.iter() .iter()
.filter_map(|chunk_path| node_root_ref.get_path_to(chunk_path)) .filter_map(|chunk_path| node_root_ref.get_path_to(chunk_path))
.map(ToString::to_string) .map(ToString::to_string)
.collect::<Vec<_>>(); .collect::<Vec<_>>()
} else {
Vec::new()
};
let mut ssr_manifest_node = ManifestNode::default();
ssr_manifest_node.module_exports.insert(
"*".to_string(),
ManifestNodeEntry {
name: "*".to_string(),
id: (&*ssr_module_id).into(),
chunks: ssr_chunks_paths,
// TODO(WEB-434)
r#async: false,
},
);
match runtime {
NextRuntime::NodeJs => {
entry_manifest
.ssr_module_mapping
.insert((&*client_module_id).into(), ssr_manifest_node);
}
NextRuntime::Edge => {
entry_manifest
.edge_ssr_module_mapping
.insert((&*client_module_id).into(), ssr_manifest_node);
}
}
}
}
let mut ssr_manifest_node = ManifestNode::default(); // per layout segment chunks need to be emitted into the manifest too
for (server_component, client_chunks) in
client_references_chunks.layout_segment_client_chunks.iter()
{
let client_chunks = &client_chunks.await?;
entry_manifest.client_modules.module_exports.insert( let client_chunks_paths = client_chunks
get_client_reference_module_key(&server_path, "*"), .iter()
ManifestNodeEntry { .map(|chunk| chunk.ident().path())
name: "*".to_string(), .try_join()
id: (&*client_module_id).into(), .await?;
chunks: client_chunks_paths.clone(),
// TODO(WEB-434)
r#async: false,
},
);
ssr_manifest_node.module_exports.insert( let server_component_name = server_component
"*".to_string(), .server_path()
ManifestNodeEntry { .with_extension("".to_string())
name: "*".to_string(), .to_string()
id: (&*ssr_module_id).into(), .await?;
chunks: if runtime == NextRuntime::Edge {
// the chunks get added to the middleware-manifest.json instead of
// this file because the edge runtime doesn't support dynamically
// loading chunks.
vec![]
} else {
ssr_chunks_paths.clone()
},
// TODO(WEB-434)
r#async: false,
},
);
match runtime { let entry_css_files = entry_manifest
NextRuntime::NodeJs => { .entry_css_files
entry_manifest .entry(server_component_name.clone_value())
.ssr_module_mapping .or_default();
.insert((&*client_module_id).into(), ssr_manifest_node.clone());
} let entry_js_files = entry_manifest
NextRuntime::Edge => { .entry_js_files
entry_manifest .entry(server_component_name.clone_value())
.edge_ssr_module_mapping .or_default();
.insert((&*client_module_id).into(), ssr_manifest_node);
} for chunk_path in client_chunks_paths {
if let Some(path) = client_relative_path.get_path_to(&chunk_path) {
let path = path.to_string();
if chunk_path.extension_ref() == Some("css") {
entry_css_files.insert(path);
} else {
entry_js_files.insert(path);
} }
} }
} }
......
...@@ -4,6 +4,7 @@ pub(crate) mod client_reference_manifest; ...@@ -4,6 +4,7 @@ pub(crate) mod client_reference_manifest;
use std::collections::HashMap; use std::collections::HashMap;
use indexmap::IndexSet;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TaskInput}; use turbo_tasks::{trace::TraceRawVcs, TaskInput};
...@@ -236,10 +237,10 @@ pub struct ClientReferenceManifest { ...@@ -236,10 +237,10 @@ pub struct ClientReferenceManifest {
pub edge_ssr_module_mapping: HashMap<ModuleId, ManifestNode>, pub edge_ssr_module_mapping: HashMap<ModuleId, ManifestNode>,
/// Mapping of server component path to required CSS client chunks. /// Mapping of server component path to required CSS client chunks.
#[serde(rename = "entryCSSFiles")] #[serde(rename = "entryCSSFiles")]
pub entry_css_files: HashMap<String, Vec<String>>, pub entry_css_files: HashMap<String, IndexSet<String>>,
/// Mapping of server component path to required JS client chunks. /// Mapping of server component path to required JS client chunks.
#[serde(rename = "entryJSFiles")] #[serde(rename = "entryJSFiles")]
pub entry_js_files: HashMap<String, Vec<String>>, pub entry_js_files: HashMap<String, IndexSet<String>>,
} }
#[derive(Serialize, Default, Debug)] #[derive(Serialize, Default, Debug)]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment