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::{
get_client_module_options_context, get_client_resolve_options_context,
get_client_runtime_entries, ClientContextType, RuntimeEntries,
},
next_client_reference::{
ClientReferenceGraph, ClientReferenceType, NextEcmascriptClientReferenceTransition,
},
next_client_reference::{ClientReferenceGraph, NextEcmascriptClientReferenceTransition},
next_dynamic::NextDynamicTransition,
next_edge::route_regex::get_named_middleware_regex,
next_manifests::{
......@@ -611,10 +609,6 @@ impl AppEndpoint {
// ))
// .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();
if ssr_and_client {
......@@ -626,8 +620,7 @@ impl AppEndpoint {
};
let client_references_chunks = get_app_client_references_chunks(
app_entry.rsc_entry.ident(),
client_reference_types,
client_references,
this.app_project.project().client_chunking_context(),
ssr_chunking_context,
);
......@@ -636,13 +629,23 @@ impl AppEndpoint {
let mut entry_client_chunks = IndexSet::new();
// TODO(alexkirsz) In which manifest does this go?
let mut entry_ssr_chunks = IndexSet::new();
for client_reference in app_entry_client_references.iter() {
let client_reference_chunks = client_references_chunks_ref
.get(client_reference.ty())
.context("client reference should have corresponding chunks")?;
entry_client_chunks
.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
.layout_segment_client_chunks
.values()
{
entry_client_chunks.extend(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());
......@@ -718,12 +721,13 @@ impl AppEndpoint {
// initialization
let client_references_chunks = &*client_references_chunks.await?;
for (ty, chunks) in client_references_chunks {
if matches!(ty, ClientReferenceType::EcmascriptClientReference(..)) {
let ssr_chunks = &*chunks.ssr_chunks.await?;
for &ssr_chunks in client_references_chunks
.client_component_ssr_chunks
.values()
{
let ssr_chunks = ssr_chunks.await?;
middleware_assets.extend(ssr_chunks);
}
middleware_assets.extend(ssr_chunks);
}
}
}
......
use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use tracing::Instrument;
use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, TryFlatJoinIterExt, TryJoinIterExt, Vc,
};
use turbo_tasks::{TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc};
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,
};
use super::include_modules_module::IncludeModulesModule;
use crate::next_client_reference::{ClientReferenceType, ClientReferenceTypes};
/// Contains the chunks corresponding to a client reference.
#[derive(
Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat,
)]
pub struct ClientReferenceChunks {
/// Chunks to be loaded on the client.
pub client_chunks: Vc<OutputAssets>,
/// Chunks to be loaded on the server for SSR.
pub ssr_chunks: Vc<OutputAssets>,
use crate::{
next_client_reference::{
visit_client_reference::ClientReferenceGraphResult, ClientReferenceType,
ClientReferenceTypes,
},
next_server_component::server_component_module::NextServerComponentModule,
};
#[turbo_tasks::function]
fn client_modules_modifier() -> Vc<String> {
Vc::cell("client modules".to_string())
}
#[turbo_tasks::value(transparent)]
pub struct ClientReferencesChunks(IndexMap<ClientReferenceType, ClientReferenceChunks>);
#[turbo_tasks::function]
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.
///
......@@ -33,115 +43,231 @@ pub struct ClientReferencesChunks(IndexMap<ClientReferenceType, ClientReferenceC
/// type needs to load.
#[turbo_tasks::function]
pub async fn get_app_client_references_chunks(
base_ident: Vc<AssetIdent>,
app_client_reference_types: Vc<ClientReferenceTypes>,
app_client_references: Vc<ClientReferenceGraphResult>,
client_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
ssr_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
) -> Result<Vc<ClientReferencesChunks>> {
async move {
// TODO Reconsider this. Maybe it need to be true in production.
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 {
let app_client_references_chunks: IndexMap<_, _> = app_client_reference_types
let app_client_references_chunks: Vec<(_, (_, Option<_>))> = app_client_references
.client_references
.iter()
.map(|client_reference_ty| async move {
.map(|client_reference| async move {
let client_reference_ty = client_reference.ty();
Ok((
*client_reference_ty,
client_reference_ty,
match client_reference_ty {
ClientReferenceType::EcmascriptClientReference(
ecmascript_client_reference,
) => {
let ecmascript_client_reference_ref =
ecmascript_client_reference.await?;
ClientReferenceChunks {
client_chunks: client_chunking_context.root_chunk_group_assets(
Vc::upcast(ecmascript_client_reference_ref.client_module),
),
ssr_chunks: ssr_chunking_context.root_chunk_group_assets(
Vc::upcast(ecmascript_client_reference_ref.ssr_module),
),
}
(
client_chunking_context.root_chunk_group_assets(Vc::upcast(
ecmascript_client_reference_ref.client_module,
)),
Some(ssr_chunking_context.root_chunk_group_assets(Vc::upcast(
ecmascript_client_reference_ref.ssr_module,
))),
)
}
ClientReferenceType::CssClientReference(css_client_reference) => {
let css_client_reference_ref = css_client_reference.await?;
ClientReferenceChunks {
client_chunks: client_chunking_context.root_chunk_group_assets(
Vc::upcast(css_client_reference_ref.client_module),
),
ssr_chunks: OutputAssets::empty(),
}
(
client_chunking_context.root_chunk_group_assets(Vc::upcast(
css_client_reference_ref.client_module,
)),
None,
)
}
},
))
})
.try_join()
.await?
.into_iter()
.collect();
.await?;
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 {
let ssr_modules = app_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,
let mut client_references_by_server_component: IndexMap<_, Vec<_>> = IndexMap::new();
let mut framework_reference_types = Vec::new();
for &server_component in app_client_references.server_component_entries.iter() {
client_references_by_server_component
.entry(server_component)
.or_default();
}
for client_reference in app_client_references.client_references.iter() {
if let Some(server_component) = client_reference.server_component() {
client_references_by_server_component
.entry(server_component)
.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()
.await?;
let ssr_entry_module = IncludeModulesModule::new(
base_ident.with_modifier(Vc::cell("client modules ssr".to_string())),
Vc::cell(ssr_modules),
);
let client_modules = app_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)
.try_flat_join()
.await?;
let ssr_chunk_group = if !ssr_modules.is_empty() {
let ssr_entry_module = IncludeModulesModule::new(
base_ident.with_modifier(client_modules_ssr_modifier()),
ssr_modules,
);
let _span = tracing::info_span!(
"server side rendering",
layout_segment = display(&server_component_path),
)
.entered();
Some(ssr_chunking_context.chunk_group(
Vc::upcast(ssr_entry_module),
Value::new(current_ssr_availability_info),
))
} 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"))
......
......@@ -5,7 +5,7 @@ use turbopack_binding::turbopack::{
asset::{Asset, AssetContent},
chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkableModuleReference, ChunkingContext},
ident::AssetIdent,
module::{Module, Modules},
module::Module,
reference::{ModuleReference, ModuleReferences},
resolve::ModuleResolveResult,
},
......@@ -20,13 +20,13 @@ use turbopack_binding::turbopack::{
#[turbo_tasks::value]
pub struct IncludeModulesModule {
ident: Vc<AssetIdent>,
modules: Vc<Modules>,
modules: Vec<Vc<Box<dyn Module>>>,
}
#[turbo_tasks::value_impl]
impl IncludeModulesModule {
#[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()
}
}
......@@ -48,7 +48,6 @@ impl Module for IncludeModulesModule {
async fn references(&self) -> Result<Vc<ModuleReferences>> {
Ok(Vc::cell(
self.modules
.await?
.iter()
.map(|&module| async move {
Ok(Vc::upcast(
......
......@@ -16,9 +16,7 @@ use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TaskInput};
pub use crate::next_app::{
app_client_references_chunks::{
get_app_client_references_chunks, ClientReferenceChunks, ClientReferencesChunks,
},
app_client_references_chunks::{get_app_client_references_chunks, ClientReferencesChunks},
app_client_shared_chunks::get_app_client_shared_chunks,
app_entry::AppEntry,
app_page_entry::get_app_page_entry,
......
......@@ -8,6 +8,6 @@ pub use ecmascript_client_reference::{
ecmascript_client_reference_transition::NextEcmascriptClientReferenceTransition,
};
pub use visit_client_reference::{
ClientReference, ClientReferenceGraph, ClientReferenceType, ClientReferenceTypes,
ClientReferences,
ClientReference, ClientReferenceGraph, ClientReferenceGraphResult, ClientReferenceType,
ClientReferenceTypes,
};
......@@ -30,12 +30,12 @@ pub struct ClientReference {
}
impl ClientReference {
pub fn server_component(&self) -> Option<&Vc<NextServerComponentModule>> {
self.server_component.as_ref()
pub fn server_component(&self) -> Option<Vc<NextServerComponentModule>> {
self.server_component
}
pub fn ty(&self) -> &ClientReferenceType {
&self.ty
pub fn ty(&self) -> ClientReferenceType {
self.ty
}
}
......@@ -47,8 +47,11 @@ pub enum ClientReferenceType {
CssClientReference(Vc<CssClientReferenceModule>),
}
#[turbo_tasks::value(transparent)]
pub struct ClientReferences(Vec<ClientReference>);
#[turbo_tasks::value]
pub struct ClientReferenceGraphResult {
pub client_references: Vec<ClientReference>,
pub server_component_entries: Vec<Vc<NextServerComponentModule>>,
}
#[turbo_tasks::value(transparent)]
pub struct ClientReferenceTypes(IndexSet<ClientReferenceType>);
......@@ -101,12 +104,13 @@ impl ClientReferenceGraph {
for node in this.graph.reverse_topological() {
match &node.ty {
VisitClientReferenceNodeType::Internal(_asset, _) => {
VisitClientReferenceNodeType::Internal(..)
| VisitClientReferenceNodeType::ServerComponentEntry(..) => {
// No-op. These nodes are only useful during graph
// traversal.
}
VisitClientReferenceNodeType::ClientReference(client_reference, _) => {
client_reference_types.insert(*client_reference.ty());
client_reference_types.insert(client_reference.ty());
}
}
}
......@@ -115,9 +119,13 @@ impl ClientReferenceGraph {
}
#[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 mut entry_client_references = vec![];
let mut client_references = vec![];
let mut server_component_entries = vec![];
for node in this
.graph
......@@ -132,12 +140,19 @@ impl ClientReferenceGraph {
// traversal.
}
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 {
)]
enum VisitClientReferenceNodeType {
ClientReference(ClientReference, ReadRef<String>),
ServerComponentEntry(Vc<NextServerComponentModule>, ReadRef<String>),
Internal(Vc<Box<dyn Module>>, ReadRef<String>),
}
......@@ -168,84 +184,85 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference {
match edge.ty {
VisitClientReferenceNodeType::ClientReference(..) => VisitControlFlow::Skip(edge),
VisitClientReferenceNodeType::Internal(..) => VisitControlFlow::Continue(edge),
VisitClientReferenceNodeType::ServerComponentEntry(..) => {
VisitControlFlow::Continue(edge)
}
}
}
fn edges(&mut self, node: &VisitClientReferenceNode) -> Self::EdgesFuture {
let node = node.clone();
async move {
match node.ty {
let module = match node.ty {
// This should never occur since we always skip visiting these
// nodes' edges.
VisitClientReferenceNodeType::ClientReference(..) => Ok(vec![]),
VisitClientReferenceNodeType::Internal(module, _) => {
let referenced_modules = primary_referenced_modules(module).await?;
let referenced_modules = referenced_modules.iter().map(|module| async move {
let module = module.resolve().await?;
if let Some(client_reference_module) =
Vc::try_resolve_downcast_type::<EcmascriptClientReferenceModule>(module)
.await?
{
return Ok(VisitClientReferenceNode {
VisitClientReferenceNodeType::ClientReference(..) => return Ok(vec![]),
VisitClientReferenceNodeType::Internal(module, _) => module,
VisitClientReferenceNodeType::ServerComponentEntry(module, _) => Vc::upcast(module),
};
let referenced_modules = primary_referenced_modules(module).await?;
let referenced_modules = referenced_modules.iter().map(|module| async move {
let module = module.resolve().await?;
if let Some(client_reference_module) =
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,
ty: VisitClientReferenceNodeType::ClientReference(
ClientReference {
server_component: node.server_component,
ty: ClientReferenceType::EcmascriptClientReference(
client_reference_module,
),
},
client_reference_module.ident().to_string().await?,
ty: ClientReferenceType::EcmascriptClientReference(
client_reference_module,
),
});
}
if let Some(css_client_reference_asset) =
Vc::try_resolve_downcast_type::<CssClientReferenceModule>(module)
.await?
{
return Ok(VisitClientReferenceNode {
},
client_reference_module.ident().to_string().await?,
),
});
}
if let Some(css_client_reference_asset) =
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,
ty: VisitClientReferenceNodeType::ClientReference(
ClientReference {
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?,
ty: ClientReferenceType::CssClientReference(
css_client_reference_asset,
),
});
}
Ok(VisitClientReferenceNode {
server_component: node.server_component,
ty: VisitClientReferenceNodeType::Internal(
module,
module.ident().to_string().await?,
),
})
},
css_client_reference_asset.ident().to_string().await?,
),
});
}
let assets = referenced_modules.try_join().await?;
Ok(assets)
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::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 {
VisitClientReferenceNodeType::Internal(_, 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 turbo_tasks::{TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::{File, FileSystemPath};
......@@ -15,7 +15,7 @@ use turbopack_binding::turbopack::{
use super::{ClientReferenceManifest, ManifestNode, ManifestNodeEntry, ModuleId};
use crate::{
next_app::ClientReferencesChunks,
next_client_reference::{ClientReferenceType, ClientReferences},
next_client_reference::{ClientReferenceGraphResult, ClientReferenceType},
util::NextRuntime,
};
......@@ -26,7 +26,7 @@ impl ClientReferenceManifest {
node_root: Vc<FileSystemPath>,
client_relative_path: Vc<FileSystemPath>,
entry_name: String,
client_references: Vc<ClientReferences>,
client_references: Vc<ClientReferenceGraphResult>,
client_references_chunks: Vc<ClientReferencesChunks>,
client_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
ssr_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
......@@ -44,180 +44,154 @@ impl ClientReferenceManifest {
let client_relative_path = client_relative_path.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_chunks = client_references_chunks
.get(app_client_reference.ty())
.context("client reference chunks not found")?;
// An client component need to be emitted into the client reference manifest
if let ClientReferenceType::EcmascriptClientReference(ecmascript_client_reference) =
app_client_reference_ty
{
let ecmascript_client_reference = ecmascript_client_reference.await?;
let client_reference_chunks = client_references_chunks
.get(app_client_reference_ty)
.context("client reference chunks not found")?;
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())
let server_path = ecmascript_client_reference
.server_ident
.path()
.to_string()
.await?;
let entry_css_files = entry_manifest
.entry_css_files
.entry(server_component_name.clone_value())
.or_default();
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_module_id = ecmascript_client_reference
.client_module
.as_chunk_item(Vc::upcast(client_chunking_context))
.id()
.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
.iter()
.map(|chunk| chunk.ident().path())
.try_join()
.await?;
let client_chunks_paths: Vec<String> = client_chunks_paths
client_chunks_paths
.iter()
.filter_map(|chunk_path| client_relative_path.get_path_to(chunk_path))
.map(ToString::to_string)
// It's possible that a chunk also emits CSS files, that will
// be handled separatedly.
.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
.iter()
.map(|chunk| chunk.ident().path())
.try_join()
.await?;
let ssr_chunks_paths = ssr_chunks_paths
ssr_chunks_paths
.iter()
.filter_map(|chunk_path| node_root_ref.get_path_to(chunk_path))
.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(
get_client_reference_module_key(&server_path, "*"),
ManifestNodeEntry {
name: "*".to_string(),
id: (&*client_module_id).into(),
chunks: client_chunks_paths.clone(),
// TODO(WEB-434)
r#async: false,
},
);
let client_chunks_paths = client_chunks
.iter()
.map(|chunk| chunk.ident().path())
.try_join()
.await?;
ssr_manifest_node.module_exports.insert(
"*".to_string(),
ManifestNodeEntry {
name: "*".to_string(),
id: (&*ssr_module_id).into(),
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,
},
);
let server_component_name = server_component
.server_path()
.with_extension("".to_string())
.to_string()
.await?;
match runtime {
NextRuntime::NodeJs => {
entry_manifest
.ssr_module_mapping
.insert((&*client_module_id).into(), ssr_manifest_node.clone());
}
NextRuntime::Edge => {
entry_manifest
.edge_ssr_module_mapping
.insert((&*client_module_id).into(), ssr_manifest_node);
}
let entry_css_files = entry_manifest
.entry_css_files
.entry(server_component_name.clone_value())
.or_default();
let entry_js_files = entry_manifest
.entry_js_files
.entry(server_component_name.clone_value())
.or_default();
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;
use std::collections::HashMap;
use indexmap::IndexSet;
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TaskInput};
......@@ -236,10 +237,10 @@ pub struct ClientReferenceManifest {
pub edge_ssr_module_mapping: HashMap<ModuleId, ManifestNode>,
/// Mapping of server component path to required CSS client chunks.
#[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.
#[serde(rename = "entryJSFiles")]
pub entry_js_files: HashMap<String, Vec<String>>,
pub entry_js_files: HashMap<String, IndexSet<String>>,
}
#[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