Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
261 changes: 198 additions & 63 deletions crates/next-api/src/app.rs

Large diffs are not rendered by default.

85 changes: 52 additions & 33 deletions crates/next-api/src/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use smallvec::smallvec;
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Completion, FxIndexMap, ReadRef, ResolvedVc, ValueToString, Vc, fxindexmap, fxindexset,
Completion, FxIndexMap, OrderedAutoMap, ReadRef, ResolvedVc, ValueToString, Vc, fxindexset,
};
use turbo_tasks_fs::{
self, File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem,
Expand Down Expand Up @@ -88,7 +88,7 @@ use crate::{
project::Project,
route::{
AnalyzeChunkGroup, AnalyzeChunkGroups, AnalyzeClientEntries, Endpoint, EndpointOutput,
EndpointOutputPaths, ModuleGraphs, Route, Routes,
EndpointOutputPaths, FirstLoadChunks, ModuleGraphs, Route, Routes,
},
service_worker::service_worker_output_assets,
sri_manifest::get_sri_manifest_asset,
Expand Down Expand Up @@ -119,15 +119,15 @@ impl PagesProject {
has_user_pages: _,
should_create_pages_entries,
} = &*pages_structure.await?;
let mut routes = FxIndexMap::default();
let mut routes = OrderedAutoMap::default();

// If pages entries shouldn't be created (build mode with no pages), return empty routes
if !should_create_pages_entries {
return Ok(Vc::cell(routes));
}

async fn add_page_to_routes(
routes: &mut FxIndexMap<RcStr, Route>,
routes: &mut OrderedAutoMap<RcStr, Route>,
page: Vc<PagesStructureItem>,
make_route: impl Fn(
RcStr,
Expand All @@ -148,7 +148,7 @@ impl PagesProject {
}

async fn add_dir_to_routes(
routes: &mut FxIndexMap<RcStr, Route>,
routes: &mut OrderedAutoMap<RcStr, Route>,
dir: Vc<PagesDirectoryStructure>,
make_route: impl Fn(
RcStr,
Expand Down Expand Up @@ -471,7 +471,7 @@ impl PagesProject {
self.project().encryption_key(),
self.project().server_compile_time_info().environment(),
self.project().client_compile_time_info().environment(),
*self.project().should_write_nft_manifests().await?,
*self.project().should_trace().await?,
self.project().server_source_map_generation_options(),
))
}
Expand Down Expand Up @@ -510,7 +510,7 @@ impl PagesProject {
self.project().encryption_key(),
self.project().server_compile_time_info().environment(),
self.project().client_compile_time_info().environment(),
*self.project().should_write_nft_manifests().await?,
*self.project().should_trace().await?,
self.project().server_source_map_generation_options(),
))
}
Expand Down Expand Up @@ -669,7 +669,7 @@ async fn client_entry_modules(
async fn page_next_dynamic_chunks(
endpoint: Vc<PageEndpoint>,
next_dynamic_imports: ReadRef<DynamicImportEntriesWithImporter>,
client_availability_info: AvailabilityInfo,
client_chunk_group: &ChunkGroupResult,
) -> Result<ResolvedVc<DynamicImportedChunks>> {
let this = endpoint.await?;
let project = this.pages_project.project();
Expand All @@ -680,15 +680,15 @@ async fn page_next_dynamic_chunks(
endpoint.client_module_graph(),
client_chunking_context,
next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
NextDynamicChunkAvailability::PagesRouterClientEntry(client_chunk_group),
)
.await;
}

// `/_app`'s `next/dynamic` imports are loaded by `/_app`'s async loaders, which are chunked
// with `/_app`'s graph and availability, so preload them with the chunks `/_app` itself
// lists. Chunked with the page's availability, they would name chunks that don't match what
// those loaders request (and that may not be emitted at all).
// with `/_app`'s graph and chunk group, so preload them with the chunks `/_app` itself
// lists. The page's chunk group sees `/_app`'s chunk group as available and doesn't create
// those loaders itself.
// With a per-page module graph, a page's client graph is chained after `/_app`'s (see
// `client_module_graph`), so `next_dynamic_imports` also contains `/_app`'s imports: chunk
// only the page's own imports with the page's graph and availability. With a whole-app graph
Expand All @@ -700,31 +700,35 @@ async fn page_next_dynamic_chunks(
.get_next_dynamic_imports_for_endpoint(app_endpoint.client_module())
.await?;
let app_dynamic_entries = app_next_dynamic_imports
.entries
.iter()
.map(|(dynamic_entry, _)| *dynamic_entry)
.map(|import| import.dynamic_entry)
.collect::<FxHashSet<_>>();
let page_next_dynamic_imports = Vc::<DynamicImportEntriesWithImporter>::cell(
next_dynamic_imports
let page_next_dynamic_imports = DynamicImportEntriesWithImporter {
entries: next_dynamic_imports
.entries
.iter()
.filter(|(dynamic_entry, _)| !app_dynamic_entries.contains(dynamic_entry))
.filter(|import| !app_dynamic_entries.contains(&import.dynamic_entry))
.cloned()
.collect(),
)
async_modules: next_dynamic_imports.async_modules.clone(),
}
.cell()
.await?;

let page_chunks = collect_next_dynamic_chunks(
endpoint.client_module_graph(),
client_chunking_context,
page_next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
NextDynamicChunkAvailability::PagesRouterClientEntry(client_chunk_group),
)
.await?;
let app_chunks = collect_next_dynamic_chunks(
app_module_graph,
client_chunking_context,
app_next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(
app_endpoint.client_chunk_group().await?.availability_info,
NextDynamicChunkAvailability::PagesRouterClientEntry(
&*app_endpoint.client_chunk_group().await?,
),
)
.await?;
Expand Down Expand Up @@ -971,6 +975,7 @@ impl PageEndpoint {
ChunkGroupKey::Entry(evaluatable_assets),
module_graph,
OutputAssets::empty(),
None,
availability_info,
);

Expand Down Expand Up @@ -1119,7 +1124,7 @@ impl PageEndpoint {
let ssr_module_graph = self.ssr_module_graph();

let next_dynamic_imports = if let PageEndpointType::Html = this.ty {
let client_availability_info = self.client_chunk_group().await?.availability_info;
let client_chunk_group = self.client_chunk_group().await?;

let client_module_graph = self.client_module_graph();
let per_page_module_graph = *project.per_page_module_graph().await?;
Expand All @@ -1140,18 +1145,15 @@ impl PageEndpoint {
NextDynamicGraphs::new(client_module_graph, per_page_module_graph)
.get_next_dynamic_imports_for_endpoint(self.client_module())
.await?;
Some((next_dynamic_imports, client_availability_info))
Some((next_dynamic_imports, client_chunk_group))
} else {
None
};

let dynamic_import_entries = if let Some((
next_dynamic_imports,
client_availability_info,
)) = next_dynamic_imports
let dynamic_import_entries = if let Some((next_dynamic_imports, client_chunk_group)) =
next_dynamic_imports
{
page_next_dynamic_chunks(self, next_dynamic_imports, client_availability_info)
.await?
page_next_dynamic_chunks(self, next_dynamic_imports, &client_chunk_group).await?
} else {
DynamicImportedChunks::default().resolved_cell()
};
Expand Down Expand Up @@ -1421,14 +1423,14 @@ impl PageEndpoint {
let (pages, pages_chunk_group_bootstrap_params) =
if pages_structure.should_create_pages_entries {
(
fxindexmap!(self.pathname.clone() => client_chunks),
OrderedAutoMap::from_iter([(self.pathname.clone(), client_chunks)]),
chunk_group_bootstrap_params
.map(|params| fxindexmap!(self.pathname.clone() => params))
.map(|params| OrderedAutoMap::from_iter([(self.pathname.clone(), params)]))
.unwrap_or_default(),
)
} else {
// Empty when no user pages should be created
(fxindexmap![], fxindexmap![])
(OrderedAutoMap::default(), OrderedAutoMap::default())
};

let chunk_loading_global = (*self
Expand Down Expand Up @@ -1474,9 +1476,9 @@ impl PageEndpoint {
// Check if we should include pages in the manifest
let pages_structure = self.pages_structure.await?;
let pages = if pages_structure.should_create_pages_entries {
fxindexmap!(self.pathname.clone() => page_loader)
OrderedAutoMap::from_iter([(self.pathname.clone(), page_loader)])
} else {
fxindexmap![] // Empty pages when no user pages should be created
OrderedAutoMap::default() // Empty pages when no user pages should be created
};

let manifest_path_prefix = get_asset_prefix_from_pathname(&self.pathname);
Expand Down Expand Up @@ -1905,11 +1907,28 @@ impl Endpoint for PageEndpoint {
},
};

// Only needed for the route bundle stats of production builds: the chunks listed for
// this page in its `build-manifest.json`.
let first_load_chunks = if this.ty == PageEndpointType::Html
&& project.next_mode().await?.is_production()
{
Some(FirstLoadChunks::PagesPage(
if this.pages_structure.await?.should_create_pages_entries {
self.client_chunk_group().await?.assets
} else {
OutputAssets::empty_resolved()
},
))
} else {
None
};

anyhow::Ok(
EndpointOutput {
output_assets: output_assets.to_resolved().await?,
output_paths: written_endpoint.resolved_cell(),
project: project.to_resolved().await?,
first_load_chunks,
}
.cell(),
)
Expand Down
45 changes: 28 additions & 17 deletions crates/next-api/src/server_actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,16 @@ use swc_core::{
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, OperationVc, ReadRef, ResolvedVc, TryFlatJoinIterExt,
TryJoinIterExt, ValueToStringRef, Vc, turbofmt,
FxIndexMap, FxIndexSet, NonLocalValue, OperationVc, OrderedAutoMap, ReadRef, ResolvedVc,
TryFlatJoinIterExt, TryJoinIterExt, ValueToStringRef, Vc, turbofmt,
};
use turbo_tasks_fs::{self, File, FileContent, FileSystemPath, rope::RopeBuilder};
use turbo_tasks_hash::{HashAlgorithm, deterministic_hash};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{
ChunkGroupResult, ChunkItem, ChunkItemExt, ChunkableModule, ChunkingConfigs,
ChunkingContext, EntryChunkGroupResult, EvaluatableAsset, HmrChunkListSource, MinifyType,
ChunkingContext, EmitOptions, EntryChunkGroupResult, EvaluatableAsset, HmrChunkListSource,
ModuleId, SourceMapSourceType, UnusedReferences, UrlBehavior, WorkerConfigurationOptions,
availability_info::AvailabilityInfo, chunk_id_strategy::ModuleIdStrategy,
},
Expand All @@ -58,9 +58,11 @@ use turbopack_core::{
source_map::{OptionSourceMapType, SourceMapGenerationOptions},
virtual_source::VirtualSource,
};
use turbopack_css::emit_options::CssEmitOptions;
use turbopack_ecmascript::{
EcmascriptAnalyzable, EcmascriptParsable, EnvVarAccessMode, EnvVarInfo,
chunk::{EcmascriptChunkItem, EcmascriptChunkItemExt, EcmascriptChunkPlaceable},
emit_options::EcmascriptEmitOptions,
module_fragments::part::module::EcmascriptModulePartAsset,
parse::ParseResult,
};
Expand Down Expand Up @@ -915,11 +917,10 @@ async fn parse_actions(module: ResolvedVc<Box<dyn Module>>) -> Result<Vc<OptionA
actions.retain(|_, entry| all_exports.iter().any(|export| export == &entry.name));
}

let mut actions = FxIndexMap::from_iter(actions.into_iter());
actions.sort_keys();
// `actions` is a `BTreeMap`, so this is sorted by the action hash.
Ok(Vc::cell(Some(
ActionMap {
actions,
actions: actions.into(),
entry_path,
entry_query,
}
Expand Down Expand Up @@ -1039,8 +1040,7 @@ impl AllActions {
#[turbo_tasks::value]
#[derive(Debug)]
pub struct ActionMap {
#[bincode(with = "turbo_bincode::indexmap")]
pub actions: FxIndexMap<String, ActionEntry>,
pub actions: OrderedAutoMap<String, ActionEntry>,
pub entry_path: String,
pub entry_query: String,
}
Expand All @@ -1052,10 +1052,7 @@ struct OptionActionMap(Option<ResolvedVc<ActionMap>>);
type LayerAndActions = (ActionLayer, ResolvedVc<ActionMap>);
/// A mapping of every module module containing Server Actions, mapping to its layer and actions.
#[turbo_tasks::value(transparent)]
pub struct AllModuleActions(
#[bincode(with = "turbo_bincode::indexmap")]
FxIndexMap<ResolvedVc<Box<dyn Module>>, LayerAndActions>,
);
pub struct AllModuleActions(OrderedAutoMap<ResolvedVc<Box<dyn Module>>, LayerAndActions>);

#[turbo_tasks::function]
pub async fn map_server_actions(
Expand Down Expand Up @@ -1257,11 +1254,24 @@ impl ChunkingContext for UseCacheContentHashChunkingContext {
}

#[turbo_tasks::function]
pub fn minify_type(&self) -> Vc<MinifyType> {
// Intentionally override: we are not performing chunking, so minify_type is only used for
// generating less whitespace during AST emitting (which means less data and thus slightly
// faster)
MinifyType::default().cell()
fn emit_options(&self) -> Vc<EmitOptions> {
// Intentionally override: we are not performing chunking, so emit options are only used
// for generating less whitespace during AST emitting (which means less data and thus
// slightly faster)
Vc::cell(vec![
ResolvedVc::upcast(
EcmascriptEmitOptions::builder()
.preset_minify_optimal_size()
.build()
.resolved_cell(),
),
ResolvedVc::upcast(
CssEmitOptions::builder()
.preset_minify()
.build()
.resolved_cell(),
),
])
}

#[turbo_tasks::function]
Expand Down Expand Up @@ -1290,6 +1300,7 @@ impl ChunkingContext for UseCacheContentHashChunkingContext {
_chunk_group: ChunkGroupKey,
_module_graph: ResolvedVc<ModuleGraph>,
_extra_chunks: Vc<OutputAssets>,
_hmr_ident: Option<Vc<AssetIdent>>,
_input_availability_info: AvailabilityInfo,
) -> Result<Vc<ChunkGroupResult>> {
bail!("evaluated_chunk_group should not be called in UseCacheContentHashChunkingContext");
Expand Down
7 changes: 4 additions & 3 deletions crates/next-core/src/next_app/app_client_shared_chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use turbopack_core::{
#[turbo_tasks::function]
pub async fn get_app_client_shared_chunk_group(
ident: Vc<AssetIdent>,
hmr_ident: Vc<AssetIdent>,
app_client_runtime_entries: Vc<EvaluatableAssets>,
module_graph: Vc<ModuleGraph>,
client_chunking_context: Vc<Box<dyn ChunkingContext>>,
Expand All @@ -34,10 +35,10 @@ pub async fn get_app_client_shared_chunk_group(
.collect(),
),
module_graph,
// The shared chunk group must stay shared across pages; page-specific HMR
// chunks (e.g. client references) are routed through a separate page-specific
// evaluated chunk group instead.
// The evaluated chunk group stays shared across pages, while the HMR chunk list
// is page-specific because it can contain route-specific dynamic chunks.
OutputAssets::empty(),
Some(hmr_ident),
AvailabilityInfo::root(),
)
.to_resolved()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use client'

import { useState } from 'react'

export function CounterA() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>Counter A: {count}</button>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { ReactNode } from 'react'

export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { version } from 'react'

export function init() {
document.documentElement.dataset.lazyModuleLoaded = version
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use client'

import { useState } from 'react'

export function CounterB() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>Counter B: {count}</button>
}
Loading