Unverified Commit 09bdc452 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: improve incremental build performance when deployment id changes (#84460)

### What?

* avoid dependencies due to tracing
* Avoid invalidating client chunking context when chunk_suffix_path changes
* BrowserChunkingContext::chunk_path only depends on a selected subset of fields
* select cross_origin field instead of depending on the whole config
* select NextConfig::output field instead of depending on the whole config
* make all next config fields private to ensure using selector functions
parent f8816b06
...@@ -157,14 +157,14 @@ impl MiddlewareEndpoint { ...@@ -157,14 +157,14 @@ impl MiddlewareEndpoint {
parse_segment_config_from_source(*self.await?.source, ParseSegmentMode::Base).await?; parse_segment_config_from_source(*self.await?.source, ParseSegmentMode::Base).await?;
let runtime = config.runtime.unwrap_or(NextRuntime::Edge); let runtime = config.runtime.unwrap_or(NextRuntime::Edge);
let next_config = this.project.next_config().await?; let next_config = this.project.next_config();
let has_i18n = next_config.i18n.is_some(); let i18n = next_config.i18n().await?;
let has_i18n_locales = next_config let has_i18n = i18n.is_some();
.i18n let has_i18n_locales = i18n
.as_ref() .as_ref()
.map(|i18n| i18n.locales.len() > 1) .map(|i18n| i18n.locales.len() > 1)
.unwrap_or(false); .unwrap_or(false);
let base_path = next_config.base_path.as_ref(); let base_path = next_config.base_path().await?;
let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() { let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() {
matchers matchers
...@@ -202,7 +202,7 @@ impl MiddlewareEndpoint { ...@@ -202,7 +202,7 @@ impl MiddlewareEndpoint {
source.insert_str(0, "/:nextData(_next/data/[^/]{1,})?"); source.insert_str(0, "/:nextData(_next/data/[^/]{1,})?");
if let Some(base_path) = base_path { if let Some(base_path) = base_path.as_ref() {
source.insert_str(0, base_path); source.insert_str(0, base_path);
} }
......
...@@ -408,7 +408,9 @@ pub async fn all_assets_from_entries_filtered( ...@@ -408,7 +408,9 @@ pub async fn all_assets_from_entries_filtered(
Ok(( Ok((
*asset, *asset,
if emit_spans { if emit_spans {
Some(asset.path().to_string().await?) // INVALIDATION: we don't need to invalidate the list of assets when
// the span name changes
Some(asset.path_string().untracked().await?)
} else { } else {
None None
}, },
...@@ -498,7 +500,9 @@ async fn get_referenced_server_assets( ...@@ -498,7 +500,9 @@ async fn get_referenced_server_assets(
Ok(Some(( Ok(Some((
*asset, *asset,
if emit_spans { if emit_spans {
Some(asset.path().to_string().await?) // INVALIDATION: we don't need to invalidate the list of assets when the span
// name changes
Some(asset.path_string().untracked().await?)
} else { } else {
None None
}, },
......
...@@ -479,8 +479,8 @@ impl ProjectContainer { ...@@ -479,8 +479,8 @@ impl ProjectContainer {
} }
let dist_dir = next_config let dist_dir = next_config
.dist_dir()
.await? .await?
.dist_dir
.as_ref() .as_ref()
.map_or_else(|| rcstr!(".next"), |d| d.clone()); .map_or_else(|| rcstr!(".next"), |d| d.clone());
...@@ -722,13 +722,17 @@ impl Project { ...@@ -722,13 +722,17 @@ impl Project {
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn client_relative_path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> { pub async fn client_relative_path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> {
let next_config = self.next_config().await?; let next_config = self.next_config();
Ok(self Ok(self
.client_root() .client_root()
.await? .await?
.join(&format!( .join(&format!(
"{}/_next", "{}/_next",
next_config.base_path.clone().unwrap_or_default(), next_config
.base_path()
.await?
.as_deref()
.unwrap_or_default(),
))? ))?
.cell()) .cell())
} }
...@@ -1156,26 +1160,38 @@ impl Project { ...@@ -1156,26 +1160,38 @@ impl Project {
*config.persistent_caching_enabled().await?, *config.persistent_caching_enabled().await?,
); );
let config = &config.await?; emit_event(
"modularizeImports",
emit_event("modularizeImports", config.modularize_imports.is_some()); !config.modularize_imports().await?.is_empty(),
emit_event("transpilePackages", config.transpile_packages.is_some()); );
emit_event(
"transpilePackages",
!config.transpile_packages().await?.is_empty(),
);
emit_event("turbotrace", false); emit_event("turbotrace", false);
// compiler options // compiler options
let compiler_options = config.compiler.as_ref(); let compiler_options = config.compiler().await?;
let swc_relay_enabled = compiler_options.and_then(|c| c.relay.as_ref()).is_some(); let swc_relay_enabled = compiler_options.relay.is_some();
let styled_components_enabled = compiler_options let styled_components_enabled = compiler_options
.and_then(|c| c.styled_components.as_ref().map(|sc| sc.is_enabled())) .styled_components
.as_ref()
.map(|sc| sc.is_enabled())
.unwrap_or_default(); .unwrap_or_default();
let react_remove_properties_enabled = compiler_options let react_remove_properties_enabled = compiler_options
.and_then(|c| c.react_remove_properties.as_ref().map(|rc| rc.is_enabled())) .react_remove_properties
.as_ref()
.map(|rc| rc.is_enabled())
.unwrap_or_default(); .unwrap_or_default();
let remove_console_enabled = compiler_options let remove_console_enabled = compiler_options
.and_then(|c| c.remove_console.as_ref().map(|rc| rc.is_enabled())) .remove_console
.as_ref()
.map(|rc| rc.is_enabled())
.unwrap_or_default(); .unwrap_or_default();
let emotion_enabled = compiler_options let emotion_enabled = compiler_options
.and_then(|c| c.emotion.as_ref().map(|e| e.is_enabled())) .emotion
.as_ref()
.map(|e| e.is_enabled())
.unwrap_or_default(); .unwrap_or_default();
emit_event("swcRelay", swc_relay_enabled); emit_event("swcRelay", swc_relay_enabled);
......
...@@ -2,7 +2,7 @@ use anyhow::Result; ...@@ -2,7 +2,7 @@ use anyhow::Result;
use tracing::{Instrument, Level, Span}; use tracing::{Instrument, Level, Span};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc, FxIndexSet, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc,
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow}, graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
}; };
use turbo_tasks_fs::{FileSystemPath, rebase}; use turbo_tasks_fs::{FileSystemPath, rebase};
...@@ -161,7 +161,9 @@ pub async fn all_assets_from_entries(entries: Vc<OutputAssets>) -> Result<Vc<Out ...@@ -161,7 +161,9 @@ pub async fn all_assets_from_entries(entries: Vc<OutputAssets>) -> Result<Vc<Out
Ok(( Ok((
*asset, *asset,
if emit_spans { if emit_spans {
Some(asset.path().to_string().await?) // INVALIDATION: we don't need to invalidate when the span name
// changes
Some(asset.path_string().untracked().await?)
} else { } else {
None None
}, },
...@@ -195,7 +197,9 @@ async fn get_referenced_assets( ...@@ -195,7 +197,9 @@ async fn get_referenced_assets(
Ok(( Ok((
*asset, *asset,
if emit_spans { if emit_spans {
Some(asset.path().to_string().await?) // INVALIDATION: we don't need to invalidate the list of assets when the span
// name changes
Some(asset.path_string().untracked().await?)
} else { } else {
None None
}, },
......
...@@ -48,7 +48,7 @@ pub async fn get_app_page_entry( ...@@ -48,7 +48,7 @@ pub async fn get_app_page_entry(
let server_component_transition = let server_component_transition =
ResolvedVc::upcast(NextServerComponentTransition::new().to_resolved().await?); ResolvedVc::upcast(NextServerComponentTransition::new().to_resolved().await?);
let base_path = next_config.await?.base_path.clone(); let base_path = next_config.base_path().owned().await?;
let loader_tree = AppPageLoaderTreeModule::build( let loader_tree = AppPageLoaderTreeModule::build(
loader_tree, loader_tree,
module_asset_context, module_asset_context,
......
...@@ -60,8 +60,8 @@ pub async fn get_app_route_entry( ...@@ -60,8 +60,8 @@ pub async fn get_app_route_entry(
let inner = rcstr!("INNER_APP_ROUTE"); let inner = rcstr!("INNER_APP_ROUTE");
let output_type: &str = next_config let output_type: &str = next_config
.output()
.await? .await?
.output
.as_ref() .as_ref()
.map(|o| match o { .map(|o| match o {
OutputType::Standalone => "\"standalone\"", OutputType::Standalone => "\"standalone\"",
......
...@@ -447,7 +447,7 @@ pub async fn get_client_chunking_context( ...@@ -447,7 +447,7 @@ pub async fn get_client_chunking_context(
let next_mode = mode.await?; let next_mode = mode.await?;
let asset_prefix = asset_prefix.owned().await?; let asset_prefix = asset_prefix.owned().await?;
let chunk_suffix_path = chunk_suffix_path.owned().await?; let chunk_suffix_path = chunk_suffix_path.to_resolved().await?;
let mut builder = BrowserChunkingContext::builder( let mut builder = BrowserChunkingContext::builder(
root_path, root_path,
client_root.clone(), client_root.clone(),
......
...@@ -3,10 +3,10 @@ use std::future::Future; ...@@ -3,10 +3,10 @@ use std::future::Future;
use anyhow::Result; use anyhow::Result;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::{Instrument, Level, Span};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TryJoinIterExt, ValueToString, Vc, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TryJoinIterExt, Vc,
debug::ValueDebugFormat, debug::ValueDebugFormat,
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow}, graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
trace::TraceRawVcs, trace::TraceRawVcs,
...@@ -121,14 +121,23 @@ pub async fn find_server_entries( ...@@ -121,14 +121,23 @@ pub async fn find_server_entries(
include_traced: bool, include_traced: bool,
) -> Result<Vc<ServerEntries>> { ) -> Result<Vc<ServerEntries>> {
async move { async move {
let emit_spans = tracing::enabled!(Level::INFO);
let graph = AdjacencyMap::new() let graph = AdjacencyMap::new()
.skip_duplicates() .skip_duplicates()
.visit( .visit(
vec![FindServerEntriesNode::Internal( vec![FindServerEntriesNode::Internal(
entry, entry,
entry.ident().to_string().await?, if emit_spans {
// INVALIDATION: we don't need to invalidate when the span name changes
Some(entry.ident_string().untracked().await?)
} else {
None
},
)], )],
FindServerEntries { include_traced }, FindServerEntries {
include_traced,
emit_spans,
},
) )
.await .await
.completed()? .completed()?
...@@ -161,6 +170,7 @@ pub async fn find_server_entries( ...@@ -161,6 +170,7 @@ pub async fn find_server_entries(
struct FindServerEntries { struct FindServerEntries {
/// Whether to walk ChunkingType::Traced references /// Whether to walk ChunkingType::Traced references
include_traced: bool, include_traced: bool,
emit_spans: bool,
} }
#[derive( #[derive(
...@@ -177,9 +187,12 @@ struct FindServerEntries { ...@@ -177,9 +187,12 @@ struct FindServerEntries {
)] )]
enum FindServerEntriesNode { enum FindServerEntriesNode {
ClientReference, ClientReference,
ServerComponentEntry(ResolvedVc<NextServerComponentModule>, ReadRef<RcStr>), ServerComponentEntry(
ServerUtilEntry(ResolvedVc<NextServerUtilityModule>, ReadRef<RcStr>), ResolvedVc<NextServerComponentModule>,
Internal(ResolvedVc<Box<dyn Module>>, ReadRef<RcStr>), Option<ReadRef<RcStr>>,
),
ServerUtilEntry(ResolvedVc<NextServerUtilityModule>, Option<ReadRef<RcStr>>),
Internal(ResolvedVc<Box<dyn Module>>, Option<ReadRef<RcStr>>),
} }
impl Visit<FindServerEntriesNode> for FindServerEntries { impl Visit<FindServerEntriesNode> for FindServerEntries {
...@@ -208,6 +221,7 @@ impl Visit<FindServerEntriesNode> for FindServerEntries { ...@@ -208,6 +221,7 @@ impl Visit<FindServerEntriesNode> for FindServerEntries {
FindServerEntriesNode::ServerUtilEntry(module, _) => Vc::upcast(**module), FindServerEntriesNode::ServerUtilEntry(module, _) => Vc::upcast(**module),
FindServerEntriesNode::ServerComponentEntry(module, _) => Vc::upcast(**module), FindServerEntriesNode::ServerComponentEntry(module, _) => Vc::upcast(**module),
}; };
let emit_spans = self.emit_spans;
async move { async move {
// Pass include_traced to reuse the same cached `primary_chunkable_referenced_modules` // Pass include_traced to reuse the same cached `primary_chunkable_referenced_modules`
// task result, but the traced references will be filtered out again afterwards. // task result, but the traced references will be filtered out again afterwards.
...@@ -235,7 +249,13 @@ impl Visit<FindServerEntriesNode> for FindServerEntries { ...@@ -235,7 +249,13 @@ impl Visit<FindServerEntriesNode> for FindServerEntries {
{ {
return Ok(FindServerEntriesNode::ServerComponentEntry( return Ok(FindServerEntriesNode::ServerComponentEntry(
server_component_asset, server_component_asset,
server_component_asset.ident().to_string().await?, if emit_spans {
// INVALIDATION: we don't need to invalidate when the span name
// changes
Some(server_component_asset.ident_string().untracked().await?)
} else {
None
},
)); ));
} }
...@@ -244,13 +264,24 @@ impl Visit<FindServerEntriesNode> for FindServerEntries { ...@@ -244,13 +264,24 @@ impl Visit<FindServerEntriesNode> for FindServerEntries {
{ {
return Ok(FindServerEntriesNode::ServerUtilEntry( return Ok(FindServerEntriesNode::ServerUtilEntry(
server_util_module, server_util_module,
module.ident().to_string().await?, if emit_spans {
// INVALIDATION: we don't need to invalidate when the span name
// changes
Some(module.ident_string().untracked().await?)
} else {
None
},
)); ));
} }
Ok(FindServerEntriesNode::Internal( Ok(FindServerEntriesNode::Internal(
*module, *module,
module.ident().to_string().await?, if emit_spans {
// INVALIDATION: we don't need to invalidate when the span name changes
Some(module.ident_string().untracked().await?)
} else {
None
},
)) ))
}); });
...@@ -261,18 +292,21 @@ impl Visit<FindServerEntriesNode> for FindServerEntries { ...@@ -261,18 +292,21 @@ impl Visit<FindServerEntriesNode> for FindServerEntries {
} }
fn span(&mut self, node: &FindServerEntriesNode) -> tracing::Span { fn span(&mut self, node: &FindServerEntriesNode) -> tracing::Span {
if !self.emit_spans {
return Span::current();
}
match node { match node {
FindServerEntriesNode::ClientReference => { FindServerEntriesNode::ClientReference => {
tracing::info_span!("client reference") tracing::info_span!("client reference")
} }
FindServerEntriesNode::Internal(_, name) => { FindServerEntriesNode::Internal(_, name) => {
tracing::info_span!("module", name = display(name)) tracing::info_span!("module", name = display(name.as_ref().unwrap()))
} }
FindServerEntriesNode::ServerUtilEntry(_, name) => { FindServerEntriesNode::ServerUtilEntry(_, name) => {
tracing::info_span!("server util", name = display(name)) tracing::info_span!("server util", name = display(name.as_ref().unwrap()))
} }
FindServerEntriesNode::ServerComponentEntry(_, name) => { FindServerEntriesNode::ServerComponentEntry(_, name) => {
tracing::info_span!("layout segment", name = display(name)) tracing::info_span!("layout segment", name = display(name.as_ref().unwrap()))
} }
} }
} }
......
...@@ -75,40 +75,40 @@ impl Default for CacheKinds { ...@@ -75,40 +75,40 @@ impl Default for CacheKinds {
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
#[serde(default, rename_all = "camelCase")] #[serde(default, rename_all = "camelCase")]
pub struct NextConfig { pub struct NextConfig {
// TODO all fields should be private and access should be wrapped within a turbo-tasks function // IMPORTANT: all fields should be private and access should be wrapped within a turbo-tasks
// Otherwise changing NextConfig will lead to invalidating all tasks accessing it. // function. Otherwise changing NextConfig will lead to invalidating all tasks accessing it.
pub config_file: Option<RcStr>, config_file: Option<RcStr>,
pub config_file_name: RcStr, config_file_name: RcStr,
/// In-memory cache size in bytes. /// In-memory cache size in bytes.
/// ///
/// If `cache_max_memory_size: 0` disables in-memory caching. /// If `cache_max_memory_size: 0` disables in-memory caching.
pub cache_max_memory_size: Option<f64>, cache_max_memory_size: Option<f64>,
/// custom path to a cache handler to use /// custom path to a cache handler to use
pub cache_handler: Option<RcStr>, cache_handler: Option<RcStr>,
pub env: FxIndexMap<String, JsonValue>, env: FxIndexMap<String, JsonValue>,
pub experimental: ExperimentalConfig, experimental: ExperimentalConfig,
pub images: ImageConfig, images: ImageConfig,
pub page_extensions: Vec<RcStr>, page_extensions: Vec<RcStr>,
pub react_compiler: Option<ReactCompilerOptionsOrBoolean>, react_compiler: Option<ReactCompilerOptionsOrBoolean>,
pub react_production_profiling: Option<bool>, react_production_profiling: Option<bool>,
pub react_strict_mode: Option<bool>, react_strict_mode: Option<bool>,
pub transpile_packages: Option<Vec<RcStr>>, transpile_packages: Option<Vec<RcStr>>,
pub modularize_imports: Option<FxIndexMap<String, ModularizeImportPackageConfig>>, modularize_imports: Option<FxIndexMap<String, ModularizeImportPackageConfig>>,
pub dist_dir: Option<RcStr>, dist_dir: Option<RcStr>,
pub deployment_id: Option<RcStr>, deployment_id: Option<RcStr>,
sass_options: Option<serde_json::Value>, sass_options: Option<serde_json::Value>,
pub trailing_slash: Option<bool>, trailing_slash: Option<bool>,
pub asset_prefix: Option<RcStr>, asset_prefix: Option<RcStr>,
pub base_path: Option<RcStr>, base_path: Option<RcStr>,
pub skip_middleware_url_normalize: Option<bool>, skip_middleware_url_normalize: Option<bool>,
pub skip_trailing_slash_redirect: Option<bool>, skip_trailing_slash_redirect: Option<bool>,
pub i18n: Option<I18NConfig>, i18n: Option<I18NConfig>,
pub cross_origin: Option<CrossOriginConfig>, cross_origin: Option<CrossOriginConfig>,
pub dev_indicators: Option<DevIndicatorsConfig>, dev_indicators: Option<DevIndicatorsConfig>,
pub output: Option<OutputType>, output: Option<OutputType>,
pub turbopack: Option<TurbopackConfig>, turbopack: Option<TurbopackConfig>,
production_browser_source_maps: bool, production_browser_source_maps: bool,
output_file_tracing_includes: Option<serde_json::Value>, output_file_tracing_includes: Option<serde_json::Value>,
output_file_tracing_excludes: Option<serde_json::Value>, output_file_tracing_excludes: Option<serde_json::Value>,
...@@ -119,21 +119,21 @@ pub struct NextConfig { ...@@ -119,21 +119,21 @@ pub struct NextConfig {
/// server-side bundles. /// server-side bundles.
/// ///
/// [API Reference](https://nextjs.org/docs/pages/api-reference/next-config-js/bundlePagesRouterDependencies) /// [API Reference](https://nextjs.org/docs/pages/api-reference/next-config-js/bundlePagesRouterDependencies)
pub bundle_pages_router_dependencies: Option<bool>, bundle_pages_router_dependencies: Option<bool>,
/// A list of packages that should be treated as external on the server /// A list of packages that should be treated as external on the server
/// build. /// build.
/// ///
/// [API Reference](https://nextjs.org/docs/app/api-reference/next-config-js/serverExternalPackages) /// [API Reference](https://nextjs.org/docs/app/api-reference/next-config-js/serverExternalPackages)
pub server_external_packages: Option<Vec<RcStr>>, server_external_packages: Option<Vec<RcStr>>,
#[serde(rename = "_originalRedirects")] #[serde(rename = "_originalRedirects")]
pub original_redirects: Option<Vec<Redirect>>, original_redirects: Option<Vec<Redirect>>,
// Partially supported // Partially supported
pub compiler: Option<CompilerConfig>, compiler: Option<CompilerConfig>,
pub optimize_fonts: Option<bool>, optimize_fonts: Option<bool>,
clean_dist_dir: bool, clean_dist_dir: bool,
compress: bool, compress: bool,
...@@ -157,7 +157,7 @@ pub struct NextConfig { ...@@ -157,7 +157,7 @@ pub struct NextConfig {
} }
#[derive( #[derive(
Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
)] )]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum CrossOriginConfig { pub enum CrossOriginConfig {
...@@ -165,6 +165,9 @@ pub enum CrossOriginConfig { ...@@ -165,6 +165,9 @@ pub enum CrossOriginConfig {
UseCredentials, UseCredentials,
} }
#[turbo_tasks::value(transparent)]
pub struct OptionCrossOriginConfig(Option<CrossOriginConfig>);
#[derive( #[derive(
Clone, Clone,
Debug, Debug,
...@@ -262,7 +265,7 @@ struct HttpAgentConfig { ...@@ -262,7 +265,7 @@ struct HttpAgentConfig {
} }
#[derive( #[derive(
Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
)] )]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct DomainLocale { pub struct DomainLocale {
...@@ -273,7 +276,7 @@ pub struct DomainLocale { ...@@ -273,7 +276,7 @@ pub struct DomainLocale {
} }
#[derive( #[derive(
Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
)] )]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct I18NConfig { pub struct I18NConfig {
...@@ -283,8 +286,11 @@ pub struct I18NConfig { ...@@ -283,8 +286,11 @@ pub struct I18NConfig {
pub locales: Vec<String>, pub locales: Vec<String>,
} }
#[turbo_tasks::value(transparent)]
pub struct OptionI18NConfig(Option<I18NConfig>);
#[derive( #[derive(
Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
)] )]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum OutputType { pub enum OutputType {
...@@ -292,6 +298,9 @@ pub enum OutputType { ...@@ -292,6 +298,9 @@ pub enum OutputType {
Export, Export,
} }
#[turbo_tasks::value(transparent)]
pub struct OptionOutputType(Option<OutputType>);
#[derive( #[derive(
Debug, Debug,
Clone, Clone,
...@@ -1330,6 +1339,11 @@ impl NextConfig { ...@@ -1330,6 +1339,11 @@ impl NextConfig {
Vc::cell(self.output == Some(OutputType::Standalone)) Vc::cell(self.output == Some(OutputType::Standalone))
} }
#[turbo_tasks::function]
pub fn base_path(&self) -> Vc<Option<RcStr>> {
Vc::cell(self.base_path.clone())
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn cache_handler(&self, project_path: FileSystemPath) -> Result<Vc<OptionFileSystemPath>> { pub fn cache_handler(&self, project_path: FileSystemPath) -> Result<Vc<OptionFileSystemPath>> {
if let Some(handler) = &self.cache_handler { if let Some(handler) = &self.cache_handler {
...@@ -1531,6 +1545,11 @@ impl NextConfig { ...@@ -1531,6 +1545,11 @@ impl NextConfig {
})) }))
} }
#[turbo_tasks::function]
pub fn inline_css(&self) -> Vc<bool> {
Vc::cell(self.experimental.inline_css.unwrap_or(false))
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn mdx_rs(&self) -> Vc<OptionalMdxTransformOptions> { pub fn mdx_rs(&self) -> Vc<OptionalMdxTransformOptions> {
let options = &self.experimental.mdx_rs; let options = &self.experimental.mdx_rs;
...@@ -1566,6 +1585,11 @@ impl NextConfig { ...@@ -1566,6 +1585,11 @@ impl NextConfig {
Vc::cell(self.modularize_imports.clone().unwrap_or_default()) Vc::cell(self.modularize_imports.clone().unwrap_or_default())
} }
#[turbo_tasks::function]
pub fn dist_dir(&self) -> Vc<Option<RcStr>> {
Vc::cell(self.dist_dir.clone())
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn experimental_cache_handlers( pub fn experimental_cache_handlers(
&self, &self,
...@@ -1857,6 +1881,21 @@ impl NextConfig { ...@@ -1857,6 +1881,21 @@ impl NextConfig {
)) ))
} }
#[turbo_tasks::function]
pub fn cross_origin(&self) -> Vc<OptionCrossOriginConfig> {
Vc::cell(self.cross_origin.clone())
}
#[turbo_tasks::function]
pub fn i18n(&self) -> Vc<OptionI18NConfig> {
Vc::cell(self.i18n.clone())
}
#[turbo_tasks::function]
pub fn output(&self) -> Vc<OptionOutputType> {
Vc::cell(self.output.clone())
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn output_file_tracing_includes(&self) -> Vc<OptionJsonValue> { pub fn output_file_tracing_includes(&self) -> Vc<OptionJsonValue> {
Vc::cell(self.output_file_tracing_includes.clone()) Vc::cell(self.output_file_tracing_includes.clone())
......
...@@ -175,11 +175,7 @@ async fn build_manifest( ...@@ -175,11 +175,7 @@ async fn build_manifest(
// TODO: Add `suffix` to the manifest for React to use. // TODO: Add `suffix` to the manifest for React to use.
// entry_manifest.module_loading.prefix = prefix_path; // entry_manifest.module_loading.prefix = prefix_path;
entry_manifest.module_loading.cross_origin = next_config entry_manifest.module_loading.cross_origin = next_config.cross_origin().owned().await?;
.await?
.cross_origin
.as_ref()
.map(|p| p.to_owned());
let ClientReferencesChunks { let ClientReferencesChunks {
client_component_client_chunks, client_component_client_chunks,
layout_segment_client_chunks, layout_segment_client_chunks,
...@@ -442,8 +438,7 @@ async fn build_manifest( ...@@ -442,8 +438,7 @@ async fn build_manifest(
cached_chunk_paths(&mut client_chunk_path_cache, client_chunks.iter().copied()) cached_chunk_paths(&mut client_chunk_path_cache, client_chunks.iter().copied())
.await?; .await?;
// Inlining breaks HMR so it is always disabled in dev. // Inlining breaks HMR so it is always disabled in dev.
let inlined_css = let inlined_css = *next_config.inline_css().await? && mode.is_production();
next_config.await?.experimental.inline_css.unwrap_or(false) && mode.is_production();
for (chunk, chunk_path) in client_chunks_with_path { for (chunk, chunk_path) in client_chunks_with_path {
if let Some(path) = client_relative_path.get_path_to(&chunk_path) { if let Some(path) = client_relative_path.get_path_to(&chunk_path) {
......
...@@ -125,8 +125,8 @@ impl BrowserChunkingContextBuilder { ...@@ -125,8 +125,8 @@ impl BrowserChunkingContextBuilder {
self self
} }
pub fn chunk_suffix_path(mut self, chunk_suffix_path: Option<RcStr>) -> Self { pub fn chunk_suffix_path(mut self, chunk_suffix_path: ResolvedVc<Option<RcStr>>) -> Self {
self.chunking_context.chunk_suffix_path = chunk_suffix_path; self.chunking_context.chunk_suffix_path = Some(chunk_suffix_path);
self self
} }
...@@ -222,7 +222,7 @@ pub struct BrowserChunkingContext { ...@@ -222,7 +222,7 @@ pub struct BrowserChunkingContext {
chunk_base_path: Option<RcStr>, chunk_base_path: Option<RcStr>,
/// Suffix path that will be appended to all chunk URLs when loading them. /// Suffix path that will be appended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data. /// This path will not appear in chunk paths or chunk data.
chunk_suffix_path: Option<RcStr>, chunk_suffix_path: Option<ResolvedVc<Option<RcStr>>>,
/// URL prefix that will be prepended to all static asset URLs when loading /// URL prefix that will be prepended to all static asset URLs when loading
/// them. /// them.
asset_base_path: Option<RcStr>, asset_base_path: Option<RcStr>,
...@@ -381,7 +381,11 @@ impl BrowserChunkingContext { ...@@ -381,7 +381,11 @@ impl BrowserChunkingContext {
/// Returns the asset suffix path. /// Returns the asset suffix path.
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn chunk_suffix_path(&self) -> Vc<Option<RcStr>> { pub fn chunk_suffix_path(&self) -> Vc<Option<RcStr>> {
Vc::cell(self.chunk_suffix_path.clone()) if let Some(chunk_suffix_path) = self.chunk_suffix_path {
*chunk_suffix_path
} else {
Vc::cell(None)
}
} }
/// Returns the source map type. /// Returns the source map type.
...@@ -395,6 +399,17 @@ impl BrowserChunkingContext { ...@@ -395,6 +399,17 @@ impl BrowserChunkingContext {
pub fn minify_type(&self) -> Vc<MinifyType> { pub fn minify_type(&self) -> Vc<MinifyType> {
self.minify_type.cell() self.minify_type.cell()
} }
/// Returns the chunk path information.
#[turbo_tasks::function]
fn chunk_path_info(&self) -> Vc<ChunkPathInfo> {
ChunkPathInfo {
root_path: self.root_path.clone(),
chunk_root_path: self.chunk_root_path.clone(),
content_hashing: self.content_hashing,
}
.cell()
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -435,7 +450,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -435,7 +450,7 @@ impl ChunkingContext for BrowserChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn chunk_path( async fn chunk_path(
&self, self: Vc<Self>,
asset: Option<Vc<Box<dyn Asset>>>, asset: Option<Vc<Box<dyn Asset>>>,
ident: Vc<AssetIdent>, ident: Vc<AssetIdent>,
prefix: Option<RcStr>, prefix: Option<RcStr>,
...@@ -445,11 +460,15 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -445,11 +460,15 @@ impl ChunkingContext for BrowserChunkingContext {
extension.starts_with("."), extension.starts_with("."),
"`extension` should include the leading '.', got '{extension}'" "`extension` should include the leading '.', got '{extension}'"
); );
let root_path = self.chunk_root_path.clone(); let ChunkPathInfo {
let name = match self.content_hashing { chunk_root_path,
content_hashing,
root_path,
} = &*self.chunk_path_info().await?;
let name = match *content_hashing {
None => { None => {
ident ident
.output_name(self.root_path.clone(), prefix, extension) .output_name(root_path.clone(), prefix, extension)
.owned() .owned()
.await? .await?
} }
...@@ -474,7 +493,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -474,7 +493,7 @@ impl ChunkingContext for BrowserChunkingContext {
} }
} }
}; };
Ok(root_path.join(&name)?.cell()) Ok(chunk_root_path.join(&name)?.cell())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -794,3 +813,10 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -794,3 +813,10 @@ impl ChunkingContext for BrowserChunkingContext {
Ok(Vc::cell(self.await?.debug_ids)) Ok(Vc::cell(self.await?.debug_ids))
} }
} }
#[turbo_tasks::value]
struct ChunkPathInfo {
root_path: FileSystemPath,
chunk_root_path: FileSystemPath,
content_hashing: Option<ContentHashing>,
}
use turbo_tasks::{ResolvedVc, TaskInput, Vc}; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, TaskInput, ValueToString, Vc};
use crate::{asset::Asset, ident::AssetIdent, reference::ModuleReferences}; use crate::{asset::Asset, ident::AssetIdent, reference::ModuleReferences};
...@@ -18,6 +19,13 @@ pub trait Module: Asset { ...@@ -18,6 +19,13 @@ pub trait Module: Asset {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ident(&self) -> Vc<AssetIdent>; fn ident(&self) -> Vc<AssetIdent>;
/// The identifier of the [Module] as string. It's expected to be unique and capture
/// all properties of the [Module].
#[turbo_tasks::function]
fn ident_string(self: Vc<Self>) -> Vc<RcStr> {
self.ident().to_string()
}
/// Other [Module]s or [OutputAsset]s referenced from this [Module]. /// Other [Module]s or [OutputAsset]s referenced from this [Module].
// TODO refactor to avoid returning [OutputAsset]s here // TODO refactor to avoid returning [OutputAsset]s here
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -1702,7 +1702,8 @@ impl SingleModuleGraphBuilderNode { ...@@ -1702,7 +1702,8 @@ impl SingleModuleGraphBuilderNode {
Ok(Self::Module { Ok(Self::Module {
module, module,
ident: if emit_spans { ident: if emit_spans {
Some(ident.to_string().await?) // INVALIDATION: we don't need to invalidate when the span name changes
Some(ident.to_string().untracked().await?)
} else { } else {
None None
}, },
...@@ -1718,13 +1719,15 @@ impl SingleModuleGraphBuilderNode { ...@@ -1718,13 +1719,15 @@ impl SingleModuleGraphBuilderNode {
ref_data, ref_data,
source, source,
source_ident: if emit_spans { source_ident: if emit_spans {
Some(source.ident().to_string().await?) // INVALIDATION: we don't need to invalidate when the span name changes
Some(source.ident_string().untracked().await?)
} else { } else {
None None
}, },
target, target,
target_ident: if emit_spans { target_ident: if emit_spans {
Some(target.ident().to_string().await?) // INVALIDATION: we don't need to invalidate when the span name changes
Some(target.ident_string().untracked().await?)
} else { } else {
None None
}, },
......
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{FxIndexSet, ResolvedVc, Vc}; use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexSet, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use crate::asset::Asset; use crate::asset::Asset;
...@@ -16,6 +17,13 @@ pub trait OutputAsset: Asset { ...@@ -16,6 +17,13 @@ pub trait OutputAsset: Asset {
#[turbo_tasks::function] #[turbo_tasks::function]
fn path(&self) -> Vc<FileSystemPath>; fn path(&self) -> Vc<FileSystemPath>;
/// The identifier of the [OutputAsset] as string. It's expected to be unique and
/// capture all properties of the [OutputAsset].
#[turbo_tasks::function]
async fn path_string(self: Vc<Self>) -> Result<Vc<RcStr>> {
Ok(self.path().resolve().await?.to_string())
}
/// Other references [OutputAsset]s from this [OutputAsset]. /// Other references [OutputAsset]s from this [OutputAsset].
#[turbo_tasks::function] #[turbo_tasks::function]
fn references(self: Vc<Self>) -> Vc<OutputAssets> { fn references(self: Vc<Self>) -> Vc<OutputAssets> {
......
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