Unverified Commit 4e110ef3 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] Eliminate many calls to `into` and from and cell involving RcStr (#80076)

Adopt the `rcstr!` macro in turbopack

Instead of `"foo".into()` call `rcstr!("foo")` while being slightly more annoying to type the macro approach is more readabie and faster as it can leverage constant folding for small strings and amortize construction of larger strings.  In general these performance improvement are very small but consistent.

At the same time, eliminate uses of turbo-tasks where they were amortizing construction of RcStr instances since the `rcstr!` macro can do the same thing.  Generally speaking we should prefer `RcStr` over `ResolvedVc<RcStr>` as a task input since it has much more reasonable equality semantics and observationally many of these values were constructed via `Vc::cell("foo".into())`.

## Why?

Generally this should be a small consistent memory and performance improvement.  My understanding is that many uses of `ResolvedVc<RcStr>` actually predate `RcStr` when we were using `String` directly.  In that world, turbotasks are fulfilling a vital function, but now that we can rely on RcStr this is much less needed.

## How?

Mostly this was a bunch of regex replacements and manual fixups.  An AstGrep rule would have been ideal but beyond matching `RcStr::from("...")` this doesn't work since it was mostly calls to `into()` which rely on type inference.  Still by seeding the codebase with the pattern we can probably prevent regressions.

## Performance

From measuring vercel-site this is a latency progression of a few percent.  codspeed agrees!

![image.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/AwJ29EfoPcPdLSwCZxAz/c08ffcaa-2856-4742-a049-1306491d69ba.png)
parent b981ac58
...@@ -10180,6 +10180,7 @@ dependencies = [ ...@@ -10180,6 +10180,7 @@ dependencies = [
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
"serde", "serde",
"serde_with", "serde_with",
"turbo-rcstr",
"turbo-tasks", "turbo-tasks",
"turbo-tasks-build", "turbo-tasks-build",
"turbo-tasks-fs", "turbo-tasks-fs",
......
...@@ -28,7 +28,7 @@ use serde::{Deserialize, Serialize}; ...@@ -28,7 +28,7 @@ use serde::{Deserialize, Serialize};
use tokio::{io::AsyncWriteExt, time::Instant}; use tokio::{io::AsyncWriteExt, time::Instant};
use tracing::Instrument; use tracing::Instrument;
use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt}; use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
Completion, Effects, FxIndexSet, NonLocalValue, OperationValue, OperationVc, ReadRef, Completion, Effects, FxIndexSet, NonLocalValue, OperationValue, OperationVc, ReadRef,
ResolvedVc, TaskInput, TransientInstance, TryJoinIterExt, UpdateInfo, Vc, get_effects, ResolvedVc, TaskInput, TransientInstance, TryJoinIterExt, UpdateInfo, Vc, get_effects,
...@@ -426,7 +426,7 @@ pub async fn project_new( ...@@ -426,7 +426,7 @@ pub async fn project_new(
let options: ProjectOptions = options.into(); let options: ProjectOptions = options.into();
let container = turbo_tasks let container = turbo_tasks
.run_once(async move { .run_once(async move {
let project = ProjectContainer::new("next.js".into(), options.dev); let project = ProjectContainer::new(rcstr!("next.js"), options.dev);
let project = project.to_resolved().await?; let project = project.to_resolved().await?;
project.initialize(options).await?; project.initialize(options).await?;
Ok(project) Ok(project)
......
This diff is collapsed.
...@@ -6,7 +6,7 @@ use next_core::{ ...@@ -6,7 +6,7 @@ use next_core::{
next_server::{ServerContextType, get_server_runtime_entries}, next_server::{ServerContextType, get_server_runtime_entries},
}; };
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, ResolvedVc, Value, Vc}; use turbo_tasks::{Completion, ResolvedVc, Value, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath}; use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -44,7 +44,7 @@ pub struct InstrumentationEndpoint { ...@@ -44,7 +44,7 @@ pub struct InstrumentationEndpoint {
is_edge: bool, is_edge: bool,
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -56,7 +56,7 @@ impl InstrumentationEndpoint { ...@@ -56,7 +56,7 @@ impl InstrumentationEndpoint {
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
is_edge: bool, is_edge: bool,
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
) -> Vc<Self> { ) -> Vc<Self> {
Self { Self {
project, project,
...@@ -85,7 +85,7 @@ impl InstrumentationEndpoint { ...@@ -85,7 +85,7 @@ impl InstrumentationEndpoint {
*self.asset_context, *self.asset_context,
self.project.project_path(), self.project.project_path(),
*userland_module, *userland_module,
"instrumentation".into(), rcstr!("instrumentation"),
) )
.to_resolved() .to_resolved()
.await?; .await?;
...@@ -108,7 +108,8 @@ impl InstrumentationEndpoint { ...@@ -108,7 +108,8 @@ impl InstrumentationEndpoint {
Value::new(ServerContextType::Instrumentation { Value::new(ServerContextType::Instrumentation {
app_dir: this.app_dir, app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name, .ecmascript_client_reference_transition_name
.clone(),
}), }),
this.project.next_mode(), this.project.next_mode(),
) )
...@@ -147,12 +148,13 @@ impl InstrumentationEndpoint { ...@@ -147,12 +148,13 @@ impl InstrumentationEndpoint {
.entry_chunk_group( .entry_chunk_group(
this.project this.project
.node_root() .node_root()
.join("server/instrumentation.js".into()), .join(rcstr!("server/instrumentation.js")),
get_server_runtime_entries( get_server_runtime_entries(
Value::new(ServerContextType::Instrumentation { Value::new(ServerContextType::Instrumentation {
app_dir: this.app_dir, app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name, .ecmascript_client_reference_transition_name
.clone(),
}), }),
this.project.next_mode(), this.project.next_mode(),
) )
...@@ -188,7 +190,7 @@ impl InstrumentationEndpoint { ...@@ -188,7 +190,7 @@ impl InstrumentationEndpoint {
let instrumentation_definition = InstrumentationDefinition { let instrumentation_definition = InstrumentationDefinition {
files: file_paths_from_root, files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?, wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
name: "instrumentation".into(), name: rcstr!("instrumentation"),
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
...@@ -196,7 +198,7 @@ impl InstrumentationEndpoint { ...@@ -196,7 +198,7 @@ impl InstrumentationEndpoint {
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = VirtualOutputAsset::new( let middleware_manifest_v2 = VirtualOutputAsset::new(
node_root.join("server/instrumentation/middleware-manifest.json".into()), node_root.join(rcstr!("server/instrumentation/middleware-manifest.json")),
AssetContent::file( AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty( FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2, &middleware_manifest_v2,
......
...@@ -10,7 +10,7 @@ use next_core::{ ...@@ -10,7 +10,7 @@ use next_core::{
util::{MiddlewareMatcherKind, NextRuntime, parse_config_from_source}, util::{MiddlewareMatcherKind, NextRuntime, parse_config_from_source},
}; };
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, ResolvedVc, Value, Vc}; use turbo_tasks::{Completion, ResolvedVc, Value, Vc};
use turbo_tasks_fs::{self, File, FileContent, FileSystemPath}; use turbo_tasks_fs::{self, File, FileContent, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -47,7 +47,7 @@ pub struct MiddlewareEndpoint { ...@@ -47,7 +47,7 @@ pub struct MiddlewareEndpoint {
asset_context: ResolvedVc<Box<dyn AssetContext>>, asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -58,7 +58,7 @@ impl MiddlewareEndpoint { ...@@ -58,7 +58,7 @@ impl MiddlewareEndpoint {
asset_context: ResolvedVc<Box<dyn AssetContext>>, asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
) -> Vc<Self> { ) -> Vc<Self> {
Self { Self {
project, project,
...@@ -95,7 +95,7 @@ impl MiddlewareEndpoint { ...@@ -95,7 +95,7 @@ impl MiddlewareEndpoint {
*self.asset_context, *self.asset_context,
self.project.project_path(), self.project.project_path(),
module, module,
"middleware".into(), rcstr!("middleware"),
)) ))
} }
...@@ -110,7 +110,8 @@ impl MiddlewareEndpoint { ...@@ -110,7 +110,8 @@ impl MiddlewareEndpoint {
Value::new(ServerContextType::Middleware { Value::new(ServerContextType::Middleware {
app_dir: this.app_dir, app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name, .ecmascript_client_reference_transition_name
.clone(),
}), }),
this.project.next_mode(), this.project.next_mode(),
) )
...@@ -146,12 +147,15 @@ impl MiddlewareEndpoint { ...@@ -146,12 +147,15 @@ impl MiddlewareEndpoint {
let EntryChunkGroupResult { asset: chunk, .. } = *chunking_context let EntryChunkGroupResult { asset: chunk, .. } = *chunking_context
.entry_chunk_group( .entry_chunk_group(
this.project.node_root().join("server/middleware.js".into()), this.project
.node_root()
.join(rcstr!("server/middleware.js")),
get_server_runtime_entries( get_server_runtime_entries(
Value::new(ServerContextType::Middleware { Value::new(ServerContextType::Middleware {
app_dir: this.app_dir, app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name, .ecmascript_client_reference_transition_name
.clone(),
}), }),
this.project.next_mode(), this.project.next_mode(),
) )
...@@ -233,8 +237,8 @@ impl MiddlewareEndpoint { ...@@ -233,8 +237,8 @@ impl MiddlewareEndpoint {
.collect() .collect()
} else { } else {
vec![MiddlewareMatcher { vec![MiddlewareMatcher {
regexp: Some("^/.*$".into()), regexp: Some(rcstr!("^/.*$")),
original_source: "/:path*".into(), original_source: rcstr!("/:path*"),
..Default::default() ..Default::default()
}] }]
}; };
...@@ -256,7 +260,7 @@ impl MiddlewareEndpoint { ...@@ -256,7 +260,7 @@ impl MiddlewareEndpoint {
let middleware_manifest_v2 = VirtualOutputAsset::new( let middleware_manifest_v2 = VirtualOutputAsset::new(
this.project this.project
.node_root() .node_root()
.join("server/middleware/middleware-manifest.json".into()), .join(rcstr!("server/middleware/middleware-manifest.json")),
AssetContent::file( AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty( FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2, &middleware_manifest_v2,
...@@ -303,20 +307,20 @@ impl MiddlewareEndpoint { ...@@ -303,20 +307,20 @@ impl MiddlewareEndpoint {
files: file_paths_from_root, files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?, wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
assets: paths_to_bindings(all_assets), assets: paths_to_bindings(all_assets),
name: "middleware".into(), name: rcstr!("middleware"),
page: "/".into(), page: rcstr!("/"),
regions, regions,
matchers: matchers.clone(), matchers: matchers.clone(),
env: this.project.edge_env().owned().await?, env: this.project.edge_env().owned().await?,
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
middleware: [("/".into(), edge_function_definition)] middleware: [(rcstr!("/"), edge_function_definition)]
.into_iter() .into_iter()
.collect(), .collect(),
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = VirtualOutputAsset::new( let middleware_manifest_v2 = VirtualOutputAsset::new(
node_root.join("server/middleware/middleware-manifest.json".into()), node_root.join(rcstr!("server/middleware/middleware-manifest.json")),
AssetContent::file( AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty( FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2, &middleware_manifest_v2,
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -119,7 +119,7 @@ impl HmrEntryModuleReference { ...@@ -119,7 +119,7 @@ impl HmrEntryModuleReference {
impl ValueToString for HmrEntryModuleReference { impl ValueToString for HmrEntryModuleReference {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("entry".into()) Vc::cell(rcstr!("entry"))
} }
} }
......
use std::iter::once; use std::iter::once;
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc}; use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::EnvMap; use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -102,14 +102,14 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer ...@@ -102,14 +102,14 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer
Ok(free_var_references!( Ok(free_var_references!(
..defines(&*define_env.await?).into_iter(), ..defines(&*define_env.await?).into_iter(),
Buffer = FreeVarReference::EcmaScriptModule { Buffer = FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(), request: rcstr!("node:buffer"),
lookup_path: None, lookup_path: None,
export: Some("Buffer".into()), export: Some(rcstr!("Buffer")),
}, },
process = FreeVarReference::EcmaScriptModule { process = FreeVarReference::EcmaScriptModule {
request: "node:process".into(), request: rcstr!("node:process"),
lookup_path: None, lookup_path: None,
export: Some("default".into()), export: Some(rcstr!("default")),
} }
) )
.cell()) .cell())
...@@ -265,7 +265,7 @@ pub async fn get_client_module_options_context( ...@@ -265,7 +265,7 @@ pub async fn get_client_module_options_context(
// foreign_code_context_condition. This allows to import codes from // foreign_code_context_condition. This allows to import codes from
// node_modules that requires webpack loaders, which next-dev implicitly // node_modules that requires webpack loaders, which next-dev implicitly
// does by default. // does by default.
let conditions = vec!["browser".into(), mode.await?.condition().into()]; let conditions = vec![rcstr!("browser"), mode.await?.condition().into()];
let foreign_enable_webpack_loaders = webpack_loader_options( let foreign_enable_webpack_loaders = webpack_loader_options(
project_path, project_path,
next_config, next_config,
...@@ -273,7 +273,7 @@ pub async fn get_client_module_options_context( ...@@ -273,7 +273,7 @@ pub async fn get_client_module_options_context(
conditions conditions
.iter() .iter()
.cloned() .cloned()
.chain(once("foreign".into())) .chain(once(rcstr!("foreign")))
.collect(), .collect(),
) )
.await?; .await?;
...@@ -425,9 +425,9 @@ pub async fn get_client_module_options_context( ...@@ -425,9 +425,9 @@ pub async fn get_client_module_options_context(
pub async fn get_client_chunking_context( pub async fn get_client_chunking_context(
root_path: ResolvedVc<FileSystemPath>, root_path: ResolvedVc<FileSystemPath>,
client_root: ResolvedVc<FileSystemPath>, client_root: ResolvedVc<FileSystemPath>,
client_root_to_root_path: ResolvedVc<RcStr>, client_root_to_root_path: RcStr,
asset_prefix: ResolvedVc<Option<RcStr>>, asset_prefix: Option<RcStr>,
chunk_suffix_path: ResolvedVc<Option<RcStr>>, chunk_suffix_path: Option<RcStr>,
environment: ResolvedVc<Environment>, environment: ResolvedVc<Environment>,
mode: Vc<NextMode>, mode: Vc<NextMode>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>, module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
...@@ -442,14 +442,14 @@ pub async fn get_client_chunking_context( ...@@ -442,14 +442,14 @@ pub async fn get_client_chunking_context(
client_root_to_root_path, client_root_to_root_path,
client_root, client_root,
client_root client_root
.join("static/chunks".into()) .join(rcstr!("static/chunks"))
.to_resolved() .to_resolved()
.await?, .await?,
get_client_assets_path(*client_root).to_resolved().await?, get_client_assets_path(*client_root).to_resolved().await?,
environment, environment,
next_mode.runtime_type(), next_mode.runtime_type(),
) )
.chunk_base_path(asset_prefix) .chunk_base_path(asset_prefix.clone())
.chunk_suffix_path(chunk_suffix_path) .chunk_suffix_path(chunk_suffix_path)
.minify_type(if *minify.await? { .minify_type(if *minify.await? {
MinifyType::Minify { MinifyType::Minify {
...@@ -494,7 +494,7 @@ pub async fn get_client_chunking_context( ...@@ -494,7 +494,7 @@ pub async fn get_client_chunking_context(
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn get_client_assets_path(client_root: Vc<FileSystemPath>) -> Vc<FileSystemPath> { pub fn get_client_assets_path(client_root: Vc<FileSystemPath>) -> Vc<FileSystemPath> {
client_root.join("static/media".into()) client_root.join(rcstr!("static/media"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -522,7 +522,7 @@ pub async fn get_client_runtime_entries( ...@@ -522,7 +522,7 @@ pub async fn get_client_runtime_entries(
runtime_entries.push( runtime_entries.push(
RuntimeEntry::Request( RuntimeEntry::Request(
request.to_resolved().await?, request.to_resolved().await?,
project_root.join("_".into()).to_resolved().await?, project_root.join(rcstr!("_")).to_resolved().await?,
) )
.resolved_cell(), .resolved_cell(),
) )
...@@ -532,12 +532,12 @@ pub async fn get_client_runtime_entries( ...@@ -532,12 +532,12 @@ pub async fn get_client_runtime_entries(
if matches!(*ty, ClientContextType::App { .. },) { if matches!(*ty, ClientContextType::App { .. },) {
runtime_entries.push( runtime_entries.push(
RuntimeEntry::Request( RuntimeEntry::Request(
Request::parse(Value::new(Pattern::Constant( Request::parse(Value::new(Pattern::Constant(rcstr!(
"next/dist/client/app-next-turbopack.js".into(), "next/dist/client/app-next-turbopack.js"
))) ))))
.to_resolved() .to_resolved()
.await?, .await?,
project_root.join("_".into()).to_resolved().await?, project_root.join(rcstr!("_")).to_resolved().await?,
) )
.resolved_cell(), .resolved_cell(),
); );
......
...@@ -80,7 +80,7 @@ impl ChunkableModuleReference for CssClientReference { ...@@ -80,7 +80,7 @@ impl ChunkableModuleReference for CssClientReference {
fn chunking_type(&self) -> Vc<ChunkingTypeOption> { fn chunking_type(&self) -> Vc<ChunkingTypeOption> {
Vc::cell(Some(ChunkingType::Isolated { Vc::cell(Some(ChunkingType::Isolated {
_ty: ChunkGroupType::Evaluated, _ty: ChunkGroupType::Evaluated,
merge_tag: Some("client".into()), merge_tag: Some(rcstr!("client")),
})) }))
} }
} }
...@@ -97,6 +97,6 @@ impl ModuleReference for CssClientReference { ...@@ -97,6 +97,6 @@ impl ModuleReference for CssClientReference {
impl ValueToString for CssClientReference { impl ValueToString for CssClientReference {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("css client reference to client".into()) Vc::cell(rcstr!("css client reference to client"))
} }
} }
...@@ -176,16 +176,6 @@ impl EcmascriptClientReferenceModule { ...@@ -176,16 +176,6 @@ impl EcmascriptClientReferenceModule {
} }
} }
#[turbo_tasks::function]
fn ecmascript_client_reference_client_ref_modifier() -> Vc<RcStr> {
Vc::cell("ecmascript client reference to client".into())
}
#[turbo_tasks::function]
fn ecmascript_client_reference_ssr_ref_modifier() -> Vc<RcStr> {
Vc::cell("ecmascript client reference to ssr".into())
}
pub fn ecmascript_client_reference_merge_tag() -> RcStr { pub fn ecmascript_client_reference_merge_tag() -> RcStr {
rcstr!("client") rcstr!("client")
} }
...@@ -222,7 +212,7 @@ impl Module for EcmascriptClientReferenceModule { ...@@ -222,7 +212,7 @@ impl Module for EcmascriptClientReferenceModule {
*ResolvedVc::upcast(*client_module), *ResolvedVc::upcast(*client_module),
ChunkGroupType::Evaluated, ChunkGroupType::Evaluated,
Some(ecmascript_client_reference_merge_tag()), Some(ecmascript_client_reference_merge_tag()),
ecmascript_client_reference_client_ref_modifier(), rcstr!("ecmascript client reference to client"),
) )
.to_resolved() .to_resolved()
.await?, .await?,
...@@ -232,7 +222,7 @@ impl Module for EcmascriptClientReferenceModule { ...@@ -232,7 +222,7 @@ impl Module for EcmascriptClientReferenceModule {
*ResolvedVc::upcast(*ssr_module), *ResolvedVc::upcast(*ssr_module),
ChunkGroupType::Entry, ChunkGroupType::Entry,
Some(ecmascript_client_reference_merge_tag_ssr()), Some(ecmascript_client_reference_merge_tag_ssr()),
ecmascript_client_reference_ssr_ref_modifier(), rcstr!("ecmascript client reference to ssr"),
) )
.to_resolved() .to_resolved()
.await?, .await?,
...@@ -298,11 +288,6 @@ struct EcmascriptClientReferenceProxyChunkItem { ...@@ -298,11 +288,6 @@ struct EcmascriptClientReferenceProxyChunkItem {
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
} }
#[turbo_tasks::function]
fn client_reference_description() -> Vc<RcStr> {
Vc::cell("client references".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ChunkItem for EcmascriptClientReferenceProxyChunkItem { impl ChunkItem for EcmascriptClientReferenceProxyChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -348,7 +333,7 @@ pub(crate) struct EcmascriptClientReference { ...@@ -348,7 +333,7 @@ pub(crate) struct EcmascriptClientReference {
module: ResolvedVc<Box<dyn Module>>, module: ResolvedVc<Box<dyn Module>>,
ty: ChunkGroupType, ty: ChunkGroupType,
merge_tag: Option<RcStr>, merge_tag: Option<RcStr>,
description: ResolvedVc<RcStr>, description: RcStr,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -358,7 +343,7 @@ impl EcmascriptClientReference { ...@@ -358,7 +343,7 @@ impl EcmascriptClientReference {
module: ResolvedVc<Box<dyn Module>>, module: ResolvedVc<Box<dyn Module>>,
ty: ChunkGroupType, ty: ChunkGroupType,
merge_tag: Option<RcStr>, merge_tag: Option<RcStr>,
description: ResolvedVc<RcStr>, description: RcStr,
) -> Vc<Self> { ) -> Vc<Self> {
Self::cell(EcmascriptClientReference { Self::cell(EcmascriptClientReference {
module, module,
...@@ -392,6 +377,6 @@ impl ModuleReference for EcmascriptClientReference { ...@@ -392,6 +377,6 @@ impl ModuleReference for EcmascriptClientReference {
impl ValueToString for EcmascriptClientReference { impl ValueToString for EcmascriptClientReference {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
*self.description Vc::cell(self.description.clone())
} }
} }
...@@ -3,7 +3,7 @@ use rustc_hash::FxHashSet; ...@@ -3,7 +3,7 @@ use rustc_hash::FxHashSet;
use serde::{Deserialize, Deserializer, Serialize}; use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
use turbo_esregex::EsRegex; use turbo_esregex::EsRegex;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, NonLocalValue, OperationValue, ResolvedVc, TaskInput, Vc, debug::ValueDebugFormat, FxIndexMap, NonLocalValue, OperationValue, ResolvedVc, TaskInput, Vc, debug::ValueDebugFormat,
trace::TraceRawVcs, trace::TraceRawVcs,
...@@ -1655,7 +1655,7 @@ impl Issue for OutdatedConfigIssue { ...@@ -1655,7 +1655,7 @@ impl Issue for OutdatedConfigIssue {
fn title(&self) -> Vc<StyledString> { fn title(&self) -> Vc<StyledString> {
StyledString::Line(vec![ StyledString::Line(vec![
StyledString::Code(self.old_name.clone()), StyledString::Code(self.old_name.clone()),
StyledString::Text(" has been replaced by ".into()), StyledString::Text(rcstr!(" has been replaced by ")),
StyledString::Code(self.new_name.clone()), StyledString::Code(self.new_name.clone()),
]) ])
.cell() .cell()
......
...@@ -37,9 +37,8 @@ impl NextDynamicEntryModule { ...@@ -37,9 +37,8 @@ impl NextDynamicEntryModule {
} }
} }
#[turbo_tasks::function] fn dynamic_ref_description() -> RcStr {
fn dynamic_ref_description() -> Vc<RcStr> { rcstr!("next/dynamic reference")
Vc::cell("next/dynamic reference".into())
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -105,9 +104,10 @@ impl EcmascriptChunkPlaceable for NextDynamicEntryModule { ...@@ -105,9 +104,10 @@ impl EcmascriptChunkPlaceable for NextDynamicEntryModule {
); );
let mut exports = BTreeMap::new(); let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert( exports.insert(
"default".into(), default.clone(),
EsmExport::ImportedBinding(module_reference, "default".into(), false), EsmExport::ImportedBinding(module_reference, default, false),
); );
Ok(EcmascriptExports::EsmExports( Ok(EcmascriptExports::EsmExports(
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc}; use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::EnvMap; use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -71,9 +71,9 @@ async fn next_edge_free_vars( ...@@ -71,9 +71,9 @@ async fn next_edge_free_vars(
Ok(free_var_references!( Ok(free_var_references!(
..defines(&*define_env.await?).into_iter(), ..defines(&*define_env.await?).into_iter(),
Buffer = FreeVarReference::EcmaScriptModule { Buffer = FreeVarReference::EcmaScriptModule {
request: "buffer".into(), request: rcstr!("buffer"),
lookup_path: Some(project_path), lookup_path: Some(project_path),
export: Some("Buffer".into()), export: Some(rcstr!("Buffer")),
}, },
) )
.cell()) .cell())
...@@ -109,8 +109,13 @@ pub async fn get_edge_resolve_options_context( ...@@ -109,8 +109,13 @@ pub async fn get_edge_resolve_options_context(
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_edge_import_map = let next_edge_import_map = get_next_edge_import_map(
get_next_edge_import_map(*project_path, ty, next_config, mode, execution_context) *project_path,
ty.clone(),
next_config,
mode,
execution_context,
)
.to_resolved() .to_resolved()
.await?; .await?;
...@@ -171,7 +176,7 @@ pub async fn get_edge_resolve_options_context( ...@@ -171,7 +176,7 @@ pub async fn get_edge_resolve_options_context(
); );
if ty.supports_react_server() { if ty.supports_react_server() {
custom_conditions.push("react-server".into()); custom_conditions.push(rcstr!("react-server"));
}; };
let resolve_options_context = ResolveOptionsContext { let resolve_options_context = ResolveOptionsContext {
...@@ -214,25 +219,25 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -214,25 +219,25 @@ pub async fn get_edge_chunking_context_with_client_assets(
mode: Vc<NextMode>, mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>, root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>, node_root: ResolvedVc<FileSystemPath>,
output_root_to_root_path: ResolvedVc<RcStr>, output_root_to_root_path: RcStr,
client_root: ResolvedVc<FileSystemPath>, client_root: ResolvedVc<FileSystemPath>,
asset_prefix: ResolvedVc<Option<RcStr>>, asset_prefix: Option<RcStr>,
environment: ResolvedVc<Environment>, environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>, module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>, turbo_minify: Vc<bool>,
turbo_source_maps: Vc<bool>, turbo_source_maps: Vc<bool>,
no_mangling: Vc<bool>, no_mangling: Vc<bool>,
) -> Result<Vc<Box<dyn ChunkingContext>>> { ) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".into()).to_resolved().await?; let output_root = node_root.join(rcstr!("server/edge")).to_resolved().await?;
let next_mode = mode.await?; let next_mode = mode.await?;
let mut builder = BrowserChunkingContext::builder( let mut builder = BrowserChunkingContext::builder(
root_path, root_path,
output_root, output_root,
output_root_to_root_path, output_root_to_root_path,
client_root, client_root,
output_root.join("chunks/ssr".into()).to_resolved().await?, output_root.join(rcstr!("chunks/ssr")).to_resolved().await?,
client_root client_root
.join("static/media".into()) .join(rcstr!("static/media"))
.to_resolved() .to_resolved()
.await?, .await?,
environment, environment,
...@@ -279,22 +284,22 @@ pub async fn get_edge_chunking_context( ...@@ -279,22 +284,22 @@ pub async fn get_edge_chunking_context(
mode: Vc<NextMode>, mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>, root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>, node_root: ResolvedVc<FileSystemPath>,
node_root_to_root_path: ResolvedVc<RcStr>, node_root_to_root_path: RcStr,
environment: ResolvedVc<Environment>, environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>, module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>, turbo_minify: Vc<bool>,
turbo_source_maps: Vc<bool>, turbo_source_maps: Vc<bool>,
no_mangling: Vc<bool>, no_mangling: Vc<bool>,
) -> Result<Vc<Box<dyn ChunkingContext>>> { ) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".into()).to_resolved().await?; let output_root = node_root.join(rcstr!("server/edge")).to_resolved().await?;
let next_mode = mode.await?; let next_mode = mode.await?;
let mut builder = BrowserChunkingContext::builder( let mut builder = BrowserChunkingContext::builder(
root_path, root_path,
output_root, output_root,
node_root_to_root_path, node_root_to_root_path,
output_root, output_root,
output_root.join("chunks".into()).to_resolved().await?, output_root.join(rcstr!("chunks")).to_resolved().await?,
output_root.join("assets".into()).to_resolved().await?, output_root.join(rcstr!("assets")).to_resolved().await?,
environment, environment,
next_mode.runtime_type(), next_mode.runtime_type(),
) )
...@@ -302,7 +307,7 @@ pub async fn get_edge_chunking_context( ...@@ -302,7 +307,7 @@ pub async fn get_edge_chunking_context(
// instead. This special blob url is handled by the custom fetch // instead. This special blob url is handled by the custom fetch
// implementation in the edge sandbox. It will respond with the // implementation in the edge sandbox. It will respond with the
// asset from the output directory. // asset from the output directory.
.asset_base_path(ResolvedVc::cell(Some("blob:server/edge/".into()))) .asset_base_path(Some(rcstr!("blob:server/edge/")))
.minify_type(if *turbo_minify.await? { .minify_type(if *turbo_minify.await? {
MinifyType::Minify { MinifyType::Minify {
mangle: (!*no_mangling.await?).then_some(MangleType::OptimalSize), mangle: (!*no_mangling.await?).then_some(MangleType::OptimalSize),
......
use anyhow::Result; use anyhow::Result;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
pub(crate) struct DefaultFallbackFont { pub(crate) struct DefaultFallbackFont {
...@@ -14,16 +14,16 @@ pub(crate) struct DefaultFallbackFont { ...@@ -14,16 +14,16 @@ pub(crate) struct DefaultFallbackFont {
// From https://github.com/vercel/next.js/blob/a3893bf69c83fb08e88c87bf8a21d987a0448c8e/packages/font/src/utils.ts#L4 // From https://github.com/vercel/next.js/blob/a3893bf69c83fb08e88c87bf8a21d987a0448c8e/packages/font/src/utils.ts#L4
pub(crate) static DEFAULT_SANS_SERIF_FONT: Lazy<DefaultFallbackFont> = pub(crate) static DEFAULT_SANS_SERIF_FONT: Lazy<DefaultFallbackFont> =
Lazy::new(|| DefaultFallbackFont { Lazy::new(|| DefaultFallbackFont {
name: "Arial".into(), name: rcstr!("Arial"),
capsize_key: "arial".into(), capsize_key: rcstr!("arial"),
az_avg_width: 934.5116279069767, az_avg_width: 934.5116279069767,
units_per_em: 2048, units_per_em: 2048,
}); });
pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> = pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> =
Lazy::new(|| DefaultFallbackFont { Lazy::new(|| DefaultFallbackFont {
name: "Times New Roman".into(), name: rcstr!("Times New Roman"),
capsize_key: "timesNewRoman".into(), capsize_key: rcstr!("timesNewRoman"),
az_avg_width: 854.3953488372093, az_avg_width: 854.3953488372093,
units_per_em: 2048, units_per_em: 2048,
}); });
...@@ -32,9 +32,9 @@ pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> = ...@@ -32,9 +32,9 @@ pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> =
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub(crate) struct AutomaticFontFallback { pub(crate) struct AutomaticFontFallback {
/// e.g. `__Roboto_Fallback_c123b8` /// e.g. `__Roboto_Fallback_c123b8`
pub scoped_font_family: ResolvedVc<RcStr>, pub scoped_font_family: RcStr,
/// The name of font locally, used in `src: local("{}")` /// The name of font locally, used in `src: local("{}")`
pub local_font_family: ResolvedVc<RcStr>, pub local_font_family: RcStr,
pub adjustment: Option<FontAdjustment>, pub adjustment: Option<FontAdjustment>,
} }
......
...@@ -3,7 +3,7 @@ use once_cell::sync::Lazy; ...@@ -3,7 +3,7 @@ use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::issue::{IssueExt, IssueSeverity, StyledString}; use turbopack_core::issue::{IssueExt, IssueSeverity, StyledString};
...@@ -53,7 +53,7 @@ pub(super) async fn get_font_fallback( ...@@ -53,7 +53,7 @@ pub(super) async fn get_font_fallback(
None => { None => {
let metrics_json = load_next_js_templateon( let metrics_json = load_next_js_templateon(
lookup_path, lookup_path,
"dist/server/capsize-font-metrics.json".into(), rcstr!("dist/server/capsize-font-metrics.json"),
) )
.await?; .await?;
let fallback = lookup_fallback( let fallback = lookup_fallback(
...@@ -65,12 +65,10 @@ pub(super) async fn get_font_fallback( ...@@ -65,12 +65,10 @@ pub(super) async fn get_font_fallback(
match fallback { match fallback {
Ok(fallback) => FontFallback::Automatic(AutomaticFontFallback { Ok(fallback) => FontFallback::Automatic(AutomaticFontFallback {
scoped_font_family: get_scoped_font_family( scoped_font_family: get_scoped_font_family(
FontFamilyType::Fallback.cell(), FontFamilyType::Fallback,
options_vc.font_family(), options_vc.font_family().await?,
) ),
.to_resolved() local_font_family: fallback.font_family,
.await?,
local_font_family: ResolvedVc::cell(fallback.font_family),
adjustment: fallback.adjustment, adjustment: fallback.adjustment,
}) })
.cell(), .cell(),
...@@ -85,9 +83,9 @@ pub(super) async fn get_font_fallback( ...@@ -85,9 +83,9 @@ pub(super) async fn get_font_fallback(
.into(), .into(),
) )
.resolved_cell(), .resolved_cell(),
description: StyledString::Text( description: StyledString::Text(rcstr!(
"Skipping generating a fallback font.".into(), "Skipping generating a fallback font."
) ))
.resolved_cell(), .resolved_cell(),
severity: IssueSeverity::Warning.resolved_cell(), severity: IssueSeverity::Warning.resolved_cell(),
} }
...@@ -172,6 +170,7 @@ fn lookup_fallback( ...@@ -172,6 +170,7 @@ fn lookup_fallback(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{FontAdjustment, FontMetricsMap}; use super::{FontAdjustment, FontMetricsMap};
...@@ -211,7 +210,7 @@ mod tests { ...@@ -211,7 +210,7 @@ mod tests {
assert_eq!( assert_eq!(
lookup_fallback("Inter", font_metrics, true)?, lookup_fallback("Inter", font_metrics, true)?,
Fallback { Fallback {
font_family: "Arial".into(), font_family: rcstr!("Arial"),
adjustment: Some(FontAdjustment { adjustment: Some(FontAdjustment {
ascent: 0.901_989_700_374_532, ascent: 0.901_989_700_374_532,
descent: -0.224_836_142_322_097_4, descent: -0.224_836_142_322_097_4,
...@@ -257,7 +256,7 @@ mod tests { ...@@ -257,7 +256,7 @@ mod tests {
assert_eq!( assert_eq!(
lookup_fallback("Roboto Slab", font_metrics, true)?, lookup_fallback("Roboto Slab", font_metrics, true)?,
Fallback { Fallback {
font_family: "Times New Roman".into(), font_family: rcstr!("Times New Roman"),
adjustment: Some(FontAdjustment { adjustment: Some(FontAdjustment {
ascent: 0.885_645_438_273_993_8, ascent: 0.885_645_438_273_993_8,
descent: -0.229_046_234_036_377_7, descent: -0.229_046_234_036_377_7,
......
...@@ -5,7 +5,7 @@ use futures::FutureExt; ...@@ -5,7 +5,7 @@ use futures::FutureExt;
use indoc::formatdoc; use indoc::formatdoc;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, FxIndexMap, ResolvedVc, Value, Vc}; use turbo_tasks::{Completion, FxIndexMap, ResolvedVc, Value, Vc};
use turbo_tasks_bytes::stream::SingleValue; use turbo_tasks_bytes::stream::SingleValue;
use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv}; use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv};
...@@ -96,8 +96,8 @@ impl NextFontGoogleReplacer { ...@@ -96,8 +96,8 @@ impl NextFontGoogleReplacer {
let fallback = get_font_fallback(*self.project_path, options); let fallback = get_font_fallback(*self.project_path, options);
let properties = get_font_css_properties(options, fallback).await?; let properties = get_font_css_properties(options, fallback).await?;
let js_asset = VirtualSource::new( let js_asset = VirtualSource::new(
next_js_file_path("internal/font/google".into()) next_js_file_path(rcstr!("internal/font/google"))
.join(format!("{}.js", get_request_id(options.font_family(), request_hash).await?).into()), .join(format!("{}.js", get_request_id(options.font_family().await?, request_hash)).into()),
AssetContent::file(FileContent::Content( AssetContent::file(FileContent::Content(
formatdoc!( formatdoc!(
r#" r#"
...@@ -203,28 +203,28 @@ impl NextFontGoogleCssModuleReplacer { ...@@ -203,28 +203,28 @@ impl NextFontGoogleCssModuleReplacer {
let request_hash = get_request_hash(&query); let request_hash = get_request_hash(&query);
let font_data = load_font_data(*self.project_path); let font_data = load_font_data(*self.project_path);
let options = font_options_from_query_map(query, font_data); let options = font_options_from_query_map(query, font_data);
let stylesheet_url = get_stylesheet_url_from_options(options, font_data); let stylesheet_url = get_stylesheet_url_from_options(options, font_data)
.owned()
.await?;
let font_family = options.font_family().await?;
let scoped_font_family = let scoped_font_family =
get_scoped_font_family(FontFamilyType::WebFont.cell(), options.font_family()); get_scoped_font_family(FontFamilyType::WebFont, font_family.clone());
let css_virtual_path = next_js_file_path("internal/font/google".into()).join( let css_virtual_path = next_js_file_path(rcstr!("internal/font/google"))
format!( .join(format!("/{}.module.css", get_request_id(font_family, request_hash)).into());
"/{}.module.css",
get_request_id(options.font_family(), request_hash).await?
)
.into(),
);
// When running Next.js integration tests, use the mock data available in // When running Next.js integration tests, use the mock data available in
// process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES instead of making real // process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES instead of making real
// requests to Google Fonts. // requests to Google Fonts.
let env = Vc::upcast::<Box<dyn ProcessEnv>>(CommandLineProcessEnv::new()); let env = Vc::upcast::<Box<dyn ProcessEnv>>(CommandLineProcessEnv::new());
let mocked_responses_path = &*env.read("NEXT_FONT_GOOGLE_MOCKED_RESPONSES".into()).await?; let mocked_responses_path = &*env
.read(rcstr!("NEXT_FONT_GOOGLE_MOCKED_RESPONSES"))
.await?;
let stylesheet_str = mocked_responses_path let stylesheet_str = mocked_responses_path
.as_ref() .as_ref()
.map_or_else( .map_or_else(
|| fetch_real_stylesheet(stylesheet_url, css_virtual_path).boxed(), || fetch_real_stylesheet(stylesheet_url.clone(), css_virtual_path).boxed(),
|p| get_mock_stylesheet(stylesheet_url, p, *self.execution_context).boxed(), |p| get_mock_stylesheet(stylesheet_url.clone(), p, *self.execution_context).boxed(),
) )
.await?; .await?;
...@@ -416,12 +416,11 @@ impl ImportMappingReplacement for NextFontGoogleFontFileReplacer { ...@@ -416,12 +416,11 @@ impl ImportMappingReplacement for NextFontGoogleFontFileReplacer {
} }
let font_virtual_path = let font_virtual_path =
next_js_file_path("internal/font/google".into()).join(format!("/{name}.{ext}").into()); next_js_file_path(rcstr!("internal/font/google")).join(format!("/{name}.{ext}").into());
// doesn't seem ideal to download the font into a string, but probably doesn't // doesn't seem ideal to download the font into a string, but probably doesn't
// really matter either. // really matter either.
let Some(font) = fetch_from_google_fonts(Vc::cell(url.into()), font_virtual_path).await? let Some(font) = fetch_from_google_fonts(url.into(), font_virtual_path).await? else {
else {
return Ok(ImportMapResult::Result(ResolveResult::unresolvable()).cell()); return Ok(ImportMapResult::Result(ResolveResult::unresolvable()).cell());
}; };
...@@ -440,7 +439,7 @@ impl ImportMappingReplacement for NextFontGoogleFontFileReplacer { ...@@ -440,7 +439,7 @@ impl ImportMappingReplacement for NextFontGoogleFontFileReplacer {
async fn load_font_data(project_root: ResolvedVc<FileSystemPath>) -> Result<Vc<FontData>> { async fn load_font_data(project_root: ResolvedVc<FileSystemPath>) -> Result<Vc<FontData>> {
let data: FontData = load_next_js_templateon( let data: FontData = load_next_js_templateon(
project_root, project_root,
"dist/compiled/@next/font/dist/google/font-data.json".into(), rcstr!("dist/compiled/@next/font/dist/google/font-data.json"),
) )
.await?; .await?;
...@@ -453,7 +452,7 @@ async fn load_font_data(project_root: ResolvedVc<FileSystemPath>) -> Result<Vc<F ...@@ -453,7 +452,7 @@ async fn load_font_data(project_root: ResolvedVc<FileSystemPath>) -> Result<Vc<F
async fn update_google_stylesheet( async fn update_google_stylesheet(
stylesheet: Vc<RcStr>, stylesheet: Vc<RcStr>,
options: Vc<NextFontGoogleOptions>, options: Vc<NextFontGoogleOptions>,
scoped_font_family: Vc<RcStr>, scoped_font_family: RcStr,
has_size_adjust: Vc<bool>, has_size_adjust: Vc<bool>,
) -> Result<Vc<RcStr>> { ) -> Result<Vc<RcStr>> {
let options = &*options.await?; let options = &*options.await?;
...@@ -462,7 +461,7 @@ async fn update_google_stylesheet( ...@@ -462,7 +461,7 @@ async fn update_google_stylesheet(
// TODO: Do this more resiliently, e.g. transforming an swc ast // TODO: Do this more resiliently, e.g. transforming an swc ast
let mut stylesheet = stylesheet.await?.replace( let mut stylesheet = stylesheet.await?.replace(
&format!("font-family: '{}';", &options.font_family), &format!("font-family: '{}';", &options.font_family),
&format!("font-family: '{}';", &*scoped_font_family.await?), &format!("font-family: '{scoped_font_family}';"),
); );
let font_files = find_font_files_in_css( let font_files = find_font_files_in_css(
...@@ -541,7 +540,7 @@ async fn get_stylesheet_url_from_options( ...@@ -541,7 +540,7 @@ async fn get_stylesheet_url_from_options(
use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv}; use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv};
let env = CommandLineProcessEnv::new(); let env = CommandLineProcessEnv::new();
if let Some(url) = &*env.read("TURBOPACK_TEST_ONLY_MOCK_SERVER".into()).await? { if let Some(url) = &*env.read(rcstr!("TURBOPACK_TEST_ONLY_MOCK_SERVER")).await? {
css_url = Some(format!("{url}/css2")); css_url = Some(format!("{url}/css2"));
} }
} }
...@@ -571,7 +570,7 @@ async fn get_font_css_properties( ...@@ -571,7 +570,7 @@ async fn get_font_css_properties(
) -> Result<Vc<FontCssProperties>> { ) -> Result<Vc<FontCssProperties>> {
let options = &*options_vc.await?; let options = &*options_vc.await?;
let scoped_font_family = let scoped_font_family =
&*get_scoped_font_family(FontFamilyType::WebFont.cell(), options_vc.font_family()).await?; get_scoped_font_family(FontFamilyType::WebFont, options_vc.font_family().await?);
let mut font_families = vec![format!("'{}'", scoped_font_family.clone()).into()]; let mut font_families = vec![format!("'{}'", scoped_font_family.clone()).into()];
let font_fallback = &*font_fallback.await?; let font_fallback = &*font_fallback.await?;
...@@ -580,7 +579,7 @@ async fn get_font_css_properties( ...@@ -580,7 +579,7 @@ async fn get_font_css_properties(
font_families.extend_from_slice(fonts); font_families.extend_from_slice(fonts);
} }
FontFallback::Automatic(fallback) => { FontFallback::Automatic(fallback) => {
font_families.push(format!("'{}'", *fallback.scoped_font_family.await?).into()); font_families.push(format!("'{}'", fallback.scoped_font_family).into());
} }
FontFallback::Error => {} FontFallback::Error => {}
} }
...@@ -642,7 +641,7 @@ fn font_file_options_from_query_map(query: &RcStr) -> Result<NextFontGoogleFontF ...@@ -642,7 +641,7 @@ fn font_file_options_from_query_map(query: &RcStr) -> Result<NextFontGoogleFontF
} }
async fn fetch_real_stylesheet( async fn fetch_real_stylesheet(
stylesheet_url: Vc<RcStr>, stylesheet_url: RcStr,
css_virtual_path: Vc<FileSystemPath>, css_virtual_path: Vc<FileSystemPath>,
) -> Result<Option<Vc<RcStr>>> { ) -> Result<Option<Vc<RcStr>>> {
let body = fetch_from_google_fonts(stylesheet_url, css_virtual_path).await?; let body = fetch_from_google_fonts(stylesheet_url, css_virtual_path).await?;
...@@ -651,12 +650,12 @@ async fn fetch_real_stylesheet( ...@@ -651,12 +650,12 @@ async fn fetch_real_stylesheet(
} }
async fn fetch_from_google_fonts( async fn fetch_from_google_fonts(
url: Vc<RcStr>, url: RcStr,
virtual_path: Vc<FileSystemPath>, virtual_path: Vc<FileSystemPath>,
) -> Result<Option<Vc<HttpResponseBody>>> { ) -> Result<Option<Vc<HttpResponseBody>>> {
let result = fetch( let result = fetch(
url, url,
Vc::cell(Some(USER_AGENT_FOR_GOOGLE_FONTS.into())), Some(rcstr!(USER_AGENT_FOR_GOOGLE_FONTS)),
Vc::cell(None), Vc::cell(None),
) )
.await?; .await?;
...@@ -675,13 +674,13 @@ async fn fetch_from_google_fonts( ...@@ -675,13 +674,13 @@ async fn fetch_from_google_fonts(
} }
async fn get_mock_stylesheet( async fn get_mock_stylesheet(
stylesheet_url: Vc<RcStr>, stylesheet_url: RcStr,
mocked_responses_path: &str, mocked_responses_path: &str,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Option<Vc<RcStr>>> { ) -> Result<Option<Vc<RcStr>>> {
let response_path = Path::new(&mocked_responses_path); let response_path = Path::new(&mocked_responses_path);
let mock_fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new( let mock_fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(
"mock".into(), rcstr!("mock"),
response_path response_path
.parent() .parent()
.context("Must be valid path")? .context("Must be valid path")?
...@@ -697,8 +696,8 @@ async fn get_mock_stylesheet( ...@@ -697,8 +696,8 @@ async fn get_mock_stylesheet(
chunking_context, chunking_context,
} = *execution_context.await?; } = *execution_context.await?;
let asset_context = let asset_context =
node_evaluate_asset_context(execution_context, None, None, "next_font".into(), false); node_evaluate_asset_context(execution_context, None, None, rcstr!("next_font"), false);
let loader_path = mock_fs.root().join("loader.js".into()); let loader_path = mock_fs.root().join(rcstr!("loader.js"));
let mocked_response_asset = asset_context let mocked_response_asset = asset_context
.process( .process(
Vc::upcast(VirtualSource::new( Vc::upcast(VirtualSource::new(
...@@ -741,7 +740,7 @@ async fn get_mock_stylesheet( ...@@ -741,7 +740,7 @@ async fn get_mock_stylesheet(
let val: FxHashMap<RcStr, Option<RcStr>> = let val: FxHashMap<RcStr, Option<RcStr>> =
parse_json_with_source_context(val.to_str()?)?; parse_json_with_source_context(val.to_str()?)?;
Ok(val Ok(val
.get(&*stylesheet_url.await?) .get(&stylesheet_url)
.context("url not found")? .context("url not found")?
.clone() .clone()
.map(Vc::cell)) .map(Vc::cell))
......
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, Value, Vc, fxindexset, trace::TraceRawVcs, FxIndexMap, FxIndexSet, NonLocalValue, Value, Vc, fxindexset, trace::TraceRawVcs,
}; };
...@@ -29,17 +29,18 @@ pub(super) struct NextFontGoogleOptions { ...@@ -29,17 +29,18 @@ pub(super) struct NextFontGoogleOptions {
pub subsets: Option<Vec<RcStr>>, pub subsets: Option<Vec<RcStr>>,
} }
impl NextFontGoogleOptions {
pub async fn font_family(self: Vc<Self>) -> Result<RcStr> {
Ok(self.await?.font_family.clone())
}
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl NextFontGoogleOptions { impl NextFontGoogleOptions {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(options: Value<NextFontGoogleOptions>) -> Vc<NextFontGoogleOptions> { pub fn new(options: Value<NextFontGoogleOptions>) -> Vc<NextFontGoogleOptions> {
Self::cell(options.into_value()) Self::cell(options.into_value())
} }
#[turbo_tasks::function]
pub fn font_family(&self) -> Vc<RcStr> {
Vc::cell((*self.font_family).into())
}
} }
#[derive( #[derive(
...@@ -155,7 +156,7 @@ pub(super) fn options_from_request( ...@@ -155,7 +156,7 @@ pub(super) fn options_from_request(
if font_data.styles.len() == 1 { if font_data.styles.len() == 1 {
styles.push(font_data.styles[0].clone()); styles.push(font_data.styles[0].clone());
} else { } else {
styles.push("normal".into()); styles.push(rcstr!("normal"));
} }
} }
...@@ -170,7 +171,7 @@ pub(super) fn options_from_request( ...@@ -170,7 +171,7 @@ pub(super) fn options_from_request(
} }
} }
let display = argument.display.unwrap_or_else(|| "swap".into()); let display = argument.display.unwrap_or_else(|| rcstr!("swap"));
if !ALLOWED_DISPLAY_VALUES.contains(&display.as_str()) { if !ALLOWED_DISPLAY_VALUES.contains(&display.as_str()) {
anyhow::bail!( anyhow::bail!(
...@@ -213,7 +214,7 @@ pub(super) fn options_from_request( ...@@ -213,7 +214,7 @@ pub(super) fn options_from_request(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::FxIndexMap; use turbo_tasks::FxIndexMap;
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
...@@ -280,10 +281,10 @@ mod tests { ...@@ -280,10 +281,10 @@ mod tests {
assert_eq!( assert_eq!(
options_from_request(&request, &data)?, options_from_request(&request, &data)?,
NextFontGoogleOptions { NextFontGoogleOptions {
font_family: "ABeeZee".into(), font_family: rcstr!("ABeeZee"),
weights: FontWeights::Variable, weights: FontWeights::Variable,
styles: vec!["normal".into()], styles: vec![rcstr!("normal")],
display: "swap".into(), display: rcstr!("swap"),
preload: true, preload: true,
selected_variable_axes: None, selected_variable_axes: None,
fallback: None, fallback: None,
...@@ -436,7 +437,7 @@ mod tests { ...@@ -436,7 +437,7 @@ mod tests {
)?; )?;
let options = options_from_request(&request, &data)?; let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec![RcStr::from("italic")]); assert_eq!(options.styles, vec![rcstr!("italic")]);
Ok(()) Ok(())
} }
...@@ -468,7 +469,7 @@ mod tests { ...@@ -468,7 +469,7 @@ mod tests {
)?; )?;
let options = options_from_request(&request, &data)?; let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec![RcStr::from("normal")]); assert_eq!(options.styles, vec![rcstr!("normal")]);
Ok(()) Ok(())
} }
......
...@@ -2,7 +2,7 @@ use anyhow::{Context, Result, bail}; ...@@ -2,7 +2,7 @@ use anyhow::{Context, Result, bail};
use font_fallback::FontFallbackResult; use font_fallback::FontFallbackResult;
use indoc::formatdoc; use indoc::formatdoc;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Value, Vc}; use turbo_tasks::{ResolvedVc, Value, Vc};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
FileContent, FileSystemPath, glob::Glob, json::parse_json_with_source_context, FileContent, FileSystemPath, glob::Glob, json::parse_json_with_source_context,
...@@ -68,9 +68,9 @@ impl NextFontLocalResolvePlugin { ...@@ -68,9 +68,9 @@ impl NextFontLocalResolvePlugin {
impl BeforeResolvePlugin for NextFontLocalResolvePlugin { impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn before_resolve_condition(&self) -> Vc<BeforeResolvePluginCondition> { fn before_resolve_condition(&self) -> Vc<BeforeResolvePluginCondition> {
BeforeResolvePluginCondition::from_request_glob(Glob::new( BeforeResolvePluginCondition::from_request_glob(Glob::new(rcstr!(
"{next,@vercel/turbopack-next/internal}/font/local/*".into(), "{next,@vercel/turbopack-next/internal}/font/local/*"
)) )))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -163,7 +163,7 @@ impl BeforeResolvePlugin for NextFontLocalResolvePlugin { ...@@ -163,7 +163,7 @@ impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
lookup_path.join( lookup_path.join(
format!( format!(
"{}.js", "{}.js",
get_request_id(options_vc.font_family(), request_hash).await? get_request_id(options_vc.font_family().await?, request_hash)
) )
.into(), .into(),
), ),
...@@ -182,7 +182,7 @@ impl BeforeResolvePlugin for NextFontLocalResolvePlugin { ...@@ -182,7 +182,7 @@ impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
let css_virtual_path = lookup_path.join( let css_virtual_path = lookup_path.join(
format!( format!(
"/{}.module.css", "/{}.module.css",
get_request_id(options.font_family(), request_hash).await? get_request_id(options.font_family().await?, request_hash)
) )
.into(), .into(),
); );
...@@ -348,9 +348,9 @@ impl Issue for FontResolvingIssue { ...@@ -348,9 +348,9 @@ impl Issue for FontResolvingIssue {
async fn title(self: Vc<Self>) -> Result<Vc<StyledString>> { async fn title(self: Vc<Self>) -> Result<Vc<StyledString>> {
let this = self.await?; let this = self.await?;
Ok(StyledString::Line(vec![ Ok(StyledString::Line(vec![
StyledString::Text("Font file not found: Can't resolve '".into()), StyledString::Text(rcstr!("Font file not found: Can't resolve '")),
StyledString::Code(this.font_path.owned().await?), StyledString::Code(this.font_path.owned().await?),
StyledString::Text("'".into()), StyledString::Text(rcstr!("'")),
]) ])
.cell()) .cell())
} }
......
...@@ -34,17 +34,18 @@ pub(super) struct NextFontLocalOptions { ...@@ -34,17 +34,18 @@ pub(super) struct NextFontLocalOptions {
pub variable_name: RcStr, pub variable_name: RcStr,
} }
impl NextFontLocalOptions {
pub async fn font_family(self: Vc<Self>) -> Result<RcStr> {
Ok(self.await?.variable_name.clone())
}
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl NextFontLocalOptions { impl NextFontLocalOptions {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(options: Value<NextFontLocalOptions>) -> Vc<NextFontLocalOptions> { pub fn new(options: Value<NextFontLocalOptions>) -> Vc<NextFontLocalOptions> {
Self::cell(options.into_value()) Self::cell(options.into_value())
} }
#[turbo_tasks::function]
pub fn font_family(&self) -> Vc<RcStr> {
Vc::cell(self.variable_name.clone())
}
} }
/// Describes an individual font file's path, weight, style, etc. Derived from /// Describes an individual font file's path, weight, style, etc. Derived from
...@@ -204,6 +205,7 @@ pub(super) fn options_from_request(request: &NextFontLocalRequest) -> Result<Nex ...@@ -204,6 +205,7 @@ pub(super) fn options_from_request(request: &NextFontLocalRequest) -> Result<Nex
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{NextFontLocalOptions, options_from_request}; use super::{NextFontLocalOptions, options_from_request};
...@@ -231,19 +233,19 @@ mod tests { ...@@ -231,19 +233,19 @@ mod tests {
options_from_request(&request)?, options_from_request(&request)?,
NextFontLocalOptions { NextFontLocalOptions {
fonts: FontDescriptors::One(FontDescriptor { fonts: FontDescriptors::One(FontDescriptor {
path: "./Roboto-Regular.ttf".into(), path: rcstr!("./Roboto-Regular.ttf"),
weight: None, weight: None,
style: None, style: None,
ext: "ttf".into(), ext: rcstr!("ttf"),
}), }),
default_style: None, default_style: None,
default_weight: None, default_weight: None,
display: "swap".into(), display: rcstr!("swap"),
preload: true, preload: true,
fallback: None, fallback: None,
adjust_font_fallback: AdjustFontFallback::Arial, adjust_font_fallback: AdjustFontFallback::Arial,
variable: None, variable: None,
variable_name: "myFont".into() variable_name: rcstr!("myFont")
}, },
); );
...@@ -279,26 +281,26 @@ mod tests { ...@@ -279,26 +281,26 @@ mod tests {
NextFontLocalOptions { NextFontLocalOptions {
fonts: FontDescriptors::Many(vec![ fonts: FontDescriptors::Many(vec![
FontDescriptor { FontDescriptor {
path: "./Roboto-Regular.ttf".into(), path: rcstr!("./Roboto-Regular.ttf"),
weight: Some(FontWeight::Fixed("400".into())), weight: Some(FontWeight::Fixed(rcstr!("400"))),
style: Some("normal".into()), style: Some(rcstr!("normal")),
ext: "ttf".into(), ext: rcstr!("ttf"),
}, },
FontDescriptor { FontDescriptor {
path: "./Roboto-Italic.ttf".into(), path: rcstr!("./Roboto-Italic.ttf"),
weight: Some(FontWeight::Fixed("400".into())), weight: Some(FontWeight::Fixed(rcstr!("400"))),
style: None, style: None,
ext: "ttf".into(), ext: rcstr!("ttf"),
} }
]), ]),
default_weight: Some(FontWeight::Fixed("300".into())), default_weight: Some(FontWeight::Fixed(rcstr!("300"))),
default_style: Some("italic".into()), default_style: Some(rcstr!("italic")),
display: "swap".into(), display: rcstr!("swap"),
preload: true, preload: true,
fallback: None, fallback: None,
adjust_font_fallback: AdjustFontFallback::Arial, adjust_font_fallback: AdjustFontFallback::Arial,
variable: None, variable: None,
variable_name: "myFont".into() variable_name: rcstr!("myFont")
}, },
); );
...@@ -360,19 +362,19 @@ mod tests { ...@@ -360,19 +362,19 @@ mod tests {
options_from_request(&request)?, options_from_request(&request)?,
NextFontLocalOptions { NextFontLocalOptions {
fonts: FontDescriptors::One(FontDescriptor { fonts: FontDescriptors::One(FontDescriptor {
path: "./Roboto-Regular.woff".into(), path: rcstr!("./Roboto-Regular.woff"),
weight: Some(FontWeight::Fixed("500".into())), weight: Some(FontWeight::Fixed(rcstr!("500"))),
style: Some("italic".into()), style: Some(rcstr!("italic")),
ext: "woff".into(), ext: rcstr!("woff"),
}), }),
default_style: Some("italic".into()), default_style: Some(rcstr!("italic")),
default_weight: Some(FontWeight::Fixed("500".into())), default_weight: Some(FontWeight::Fixed(rcstr!("500"))),
display: "optional".into(), display: rcstr!("optional"),
preload: false, preload: false,
fallback: Some(vec!["Fallback".into()]), fallback: Some(vec![rcstr!("Fallback")]),
adjust_font_fallback: AdjustFontFallback::TimesNewRoman, adjust_font_fallback: AdjustFontFallback::TimesNewRoman,
variable: Some("myvar".into()), variable: Some(rcstr!("myvar")),
variable_name: "myFont".into() variable_name: rcstr!("myFont")
}, },
); );
......
...@@ -18,7 +18,7 @@ pub(super) async fn build_stylesheet( ...@@ -18,7 +18,7 @@ pub(super) async fn build_stylesheet(
css_properties: Vc<FontCssProperties>, css_properties: Vc<FontCssProperties>,
) -> Result<Vc<RcStr>> { ) -> Result<Vc<RcStr>> {
let scoped_font_family = let scoped_font_family =
get_scoped_font_family(FontFamilyType::WebFont.cell(), options.font_family()); get_scoped_font_family(FontFamilyType::WebFont, options.font_family().await?);
Ok(Vc::cell( Ok(Vc::cell(
formatdoc!( formatdoc!(
...@@ -39,7 +39,7 @@ pub(super) async fn build_stylesheet( ...@@ -39,7 +39,7 @@ pub(super) async fn build_stylesheet(
/// Builds a string of `@font-face` definitions for each local font file /// Builds a string of `@font-face` definitions for each local font file
#[turbo_tasks::function] #[turbo_tasks::function]
pub(super) async fn build_font_face_definitions( pub(super) async fn build_font_face_definitions(
scoped_font_family: Vc<RcStr>, scoped_font_family: RcStr,
options: Vc<NextFontLocalOptions>, options: Vc<NextFontLocalOptions>,
has_size_adjust: Vc<bool>, has_size_adjust: Vc<bool>,
) -> Result<Vc<RcStr>> { ) -> Result<Vc<RcStr>> {
...@@ -70,7 +70,7 @@ pub(super) async fn build_font_face_definitions( ...@@ -70,7 +70,7 @@ pub(super) async fn build_font_face_definitions(
{}{} {}{}
}} }}
"#, "#,
*scoped_font_family.await?, scoped_font_family,
query_str, query_str,
ext_to_format(&font.ext)?, ext_to_format(&font.ext)?,
options.display, options.display,
......
...@@ -17,7 +17,7 @@ pub(super) async fn build_font_family_string( ...@@ -17,7 +17,7 @@ pub(super) async fn build_font_family_string(
let mut font_families = vec![ let mut font_families = vec![
format!( format!(
"'{}'", "'{}'",
*get_scoped_font_family(FontFamilyType::WebFont.cell(), options.font_family(),).await? get_scoped_font_family(FontFamilyType::WebFont, options.font_family().await?)
) )
.into(), .into(),
]; ];
...@@ -25,7 +25,7 @@ pub(super) async fn build_font_family_string( ...@@ -25,7 +25,7 @@ pub(super) async fn build_font_family_string(
for font_fallback in &*font_fallbacks.await? { for font_fallback in &*font_fallbacks.await? {
match &*font_fallback.await? { match &*font_fallback.await? {
FontFallback::Automatic(fallback) => { FontFallback::Automatic(fallback) => {
font_families.push(format!("'{}'", *fallback.scoped_font_family.await?).into()); font_families.push(format!("'{}'", fallback.scoped_font_family).into());
} }
FontFallback::Manual(fallbacks) => { FontFallback::Manual(fallbacks) => {
font_families.extend_from_slice(fallbacks); font_families.extend_from_slice(fallbacks);
......
...@@ -38,8 +38,8 @@ pub(crate) async fn build_fallback_definition(fallbacks: Vc<FontFallbacks>) -> R ...@@ -38,8 +38,8 @@ pub(crate) async fn build_fallback_definition(fallbacks: Vc<FontFallbacks>) -> R
{} {}
}} }}
"#, "#,
fallback.scoped_font_family.await?, fallback.scoped_font_family,
fallback.local_font_family.await?, fallback.local_font_family,
override_properties override_properties
)); ));
} }
......
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use serde::Deserialize; use serde::Deserialize;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{FileSystemPath, json::parse_json_with_source_context}; use turbo_tasks_fs::{FileSystemPath, json::parse_json_with_source_context};
use turbo_tasks_hash::hash_xxh3_hash64; use turbo_tasks_hash::hash_xxh3_hash64;
...@@ -46,31 +46,21 @@ pub(crate) enum FontFamilyType { ...@@ -46,31 +46,21 @@ pub(crate) enum FontFamilyType {
/// e.g. `__Roboto_Fallback_c123b8` /// e.g. `__Roboto_Fallback_c123b8`
/// * `font_family_name` - The font name to scope, e.g. `Roboto` /// * `font_family_name` - The font name to scope, e.g. `Roboto`
/// * `request_hash` - The hash value of the font request /// * `request_hash` - The hash value of the font request
#[turbo_tasks::function] pub(crate) fn get_scoped_font_family(ty: FontFamilyType, font_family_name: RcStr) -> RcStr {
pub(crate) async fn get_scoped_font_family( match ty {
ty: Vc<FontFamilyType>, FontFamilyType::WebFont => font_family_name,
font_family_name: Vc<RcStr>, FontFamilyType::Fallback => format!("{font_family_name} Fallback").into(),
) -> Result<Vc<RcStr>> { }
let font_family_base = font_family_name.await?.to_string();
let font_family_name = match &*ty.await? {
FontFamilyType::WebFont => font_family_base,
FontFamilyType::Fallback => format!("{font_family_base} Fallback"),
};
Ok(Vc::cell(font_family_name.into()))
} }
/// Returns a [Vc] for [String] uniquely identifying the request for the font. /// Returns a [RcStr] for [String] uniquely identifying the request for the font.
#[turbo_tasks::function] pub fn get_request_id(font_family: RcStr, request_hash: u32) -> RcStr {
pub async fn get_request_id(font_family: Vc<RcStr>, request_hash: u32) -> Result<Vc<RcStr>> {
Ok(Vc::cell(
format!( format!(
"{}_{:x?}", "{}_{:x?}",
font_family.await?.to_lowercase().replace(' ', "_"), font_family.to_lowercase().replace(' ', "_"),
request_hash request_hash
) )
.into(), .into()
))
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
...@@ -98,12 +88,12 @@ pub(crate) async fn can_use_next_font( ...@@ -98,12 +88,12 @@ pub(crate) async fn can_use_next_font(
NextFontIssue { NextFontIssue {
path: path.to_resolved().await?, path: path.to_resolved().await?,
title: StyledString::Line(vec![ title: StyledString::Line(vec![
StyledString::Code("next/font:".into()), StyledString::Code(rcstr!("next/font:")),
StyledString::Text(" error:".into()), StyledString::Text(rcstr!(" error:")),
]) ])
.resolved_cell(), .resolved_cell(),
description: StyledString::Line(vec![ description: StyledString::Line(vec![
StyledString::Text("Cannot be used within ".into()), StyledString::Text(rcstr!("Cannot be used within ")),
StyledString::Code(request.path), StyledString::Code(request.path),
]) ])
.resolved_cell(), .resolved_cell(),
......
...@@ -2,7 +2,7 @@ use std::collections::BTreeMap; ...@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc, fxindexmap}; use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc, fxindexmap};
use turbo_tasks_fs::{FileSystem, FileSystemPath}; use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -333,7 +333,7 @@ pub async fn get_next_server_import_map( ...@@ -333,7 +333,7 @@ pub async fn get_next_server_import_map(
import_map.insert_exact_alias( import_map.insert_exact_alias(
"styled-jsx/style", "styled-jsx/style",
ImportMapping::External( ImportMapping::External(
Some("styled-jsx/style.js".into()), Some(rcstr!("styled-jsx/style.js")),
ExternalType::CommonJs, ExternalType::CommonJs,
ExternalTraced::Traced, ExternalTraced::Traced,
) )
...@@ -456,7 +456,7 @@ pub async fn get_next_edge_import_map( ...@@ -456,7 +456,7 @@ pub async fn get_next_edge_import_map(
.await?; .await?;
let ty = ty.into_value(); let ty = ty.into_value();
match ty { match &ty {
ServerContextType::Pages { .. } ServerContextType::Pages { .. }
| ServerContextType::PagesData { .. } | ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. } | ServerContextType::PagesApi { .. }
...@@ -486,7 +486,7 @@ pub async fn get_next_edge_import_map( ...@@ -486,7 +486,7 @@ pub async fn get_next_edge_import_map(
insert_next_server_special_aliases( insert_next_server_special_aliases(
&mut import_map, &mut import_map,
project_path, project_path,
ty, ty.clone(),
NextRuntime::Edge, NextRuntime::Edge,
next_config, next_config,
) )
...@@ -607,14 +607,14 @@ async fn insert_next_server_special_aliases( ...@@ -607,14 +607,14 @@ async fn insert_next_server_special_aliases(
.resolved_cell(), .resolved_cell(),
); );
match ty { match &ty {
ServerContextType::Pages { .. } | ServerContextType::PagesApi { .. } => {} ServerContextType::Pages { .. } | ServerContextType::PagesApi { .. } => {}
ServerContextType::PagesData { .. } => {} ServerContextType::PagesData { .. } => {}
// the logic closely follows the one in createRSCAliases in webpack-config.ts // the logic closely follows the one in createRSCAliases in webpack-config.ts
ServerContextType::AppSSR { app_dir } ServerContextType::AppSSR { app_dir }
| ServerContextType::AppRSC { app_dir, .. } | ServerContextType::AppRSC { app_dir, .. }
| ServerContextType::AppRoute { app_dir, .. } => { | ServerContextType::AppRoute { app_dir, .. } => {
let next_package = get_next_package(*app_dir).to_resolved().await?; let next_package = get_next_package(**app_dir).to_resolved().await?;
import_map.insert_exact_alias( import_map.insert_exact_alias(
"styled-jsx", "styled-jsx",
request_to_import_mapping(next_package, "styled-jsx"), request_to_import_mapping(next_package, "styled-jsx"),
...@@ -624,10 +624,10 @@ async fn insert_next_server_special_aliases( ...@@ -624,10 +624,10 @@ async fn insert_next_server_special_aliases(
request_to_import_mapping(next_package, "styled-jsx/*"), request_to_import_mapping(next_package, "styled-jsx/*"),
); );
rsc_aliases(import_map, project_path, ty, runtime, next_config).await?; rsc_aliases(import_map, project_path, ty.clone(), runtime, next_config).await?;
} }
ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => { ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => {
rsc_aliases(import_map, project_path, ty, runtime, next_config).await?; rsc_aliases(import_map, project_path, ty.clone(), runtime, next_config).await?;
} }
} }
...@@ -636,7 +636,7 @@ async fn insert_next_server_special_aliases( ...@@ -636,7 +636,7 @@ async fn insert_next_server_special_aliases(
// context, it'll resolve to the noop where it's allowed, or aliased into // context, it'll resolve to the noop where it's allowed, or aliased into
// the error which throws a runtime error. This works with in combination of // the error which throws a runtime error. This works with in combination of
// build-time error as well, refer https://github.com/vercel/next.js/blob/0060de1c4905593ea875fa7250d4b5d5ce10897d/packages/next-swc/crates/next-core/src/next_server/context.rs#L103 // build-time error as well, refer https://github.com/vercel/next.js/blob/0060de1c4905593ea875fa7250d4b5d5ce10897d/packages/next-swc/crates/next-core/src/next_server/context.rs#L103
match ty { match &ty {
ServerContextType::Pages { .. } => { ServerContextType::Pages { .. } => {
insert_exact_alias_map( insert_exact_alias_map(
import_map, import_map,
...@@ -1014,7 +1014,7 @@ pub async fn get_next_package(context_directory: Vc<FileSystemPath>) -> Result<V ...@@ -1014,7 +1014,7 @@ pub async fn get_next_package(context_directory: Vc<FileSystemPath>) -> Result<V
let result = resolve( let result = resolve(
context_directory, context_directory,
Value::new(ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined)), Value::new(ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined)),
Request::parse(Value::new(Pattern::Constant("next/package.json".into()))), Request::parse(Value::new(Pattern::Constant(rcstr!("next/package.json")))),
node_cjs_resolve_options(context_directory.root()), node_cjs_resolve_options(context_directory.root()),
); );
let source = result let source = result
...@@ -1113,7 +1113,7 @@ fn insert_package_alias( ...@@ -1113,7 +1113,7 @@ fn insert_package_alias(
) { ) {
import_map.insert_wildcard_alias( import_map.insert_wildcard_alias(
prefix, prefix,
ImportMapping::PrimaryAlternative("./*".into(), Some(package_root)).resolved_cell(), ImportMapping::PrimaryAlternative(rcstr!("./*"), Some(package_root)).resolved_cell(),
); );
} }
......
...@@ -2,7 +2,7 @@ use std::io::Write; ...@@ -2,7 +2,7 @@ use std::io::Write;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use serde::Serialize; use serde::Serialize;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc, fxindexmap}; use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc, fxindexmap};
use turbo_tasks_fs::{File, FileSystemPath, rope::RopeBuilder}; use turbo_tasks_fs::{File, FileSystemPath, rope::RopeBuilder};
use turbopack_core::{ use turbopack_core::{
...@@ -32,18 +32,18 @@ pub struct PageSsrEntryModule { ...@@ -32,18 +32,18 @@ pub struct PageSsrEntryModule {
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn create_page_ssr_entry_module( pub async fn create_page_ssr_entry_module(
pathname: Vc<RcStr>, pathname: RcStr,
reference_type: Value<ReferenceType>, reference_type: Value<ReferenceType>,
project_root: Vc<FileSystemPath>, project_root: Vc<FileSystemPath>,
ssr_module_context: Vc<Box<dyn AssetContext>>, ssr_module_context: Vc<Box<dyn AssetContext>>,
source: Vc<Box<dyn Source>>, source: Vc<Box<dyn Source>>,
next_original_name: Vc<RcStr>, next_original_name: RcStr,
pages_structure: Vc<PagesStructure>, pages_structure: Vc<PagesStructure>,
runtime: NextRuntime, runtime: NextRuntime,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
) -> Result<Vc<PageSsrEntryModule>> { ) -> Result<Vc<PageSsrEntryModule>> {
let definition_page = &*next_original_name.await?; let definition_page = next_original_name;
let definition_pathname = &*pathname.await?; let definition_pathname = pathname;
let ssr_module = ssr_module_context let ssr_module = ssr_module_context
.process(source, reference_type.clone()) .process(source, reference_type.clone())
...@@ -69,20 +69,20 @@ pub async fn create_page_ssr_entry_module( ...@@ -69,20 +69,20 @@ pub async fn create_page_ssr_entry_module(
_ => bail!("Invalid path type"), _ => bail!("Invalid path type"),
}; };
const INNER: &str = "INNER_PAGE"; let inner = rcstr!("INNER_PAGE");
const INNER_DOCUMENT: &str = "INNER_DOCUMENT"; let inner_document = rcstr!("INNER_DOCUMENT");
const INNER_APP: &str = "INNER_APP"; let inner_app = rcstr!("INNER_APP");
let mut replacements = fxindexmap! { let mut replacements = fxindexmap! {
"VAR_DEFINITION_PAGE" => definition_page.clone(), "VAR_DEFINITION_PAGE" => definition_page.clone(),
"VAR_DEFINITION_PATHNAME" => definition_pathname.clone(), "VAR_DEFINITION_PATHNAME" => definition_pathname.clone(),
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => inner.clone(),
}; };
if reference_type == ReferenceType::Entry(EntryReferenceSubType::Page) { if reference_type == ReferenceType::Entry(EntryReferenceSubType::Page) {
replacements.insert("VAR_MODULE_DOCUMENT", INNER_DOCUMENT.into()); replacements.insert("VAR_MODULE_DOCUMENT", inner_document.clone());
replacements.insert("VAR_MODULE_APP", INNER_APP.into()); replacements.insert("VAR_MODULE_APP", inner_app.clone());
} }
// Load the file from the next.js codebase. // Load the file from the next.js codebase.
...@@ -99,7 +99,7 @@ pub async fn create_page_ssr_entry_module( ...@@ -99,7 +99,7 @@ pub async fn create_page_ssr_entry_module(
// instrumentation file conflicts with a page also labeled // instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method. // /instrumentation) hoist the `register` method.
if reference_type == ReferenceType::Entry(EntryReferenceSubType::Page) if reference_type == ReferenceType::Entry(EntryReferenceSubType::Page)
&& (*definition_page == "/instrumentation" || *definition_page == "/src/instrumentation") && (definition_page == "/instrumentation" || definition_page == "/src/instrumentation")
{ {
let file = &*file_content_rope(source.content().file_content()).await?; let file = &*file_content_rope(source.content().file_content()).await?;
...@@ -120,7 +120,7 @@ pub async fn create_page_ssr_entry_module( ...@@ -120,7 +120,7 @@ pub async fn create_page_ssr_entry_module(
} }
let mut inner_assets = fxindexmap! { let mut inner_assets = fxindexmap! {
INNER.into() => ssr_module, inner => ssr_module,
}; };
let pages_structure_ref = pages_structure.await?; let pages_structure_ref = pages_structure.await?;
...@@ -141,8 +141,8 @@ pub async fn create_page_ssr_entry_module( ...@@ -141,8 +141,8 @@ pub async fn create_page_ssr_entry_module(
) )
.to_resolved() .to_resolved()
.await?; .await?;
inner_assets.insert(INNER_DOCUMENT.into(), document_module); inner_assets.insert(inner_document, document_module);
inner_assets.insert(INNER_APP.into(), app_module); inner_assets.insert(inner_app, app_module);
(Some(app_module), Some(document_module)) (Some(app_module), Some(document_module))
} else { } else {
(None, None) (None, None)
...@@ -244,8 +244,8 @@ async fn wrap_edge_page( ...@@ -244,8 +244,8 @@ async fn wrap_edge_page(
"nextConfig" => serde_json::to_string(next_config_val)?.into(), "nextConfig" => serde_json::to_string(next_config_val)?.into(),
"dev" => serde_json::Value::Bool(dev).to_string().into(), "dev" => serde_json::Value::Bool(dev).to_string().into(),
"pageRouteModuleOptions" => serde_json::to_string(&get_route_module_options(page.clone(), pathname.clone()))?.into(), "pageRouteModuleOptions" => serde_json::to_string(&get_route_module_options(page.clone(), pathname.clone()))?.into(),
"errorRouteModuleOptions" => serde_json::to_string(&get_route_module_options("/_error".into(), "/_error".into()))?.into(), "errorRouteModuleOptions" => serde_json::to_string(&get_route_module_options(rcstr!("/_error"), rcstr!("/_error")))?.into(),
"user500RouteModuleOptions" => serde_json::to_string(&get_route_module_options("/500".into(), "/500".into()))?.into(), "user500RouteModuleOptions" => serde_json::to_string(&get_route_module_options(rcstr!("/500"), rcstr!("/500")))?.into(),
}, },
fxindexmap! { fxindexmap! {
// TODO // TODO
...@@ -322,12 +322,12 @@ struct RouteDefinition { ...@@ -322,12 +322,12 @@ struct RouteDefinition {
fn get_route_module_options(page: RcStr, pathname: RcStr) -> PartialRouteModuleOptions { fn get_route_module_options(page: RcStr, pathname: RcStr) -> PartialRouteModuleOptions {
PartialRouteModuleOptions { PartialRouteModuleOptions {
definition: RouteDefinition { definition: RouteDefinition {
kind: "PAGES".into(), kind: rcstr!("PAGES"),
page, page,
pathname, pathname,
// The following aren't used in production. // The following aren't used in production.
bundle_path: "".into(), bundle_path: rcstr!(""),
filename: "".into(), filename: rcstr!(""),
}, },
} }
} }
use std::iter::once; use std::iter::once;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc}; use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::{EnvMap, ProcessEnv}; use turbo_tasks_env::{EnvMap, ProcessEnv};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -79,7 +79,7 @@ use crate::{ ...@@ -79,7 +79,7 @@ use crate::{
}; };
#[turbo_tasks::value(shared, serialization = "auto_for_input")] #[turbo_tasks::value(shared, serialization = "auto_for_input")]
#[derive(Debug, Copy, Clone, Hash)] #[derive(Debug, Clone, Hash)]
pub enum ServerContextType { pub enum ServerContextType {
Pages { Pages {
pages_dir: ResolvedVc<FileSystemPath>, pages_dir: ResolvedVc<FileSystemPath>,
...@@ -95,20 +95,20 @@ pub enum ServerContextType { ...@@ -95,20 +95,20 @@ pub enum ServerContextType {
}, },
AppRSC { AppRSC {
app_dir: ResolvedVc<FileSystemPath>, app_dir: ResolvedVc<FileSystemPath>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
client_transition: Option<ResolvedVc<Box<dyn Transition>>>, client_transition: Option<ResolvedVc<Box<dyn Transition>>>,
}, },
AppRoute { AppRoute {
app_dir: ResolvedVc<FileSystemPath>, app_dir: ResolvedVc<FileSystemPath>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
}, },
Middleware { Middleware {
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
}, },
Instrumentation { Instrumentation {
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>, ecmascript_client_reference_transition_name: Option<RcStr>,
}, },
} }
...@@ -133,8 +133,13 @@ pub async fn get_server_resolve_options_context( ...@@ -133,8 +133,13 @@ pub async fn get_server_resolve_options_context(
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> { ) -> Result<Vc<ResolveOptionsContext>> {
let next_server_import_map = let next_server_import_map = get_next_server_import_map(
get_next_server_import_map(*project_path, ty, next_config, mode, execution_context) *project_path,
ty.clone(),
next_config,
mode,
execution_context,
)
.to_resolved() .to_resolved()
.await?; .await?;
let foreign_code_context_condition = let foreign_code_context_condition =
...@@ -154,7 +159,7 @@ pub async fn get_server_resolve_options_context( ...@@ -154,7 +159,7 @@ pub async fn get_server_resolve_options_context(
// Always load these predefined packages as external. // Always load these predefined packages as external.
let mut external_packages: Vec<RcStr> = load_next_js_templateon( let mut external_packages: Vec<RcStr> = load_next_js_templateon(
project_path, project_path,
"dist/lib/server-external-packages.json".into(), rcstr!("dist/lib/server-external-packages.json"),
) )
.await?; .await?;
...@@ -209,7 +214,7 @@ pub async fn get_server_resolve_options_context( ...@@ -209,7 +214,7 @@ pub async fn get_server_resolve_options_context(
); );
if ty.supports_react_server() { if ty.supports_react_server() {
custom_conditions.push("react-server".into()); custom_conditions.push(rcstr!("react-server"));
}; };
let external_cjs_modules_plugin = if *next_config.bundle_pages_router_dependencies().await? { let external_cjs_modules_plugin = if *next_config.bundle_pages_router_dependencies().await? {
...@@ -229,11 +234,11 @@ pub async fn get_server_resolve_options_context( ...@@ -229,11 +234,11 @@ pub async fn get_server_resolve_options_context(
.to_resolved() .to_resolved()
.await?; .await?;
let next_node_shared_runtime_plugin = let next_node_shared_runtime_plugin =
NextNodeSharedRuntimeResolvePlugin::new(*project_path, Value::new(ty)) NextNodeSharedRuntimeResolvePlugin::new(*project_path, Value::new(ty.clone()))
.to_resolved() .to_resolved()
.await?; .await?;
let mut before_resolve_plugins = match ty { let mut before_resolve_plugins = match &ty {
ServerContextType::Pages { .. } ServerContextType::Pages { .. }
| ServerContextType::AppSSR { .. } | ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. } => { | ServerContextType::AppRSC { .. } => {
...@@ -415,7 +420,7 @@ pub async fn get_server_module_options_context( ...@@ -415,7 +420,7 @@ pub async fn get_server_module_options_context(
let next_mode = mode.await?; let next_mode = mode.await?;
let mut next_server_rules = get_next_server_transforms_rules( let mut next_server_rules = get_next_server_transforms_rules(
next_config, next_config,
ty.into_value(), ty.clone().into_value(),
mode, mode,
false, false,
next_runtime, next_runtime,
...@@ -424,7 +429,7 @@ pub async fn get_server_module_options_context( ...@@ -424,7 +429,7 @@ pub async fn get_server_module_options_context(
.await?; .await?;
let mut foreign_next_server_rules = get_next_server_transforms_rules( let mut foreign_next_server_rules = get_next_server_transforms_rules(
next_config, next_config,
ty.into_value(), ty.clone().into_value(),
mode, mode,
true, true,
next_runtime, next_runtime,
...@@ -432,7 +437,7 @@ pub async fn get_server_module_options_context( ...@@ -432,7 +437,7 @@ pub async fn get_server_module_options_context(
) )
.await?; .await?;
let mut internal_custom_rules = get_next_server_internal_transforms_rules( let mut internal_custom_rules = get_next_server_internal_transforms_rules(
ty.into_value(), ty.clone().into_value(),
next_config.mdx_rs().await?.is_some(), next_config.mdx_rs().await?.is_some(),
) )
.await?; .await?;
...@@ -478,7 +483,7 @@ pub async fn get_server_module_options_context( ...@@ -478,7 +483,7 @@ pub async fn get_server_module_options_context(
conditions conditions
.iter() .iter()
.cloned() .cloned()
.chain(once("foreign".into())) .chain(once(rcstr!("foreign")))
.collect(), .collect(),
) )
.await?; .await?;
...@@ -983,9 +988,9 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -983,9 +988,9 @@ pub async fn get_server_chunking_context_with_client_assets(
mode: Vc<NextMode>, mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>, root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>, node_root: ResolvedVc<FileSystemPath>,
node_root_to_root_path: ResolvedVc<RcStr>, node_root_to_root_path: RcStr,
client_root: ResolvedVc<FileSystemPath>, client_root: ResolvedVc<FileSystemPath>,
asset_prefix: ResolvedVc<Option<RcStr>>, asset_prefix: Option<RcStr>,
environment: ResolvedVc<Environment>, environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>, module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>, turbo_minify: Vc<bool>,
...@@ -1002,11 +1007,11 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -1002,11 +1007,11 @@ pub async fn get_server_chunking_context_with_client_assets(
node_root_to_root_path, node_root_to_root_path,
client_root, client_root,
node_root node_root
.join("server/chunks/ssr".into()) .join(rcstr!("server/chunks/ssr"))
.to_resolved() .to_resolved()
.await?, .await?,
client_root client_root
.join("static/media".into()) .join(rcstr!("static/media"))
.to_resolved() .to_resolved()
.await?, .await?,
environment, environment,
...@@ -1058,7 +1063,7 @@ pub async fn get_server_chunking_context( ...@@ -1058,7 +1063,7 @@ pub async fn get_server_chunking_context(
mode: Vc<NextMode>, mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>, root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>, node_root: ResolvedVc<FileSystemPath>,
node_root_to_root_path: ResolvedVc<RcStr>, node_root_to_root_path: RcStr,
environment: ResolvedVc<Environment>, environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>, module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>, turbo_minify: Vc<bool>,
...@@ -1074,8 +1079,14 @@ pub async fn get_server_chunking_context( ...@@ -1074,8 +1079,14 @@ pub async fn get_server_chunking_context(
node_root, node_root,
node_root_to_root_path, node_root_to_root_path,
node_root, node_root,
node_root.join("server/chunks".into()).to_resolved().await?, node_root
node_root.join("server/assets".into()).to_resolved().await?, .join(rcstr!("server/chunks"))
.to_resolved()
.await?,
node_root
.join(rcstr!("server/assets"))
.to_resolved()
.await?,
environment, environment,
next_mode.runtime_type(), next_mode.runtime_type(),
) )
......
...@@ -86,7 +86,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -86,7 +86,7 @@ pub async fn get_next_server_transforms_rules(
if !foreign_code { if !foreign_code {
rules.push(get_next_page_static_info_assert_rule( rules.push(get_next_page_static_info_assert_rule(
mdx_rs, mdx_rs,
Some(context_ty), Some(context_ty.clone()),
None, None,
)); ));
} }
...@@ -95,7 +95,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -95,7 +95,7 @@ pub async fn get_next_server_transforms_rules(
let cache_kinds = next_config.cache_kinds().to_resolved().await?; let cache_kinds = next_config.cache_kinds().to_resolved().await?;
let mut is_app_dir = false; let mut is_app_dir = false;
let is_server_components = match context_ty { let is_server_components = match &context_ty {
ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => { ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => {
if !foreign_code { if !foreign_code {
rules.push(get_next_disallow_export_all_in_page_rule( rules.push(get_next_disallow_export_all_in_page_rule(
...@@ -109,7 +109,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -109,7 +109,7 @@ pub async fn get_next_server_transforms_rules(
if !foreign_code { if !foreign_code {
rules.push( rules.push(
get_next_pages_transforms_rule( get_next_pages_transforms_rule(
*pages_dir, **pages_dir,
ExportFilter::StripDefaultExport, ExportFilter::StripDefaultExport,
mdx_rs, mdx_rs,
) )
......
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Vc, fxindexmap}; use turbo_tasks::{Vc, fxindexmap};
use turbopack_core::diagnostics::{Diagnostic, DiagnosticPayload}; use turbopack_core::diagnostics::{Diagnostic, DiagnosticPayload};
...@@ -17,7 +17,7 @@ pub struct NextFeatureTelemetry { ...@@ -17,7 +17,7 @@ pub struct NextFeatureTelemetry {
impl NextFeatureTelemetry { impl NextFeatureTelemetry {
pub fn new(feature_name: RcStr, enabled: bool) -> Self { pub fn new(feature_name: RcStr, enabled: bool) -> Self {
NextFeatureTelemetry { NextFeatureTelemetry {
event_name: "EVENT_BUILD_FEATURE_USAGE".into(), event_name: rcstr!("EVENT_BUILD_FEATURE_USAGE"),
feature_name, feature_name,
enabled, enabled,
} }
...@@ -28,7 +28,7 @@ impl NextFeatureTelemetry { ...@@ -28,7 +28,7 @@ impl NextFeatureTelemetry {
impl Diagnostic for NextFeatureTelemetry { impl Diagnostic for NextFeatureTelemetry {
#[turbo_tasks::function] #[turbo_tasks::function]
fn category(&self) -> Vc<RcStr> { fn category(&self) -> Vc<RcStr> {
Vc::cell("NextFeatureTelemetry_category_tbd".into()) Vc::cell(rcstr!("NextFeatureTelemetry_category_tbd"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -57,7 +57,7 @@ pub struct ModuleFeatureTelemetry { ...@@ -57,7 +57,7 @@ pub struct ModuleFeatureTelemetry {
impl ModuleFeatureTelemetry { impl ModuleFeatureTelemetry {
pub fn new(feature_name: RcStr, invocation_count: usize) -> Self { pub fn new(feature_name: RcStr, invocation_count: usize) -> Self {
ModuleFeatureTelemetry { ModuleFeatureTelemetry {
event_name: "EVENT_BUILD_FEATURE_USAGE".into(), event_name: rcstr!("EVENT_BUILD_FEATURE_USAGE"),
feature_name, feature_name,
invocation_count, invocation_count,
} }
...@@ -68,7 +68,7 @@ impl ModuleFeatureTelemetry { ...@@ -68,7 +68,7 @@ impl ModuleFeatureTelemetry {
impl Diagnostic for ModuleFeatureTelemetry { impl Diagnostic for ModuleFeatureTelemetry {
#[turbo_tasks::function] #[turbo_tasks::function]
fn category(&self) -> Vc<RcStr> { fn category(&self) -> Vc<RcStr> {
Vc::cell("ModuleFeatureTelemetry_category_tbd".into()) Vc::cell(rcstr!("ModuleFeatureTelemetry_category_tbd"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use std::io::Write; use std::io::Write;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Value, Vc, fxindexmap}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, Value, Vc, fxindexmap};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
self, File, FileContent, FileSystemPath, FileSystemPathOption, rope::RopeBuilder, self, File, FileContent, FileSystemPath, FileSystemPathOption, rope::RopeBuilder,
...@@ -25,16 +25,12 @@ use crate::{embed_js::next_js_file_path, util::get_asset_path_from_pathname}; ...@@ -25,16 +25,12 @@ use crate::{embed_js::next_js_file_path, util::get_asset_path_from_pathname};
pub async fn create_page_loader_entry_module( pub async fn create_page_loader_entry_module(
client_context: Vc<Box<dyn AssetContext>>, client_context: Vc<Box<dyn AssetContext>>,
entry_asset: Vc<Box<dyn Source>>, entry_asset: Vc<Box<dyn Source>>,
pathname: Vc<RcStr>, pathname: RcStr,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
let mut result = RopeBuilder::default(); let mut result = RopeBuilder::default();
writeln!( writeln!(result, "const PAGE_PATH = {};\n", StringifyJs(&pathname))?;
result,
"const PAGE_PATH = {};\n",
StringifyJs(&*pathname.await?)
)?;
let page_loader_path = next_js_file_path("entry/page-loader.ts".into()); let page_loader_path = next_js_file_path(rcstr!("entry/page-loader.ts"));
let base_code = page_loader_path.read(); let base_code = page_loader_path.read();
if let FileContent::Content(base_file) = &*base_code.await? { if let FileContent::Content(base_file) = &*base_code.await? {
result += base_file.content() result += base_file.content()
...@@ -62,7 +58,7 @@ pub async fn create_page_loader_entry_module( ...@@ -62,7 +58,7 @@ pub async fn create_page_loader_entry_module(
.process( .process(
virtual_source, virtual_source,
Value::new(ReferenceType::Internal(ResolvedVc::cell(fxindexmap! { Value::new(ReferenceType::Internal(ResolvedVc::cell(fxindexmap! {
"PAGE".into() => module, rcstr!("PAGE") => module,
}))), }))),
) )
.module(); .module();
...@@ -72,7 +68,7 @@ pub async fn create_page_loader_entry_module( ...@@ -72,7 +68,7 @@ pub async fn create_page_loader_entry_module(
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct PageLoaderAsset { pub struct PageLoaderAsset {
pub server_root: ResolvedVc<FileSystemPath>, pub server_root: ResolvedVc<FileSystemPath>,
pub pathname: ResolvedVc<RcStr>, pub pathname: RcStr,
pub rebase_prefix_path: ResolvedVc<FileSystemPathOption>, pub rebase_prefix_path: ResolvedVc<FileSystemPathOption>,
pub page_chunks: ResolvedVc<OutputAssets>, pub page_chunks: ResolvedVc<OutputAssets>,
} }
...@@ -82,7 +78,7 @@ impl PageLoaderAsset { ...@@ -82,7 +78,7 @@ impl PageLoaderAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new( pub fn new(
server_root: ResolvedVc<FileSystemPath>, server_root: ResolvedVc<FileSystemPath>,
pathname: ResolvedVc<RcStr>, pathname: RcStr,
rebase_prefix_path: ResolvedVc<FileSystemPathOption>, rebase_prefix_path: ResolvedVc<FileSystemPathOption>,
page_chunks: ResolvedVc<OutputAssets>, page_chunks: ResolvedVc<OutputAssets>,
) -> Vc<Self> { ) -> Vc<Self> {
...@@ -125,11 +121,6 @@ impl PageLoaderAsset { ...@@ -125,11 +121,6 @@ impl PageLoaderAsset {
} }
} }
#[turbo_tasks::function]
fn page_loader_chunk_reference_description() -> Vc<RcStr> {
Vc::cell("page loader chunk".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl OutputAsset for PageLoaderAsset { impl OutputAsset for PageLoaderAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -141,7 +132,7 @@ impl OutputAsset for PageLoaderAsset { ...@@ -141,7 +132,7 @@ impl OutputAsset for PageLoaderAsset {
Ok(root.join( Ok(root.join(
format!( format!(
"static/chunks/pages{}", "static/chunks/pages{}",
get_asset_path_from_pathname(&self.pathname.await?, ".js") get_asset_path_from_pathname(&self.pathname, ".js")
) )
.into(), .into(),
)) ))
...@@ -181,7 +172,7 @@ impl Asset for PageLoaderAsset { ...@@ -181,7 +172,7 @@ impl Asset for PageLoaderAsset {
let content = format!( let content = format!(
"__turbopack_load_page_chunks__({}, {:#})\n", "__turbopack_load_page_chunks__({}, {:#})\n",
StringifyJs(&this.pathname.await?), StringifyJs(&this.pathname),
StringifyJs(&chunks_data) StringifyJs(&chunks_data)
); );
......
...@@ -32,7 +32,7 @@ use swc_core::{ ...@@ -32,7 +32,7 @@ use swc_core::{
}, },
quote, quote,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::{rcstr, RcStr};
use crate::FxIndexMap; use crate::FxIndexMap;
...@@ -2778,7 +2778,7 @@ impl DirectiveVisitor<'_> { ...@@ -2778,7 +2778,7 @@ impl DirectiveVisitor<'_> {
if value == "use cache" { if value == "use cache" {
self.directive = Some(Directive::UseCache { self.directive = Some(Directive::UseCache {
cache_kind: RcStr::from("default"), cache_kind: rcstr!("default"),
}); });
self.increment_cache_usage_counter("default"); self.increment_cache_usage_counter("default");
} else { } else {
......
...@@ -37,8 +37,8 @@ mod tagged_value; ...@@ -37,8 +37,8 @@ mod tagged_value;
/// ///
/// ## Conversion /// ## Conversion
/// ///
/// Converting a `String` or `&str` to an `RcStr` can be perfomed using `.into()` or /// Converting a `String` or `&str` to an `RcStr` can be perfomed using `.into()`,
/// `RcStr::from(...)`: /// `RcStr::from(...)`, or the `rcstr!` macro.
/// ///
/// ``` /// ```
/// # use turbo_rcstr::RcStr; /// # use turbo_rcstr::RcStr;
...@@ -46,9 +46,15 @@ mod tagged_value; ...@@ -46,9 +46,15 @@ mod tagged_value;
/// let s = "foo"; /// let s = "foo";
/// let rc_s1: RcStr = s.into(); /// let rc_s1: RcStr = s.into();
/// let rc_s2 = RcStr::from(s); /// let rc_s2 = RcStr::from(s);
/// let rc_s3 = rcstr!("foo");
/// assert_eq!(rc_s1, rc_s2); /// assert_eq!(rc_s1, rc_s2);
/// ``` /// ```
/// ///
/// Generally speaking you should
/// * use `rcstr!` when converting a `const`-compatible `str`
/// * use `RcStr::from` for readability
/// * use `.into()` when context makes it clear.
///
/// Converting from an [`RcStr`] to a `&str` should be done with [`RcStr::as_str`]. Converting to a /// Converting from an [`RcStr`] to a `&str` should be done with [`RcStr::as_str`]. Converting to a
/// `String` should be done with [`RcStr::into_owned`]. /// `String` should be done with [`RcStr::into_owned`].
/// ///
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
#![feature(arbitrary_self_types_pointers)] #![feature(arbitrary_self_types_pointers)]
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc, duration_span, mark_session_dependent}; use turbo_tasks::{ResolvedVc, Vc, duration_span, mark_session_dependent};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::issue::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString}; use turbopack_core::issue::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString};
...@@ -50,12 +50,10 @@ pub struct OptionProxyConfig(Option<ProxyConfig>); ...@@ -50,12 +50,10 @@ pub struct OptionProxyConfig(Option<ProxyConfig>);
#[turbo_tasks::function(network)] #[turbo_tasks::function(network)]
pub async fn fetch( pub async fn fetch(
url: Vc<RcStr>, url: RcStr,
user_agent: Vc<Option<RcStr>>, user_agent: Option<RcStr>,
proxy_option: Vc<OptionProxyConfig>, proxy_option: Vc<OptionProxyConfig>,
) -> Result<Vc<FetchResult>> { ) -> Result<Vc<FetchResult>> {
let url = &*url.await?;
let user_agent = &*user_agent.await?;
let proxy_option = &*proxy_option.await?; let proxy_option = &*proxy_option.await?;
let client_builder = reqwest::Client::builder(); let client_builder = reqwest::Client::builder();
...@@ -96,7 +94,7 @@ pub async fn fetch( ...@@ -96,7 +94,7 @@ pub async fn fetch(
Err(err) => { Err(err) => {
mark_session_dependent(); mark_session_dependent();
Ok(Vc::cell(Err( Ok(Vc::cell(Err(
FetchError::from_reqwest_error(&err, url).resolved_cell() FetchError::from_reqwest_error(&err, &url).resolved_cell()
))) )))
} }
} }
...@@ -181,7 +179,7 @@ impl Issue for FetchIssue { ...@@ -181,7 +179,7 @@ impl Issue for FetchIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> { fn title(&self) -> Vc<StyledString> {
StyledString::Text("Error while requesting resource".into()).cell() StyledString::Text(rcstr!("Error while requesting resource")).cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
#![cfg(test)] #![cfg(test)]
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbo_tasks_fetch::{FetchErrorKind, fetch}; use turbo_tasks_fetch::{FetchErrorKind, fetch};
use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath}; use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath};
...@@ -18,11 +19,7 @@ async fn basic_get() { ...@@ -18,11 +19,7 @@ async fn basic_get() {
then.status(200).body("responsebody"); then.status(200).body("responsebody");
}); });
let result = &*fetch( let result = &*fetch(server.url("/foo.woff").into(), None, Vc::cell(None))
Vc::cell(server.url("/foo.woff").into()),
Vc::cell(None),
Vc::cell(None),
)
.await .await
.unwrap(); .unwrap();
resource_mock.assert(); resource_mock.assert();
...@@ -51,8 +48,8 @@ async fn sends_user_agent() { ...@@ -51,8 +48,8 @@ async fn sends_user_agent() {
}); });
let result = &*fetch( let result = &*fetch(
Vc::cell(server.url("/foo.woff").into()), server.url("/foo.woff").into(),
Vc::cell(Some("foo".into())), Some(rcstr!("foo")),
Vc::cell(None), Vc::cell(None),
) )
.await .await
...@@ -81,10 +78,10 @@ async fn invalidation_does_not_invalidate() { ...@@ -81,10 +78,10 @@ async fn invalidation_does_not_invalidate() {
then.status(200).body("responsebody"); then.status(200).body("responsebody");
}); });
let url = Vc::cell(server.url("/foo.woff").into()); let url: RcStr = server.url("/foo.woff").into();
let user_agent = Vc::cell(Some("foo".into())); let user_agent = Some(rcstr!("foo"));
let proxy = Vc::cell(None); let proxy = Vc::cell(None);
let result = &*fetch(url, user_agent, proxy).await?; let result = &*fetch(url.clone(), user_agent.clone(), proxy).await?;
resource_mock.assert(); resource_mock.assert();
let Ok(response_vc) = result else { panic!() }; let Ok(response_vc) = result else { panic!() };
...@@ -111,8 +108,8 @@ async fn invalidation_does_not_invalidate() { ...@@ -111,8 +108,8 @@ async fn invalidation_does_not_invalidate() {
#[tokio::test] #[tokio::test]
async fn errors_on_failed_connection() { async fn errors_on_failed_connection() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let url = "https://doesnotexist/foo.woff"; let url = rcstr!("https://doesnotexist/foo.woff");
let result = &*fetch(Vc::cell(url.into()), Vc::cell(None), Vc::cell(None)).await?; let result = &*fetch(url.clone(), None, Vc::cell(None)).await?;
let Err(err_vc) = result else { let Err(err_vc) = result else {
panic!() panic!()
}; };
...@@ -122,7 +119,7 @@ async fn errors_on_failed_connection() { ...@@ -122,7 +119,7 @@ async fn errors_on_failed_connection() {
let issue = err_vc.to_issue(IssueSeverity::Error.into(), get_issue_context()); let issue = err_vc.to_issue(IssueSeverity::Error.into(), get_issue_context());
assert_eq!(*issue.severity().await?, IssueSeverity::Error); assert_eq!(*issue.severity().await?, IssueSeverity::Error);
assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text("There was an issue establishing a connection while requesting https://doesnotexist/foo.woff.".into())); assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text(rcstr!("There was an issue establishing a connection while requesting https://doesnotexist/foo.woff.")));
anyhow::Ok(()) anyhow::Ok(())
}) })
.await.unwrap() .await.unwrap()
...@@ -132,12 +129,8 @@ async fn errors_on_failed_connection() { ...@@ -132,12 +129,8 @@ async fn errors_on_failed_connection() {
async fn errors_on_404() { async fn errors_on_404() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let server = httpmock::MockServer::start(); let server = httpmock::MockServer::start();
let resource_url = server.url("/"); let resource_url: RcStr = server.url("/").into();
let result = &*fetch( let result = &*fetch(resource_url.clone(), None, Vc::cell(None))
Vc::cell(resource_url.clone().into()),
Vc::cell(None),
Vc::cell(None),
)
.await .await
.unwrap(); .unwrap();
let Err(err_vc) = result else { panic!() }; let Err(err_vc) = result else { panic!() };
...@@ -164,5 +157,5 @@ async fn errors_on_404() { ...@@ -164,5 +157,5 @@ async fn errors_on_404() {
} }
fn get_issue_context() -> Vc<FileSystemPath> { fn get_issue_context() -> Vc<FileSystemPath> {
DiskFileSystem::new("root".into(), "/".into(), vec![]).root() DiskFileSystem::new(rcstr!("root"), rcstr!("/"), vec![]).root()
} }
...@@ -23,7 +23,6 @@ pub mod source_context; ...@@ -23,7 +23,6 @@ pub mod source_context;
pub mod util; pub mod util;
pub(crate) mod virtual_fs; pub(crate) mod virtual_fs;
mod watcher; mod watcher;
use std::{ use std::{
borrow::Cow, borrow::Cow,
cmp::{Ordering, min}, cmp::{Ordering, min},
...@@ -57,7 +56,7 @@ use tokio::{ ...@@ -57,7 +56,7 @@ use tokio::{
sync::{RwLock, RwLockReadGuard}, sync::{RwLock, RwLockReadGuard},
}; };
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
ApplyEffectsContext, Completion, InvalidationReason, Invalidator, NonLocalValue, ReadRef, ApplyEffectsContext, Completion, InvalidationReason, Invalidator, NonLocalValue, ReadRef,
ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, effect, mark_session_dependent, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, effect, mark_session_dependent,
...@@ -1286,7 +1285,7 @@ impl FileSystemPath { ...@@ -1286,7 +1285,7 @@ impl FileSystemPath {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn extension(&self) -> Vc<RcStr> { pub fn extension(&self) -> Vc<RcStr> {
Vc::cell(self.extension_ref().unwrap_or("").into()) Vc::cell(self.extension_ref().map(RcStr::from).unwrap_or_default())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -2404,7 +2403,7 @@ impl FileSystem for NullFileSystem { ...@@ -2404,7 +2403,7 @@ impl FileSystem for NullFileSystem {
impl ValueToString for NullFileSystem { impl ValueToString for NullFileSystem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell(RcStr::from("null")) Vc::cell(rcstr!("null"))
} }
} }
...@@ -2431,6 +2430,8 @@ pub fn register() { ...@@ -2431,6 +2430,8 @@ pub fn register() {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use turbo_rcstr::rcstr;
use super::*; use super::*;
#[test] #[test]
...@@ -2456,26 +2457,26 @@ mod tests { ...@@ -2456,26 +2457,26 @@ mod tests {
turbo_tasks_testing::VcStorage::with(async { turbo_tasks_testing::VcStorage::with(async {
let fs = Vc::upcast(VirtualFileSystem::new()); let fs = Vc::upcast(VirtualFileSystem::new());
let path_txt = FileSystemPath::new_normalized(fs, "foo/bar.txt".into()); let path_txt = FileSystemPath::new_normalized(fs, rcstr!("foo/bar.txt"));
let path_json = path_txt.with_extension("json".into()); let path_json = path_txt.with_extension(rcstr!("json"));
assert_eq!(&*path_json.await.unwrap().path, "foo/bar.json"); assert_eq!(&*path_json.await.unwrap().path, "foo/bar.json");
let path_no_ext = path_txt.with_extension("".into()); let path_no_ext = path_txt.with_extension(rcstr!(""));
assert_eq!(&*path_no_ext.await.unwrap().path, "foo/bar"); assert_eq!(&*path_no_ext.await.unwrap().path, "foo/bar");
let path_new_ext = path_no_ext.with_extension("json".into()); let path_new_ext = path_no_ext.with_extension(rcstr!("json"));
assert_eq!(&*path_new_ext.await.unwrap().path, "foo/bar.json"); assert_eq!(&*path_new_ext.await.unwrap().path, "foo/bar.json");
let path_no_slash_txt = FileSystemPath::new_normalized(fs, "bar.txt".into()); let path_no_slash_txt = FileSystemPath::new_normalized(fs, rcstr!("bar.txt"));
let path_no_slash_json = path_no_slash_txt.with_extension("json".into()); let path_no_slash_json = path_no_slash_txt.with_extension(rcstr!("json"));
assert_eq!(path_no_slash_json.await.unwrap().path.as_str(), "bar.json"); assert_eq!(path_no_slash_json.await.unwrap().path.as_str(), "bar.json");
let path_no_slash_no_ext = path_no_slash_txt.with_extension("".into()); let path_no_slash_no_ext = path_no_slash_txt.with_extension(rcstr!(""));
assert_eq!(path_no_slash_no_ext.await.unwrap().path.as_str(), "bar"); assert_eq!(path_no_slash_no_ext.await.unwrap().path.as_str(), "bar");
let path_no_slash_new_ext = path_no_slash_no_ext.with_extension("json".into()); let path_no_slash_new_ext = path_no_slash_no_ext.with_extension(rcstr!("json"));
assert_eq!( assert_eq!(
path_no_slash_new_ext.await.unwrap().path.as_str(), path_no_slash_new_ext.await.unwrap().path.as_str(),
"bar.json" "bar.json"
...@@ -2494,19 +2495,19 @@ mod tests { ...@@ -2494,19 +2495,19 @@ mod tests {
turbo_tasks_testing::VcStorage::with(async { turbo_tasks_testing::VcStorage::with(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(VirtualFileSystem::new()); let fs = Vc::upcast::<Box<dyn FileSystem>>(VirtualFileSystem::new());
let path = FileSystemPath::new_normalized(fs, "".into()); let path = FileSystemPath::new_normalized(fs, rcstr!(""));
assert_eq!(path.file_stem().await.unwrap().as_deref(), None); assert_eq!(path.file_stem().await.unwrap().as_deref(), None);
let path = FileSystemPath::new_normalized(fs, "foo/bar.txt".into()); let path = FileSystemPath::new_normalized(fs, rcstr!("foo/bar.txt"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar")); assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar"));
let path = FileSystemPath::new_normalized(fs, "bar.txt".into()); let path = FileSystemPath::new_normalized(fs, rcstr!("bar.txt"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar")); assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar"));
let path = FileSystemPath::new_normalized(fs, "foo/bar".into()); let path = FileSystemPath::new_normalized(fs, rcstr!("foo/bar"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar")); assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar"));
let path = FileSystemPath::new_normalized(fs, "foo/.bar".into()); let path = FileSystemPath::new_normalized(fs, rcstr!("foo/.bar"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some(".bar")); assert_eq!(path.file_stem().await.unwrap().as_deref(), Some(".bar"));
anyhow::Ok(()) anyhow::Ok(())
......
...@@ -11,7 +11,7 @@ use clap::{Args, Parser, Subcommand}; ...@@ -11,7 +11,7 @@ use clap::{Args, Parser, Subcommand};
use rand::{Rng, RngCore, SeedableRng}; use rand::{Rng, RngCore, SeedableRng};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use tokio::time::sleep; use tokio::time::sleep;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, TransientInstance, Vc, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, ResolvedVc, TransientInstance, Vc, trace::TraceRawVcs};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath}; use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath};
...@@ -142,7 +142,7 @@ async fn fuzz_fs_watcher(args: FsWatcher) -> anyhow::Result<()> { ...@@ -142,7 +142,7 @@ async fn fuzz_fs_watcher(args: FsWatcher) -> anyhow::Result<()> {
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
fn disk_file_system_operation(fs_root: RcStr) -> Vc<DiskFileSystem> { fn disk_file_system_operation(fs_root: RcStr) -> Vc<DiskFileSystem> {
DiskFileSystem::new("project".into(), fs_root, Vec::new()) DiskFileSystem::new(rcstr!("project"), fs_root, Vec::new())
} }
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
#![feature(arbitrary_self_types_pointers)] #![feature(arbitrary_self_types_pointers)]
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Value, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, Value, ValueToString, Vc};
use turbo_tasks_testing::{Registration, register, run}; use turbo_tasks_testing::{Registration, register, run};
...@@ -93,7 +93,7 @@ impl ValueToString for MyEnumValue { ...@@ -93,7 +93,7 @@ impl ValueToString for MyEnumValue {
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
match self { match self {
MyEnumValue::Yeah(value) => Vc::cell(value.to_string().into()), MyEnumValue::Yeah(value) => Vc::cell(value.to_string().into()),
MyEnumValue::Nah => Vc::cell("nah".into()), MyEnumValue::Nah => Vc::cell(rcstr!("nah")),
MyEnumValue::More(more) => more.to_string(), MyEnumValue::More(more) => more.to_string(),
} }
} }
......
...@@ -8,7 +8,7 @@ use anyhow::Result; ...@@ -8,7 +8,7 @@ use anyhow::Result;
use auto_hash_map::AutoSet; use auto_hash_map::AutoSet;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use tokio::time::sleep; use tokio::time::sleep;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{CollectiblesSource, ResolvedVc, ValueToString, Vc, emit}; use turbo_tasks::{CollectiblesSource, ResolvedVc, ValueToString, Vc, emit};
use turbo_tasks_testing::{Registration, register, run}; use turbo_tasks_testing::{Registration, register, run};
...@@ -17,7 +17,7 @@ static REGISTRATION: Registration = register!(); ...@@ -17,7 +17,7 @@ static REGISTRATION: Registration = register!();
#[tokio::test] #[tokio::test]
async fn transitive_emitting() { async fn transitive_emitting() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function("".into(), "".into()); let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.peek_collectibles::<Box<dyn ValueToString>>(); let list = result_op.peek_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
...@@ -35,8 +35,8 @@ async fn transitive_emitting() { ...@@ -35,8 +35,8 @@ async fn transitive_emitting() {
#[tokio::test] #[tokio::test]
async fn transitive_emitting_indirect() { async fn transitive_emitting_indirect() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function("".into(), "".into()); let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let collectibles_op = my_transitive_emitting_function_collectibles("".into(), "".into()); let collectibles_op = my_transitive_emitting_function_collectibles(rcstr!(""), rcstr!(""));
let list = collectibles_op.connect().strongly_consistent().await?; let list = collectibles_op.connect().strongly_consistent().await?;
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
let mut expected = ["123", "42"].into_iter().collect::<FxHashSet<_>>(); let mut expected = ["123", "42"].into_iter().collect::<FxHashSet<_>>();
...@@ -103,34 +103,34 @@ async fn taking_collectibles_extra_layer() { ...@@ -103,34 +103,34 @@ async fn taking_collectibles_extra_layer() {
#[tokio::test] #[tokio::test]
async fn taking_collectibles_parallel() { async fn taking_collectibles_parallel() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function("".into(), "a".into()); let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!("a"));
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>(); let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0); assert_eq!(result_val.0, 0);
let result_op = my_transitive_emitting_function("".into(), "b".into()); let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!("b"));
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>(); let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0); assert_eq!(result_val.0, 0);
let result_op = let result_op =
my_transitive_emitting_function_with_child_scope("".into(), "b".into(), "1".into()); my_transitive_emitting_function_with_child_scope(rcstr!(""), rcstr!("b"), rcstr!("1"));
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>(); let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0); assert_eq!(result_val.0, 0);
let result_op = let result_op =
my_transitive_emitting_function_with_child_scope("".into(), "b".into(), "2".into()); my_transitive_emitting_function_with_child_scope(rcstr!(""), rcstr!("b"), rcstr!("2"));
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>(); let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0); assert_eq!(result_val.0, 0);
let result_op = let result_op =
my_transitive_emitting_function_with_child_scope("".into(), "c".into(), "3".into()); my_transitive_emitting_function_with_child_scope(rcstr!(""), rcstr!("c"), rcstr!("3"));
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>(); let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
...@@ -145,7 +145,7 @@ async fn taking_collectibles_parallel() { ...@@ -145,7 +145,7 @@ async fn taking_collectibles_parallel() {
#[tokio::test] #[tokio::test]
async fn taking_collectibles_with_resolve() { async fn taking_collectibles_with_resolve() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function_with_resolve("resolve".into()); let result_op = my_transitive_emitting_function_with_resolve(rcstr!("resolve"));
result_op.connect().strongly_consistent().await?; result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>(); let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2); assert_eq!(list.len(), 2);
...@@ -161,7 +161,7 @@ struct Collectibles(AutoSet<ResolvedVc<Box<dyn ValueToString>>>); ...@@ -161,7 +161,7 @@ struct Collectibles(AutoSet<ResolvedVc<Box<dyn ValueToString>>>);
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
async fn my_collecting_function() -> Result<Vc<Thing>> { async fn my_collecting_function() -> Result<Vc<Thing>> {
let result_op = my_transitive_emitting_function("".into(), "".into()); let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let result_vc = result_op.connect(); let result_vc = result_op.connect();
result_vc.await?; result_vc.await?;
result_op.take_collectibles::<Box<dyn ValueToString>>(); result_op.take_collectibles::<Box<dyn ValueToString>>();
...@@ -182,13 +182,13 @@ async fn my_collecting_function_indirect() -> Result<Vc<Thing>> { ...@@ -182,13 +182,13 @@ async fn my_collecting_function_indirect() -> Result<Vc<Thing>> {
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
async fn my_multi_emitting_function() -> Result<Vc<Thing>> { async fn my_multi_emitting_function() -> Result<Vc<Thing>> {
my_transitive_emitting_function("".into(), "a".into()) my_transitive_emitting_function(rcstr!(""), rcstr!("a"))
.connect() .connect()
.await?; .await?;
my_transitive_emitting_function("".into(), "b".into()) my_transitive_emitting_function(rcstr!(""), rcstr!("b"))
.connect() .connect()
.await?; .await?;
my_emitting_function("".into()).await?; my_emitting_function(rcstr!("")).await?;
Ok(Thing::cell(Thing(0))) Ok(Thing::cell(Thing(0)))
} }
......
...@@ -322,6 +322,7 @@ tuple_impls! { A B C D E F G H I J K L } ...@@ -322,6 +322,7 @@ tuple_impls! { A B C D E F G H I J K L }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use turbo_rcstr::rcstr;
use turbo_tasks_macros::TaskInput; use turbo_tasks_macros::TaskInput;
use super::*; use super::*;
...@@ -364,7 +365,7 @@ mod tests { ...@@ -364,7 +365,7 @@ mod tests {
)] )]
struct MultipleUnnamedFields(u32, RcStr); struct MultipleUnnamedFields(u32, RcStr);
assert_task_input(MultipleUnnamedFields(42, "42".into())); assert_task_input(MultipleUnnamedFields(42, rcstr!("42")));
Ok(()) Ok(())
} }
...@@ -393,7 +394,7 @@ mod tests { ...@@ -393,7 +394,7 @@ mod tests {
assert_task_input(MultipleNamedFields { assert_task_input(MultipleNamedFields {
named: 42, named: 42,
other: "42".into(), other: rcstr!("42"),
}); });
Ok(()) Ok(())
} }
...@@ -406,7 +407,7 @@ mod tests { ...@@ -406,7 +407,7 @@ mod tests {
struct GenericField<T>(T); struct GenericField<T>(T);
assert_task_input(GenericField(42)); assert_task_input(GenericField(42));
assert_task_input(GenericField(RcStr::from("42"))); assert_task_input(GenericField(rcstr!("42")));
Ok(()) Ok(())
} }
...@@ -448,7 +449,7 @@ mod tests { ...@@ -448,7 +449,7 @@ mod tests {
fn test_multiple_variants_and_heterogeneous_fields() -> Result<()> { fn test_multiple_variants_and_heterogeneous_fields() -> Result<()> {
assert_task_input(MultipleVariantsAndHeterogeneousFields::Variant5 { assert_task_input(MultipleVariantsAndHeterogeneousFields::Variant5 {
named: 42, named: 42,
other: "42".into(), other: rcstr!("42"),
}); });
Ok(()) Ok(())
} }
...@@ -468,12 +469,12 @@ mod tests { ...@@ -468,12 +469,12 @@ mod tests {
assert_task_input(NestedVariants::Variant5 { assert_task_input(NestedVariants::Variant5 {
named: OneVariant::Variant, named: OneVariant::Variant,
other: "42".into(), other: rcstr!("42"),
}); });
assert_task_input(NestedVariants::Variant2( assert_task_input(NestedVariants::Variant2(
MultipleVariantsAndHeterogeneousFields::Variant5 { MultipleVariantsAndHeterogeneousFields::Variant5 {
named: 42, named: 42,
other: "42".into(), other: rcstr!("42"),
}, },
)); ));
Ok(()) Ok(())
......
...@@ -97,17 +97,17 @@ impl BrowserChunkingContextBuilder { ...@@ -97,17 +97,17 @@ impl BrowserChunkingContextBuilder {
self self
} }
pub fn asset_base_path(mut self, asset_base_path: ResolvedVc<Option<RcStr>>) -> Self { pub fn asset_base_path(mut self, asset_base_path: Option<RcStr>) -> Self {
self.chunking_context.asset_base_path = asset_base_path; self.chunking_context.asset_base_path = asset_base_path;
self self
} }
pub fn chunk_base_path(mut self, chunk_base_path: ResolvedVc<Option<RcStr>>) -> Self { pub fn chunk_base_path(mut self, chunk_base_path: Option<RcStr>) -> Self {
self.chunking_context.chunk_base_path = chunk_base_path; self.chunking_context.chunk_base_path = chunk_base_path;
self self
} }
pub fn chunk_suffix_path(mut self, chunk_suffix_path: ResolvedVc<Option<RcStr>>) -> Self { pub fn chunk_suffix_path(mut self, chunk_suffix_path: Option<RcStr>) -> Self {
self.chunking_context.chunk_suffix_path = chunk_suffix_path; self.chunking_context.chunk_suffix_path = chunk_suffix_path;
self self
} }
...@@ -182,7 +182,7 @@ pub struct BrowserChunkingContext { ...@@ -182,7 +182,7 @@ pub struct BrowserChunkingContext {
/// This path is used to compute the url to request chunks from /// This path is used to compute the url to request chunks from
output_root: ResolvedVc<FileSystemPath>, output_root: ResolvedVc<FileSystemPath>,
/// The relative path from the output_root to the root_path. /// The relative path from the output_root to the root_path.
output_root_to_root_path: ResolvedVc<RcStr>, output_root_to_root_path: RcStr,
/// This path is used to compute the url to request assets from /// This path is used to compute the url to request assets from
client_root: ResolvedVc<FileSystemPath>, client_root: ResolvedVc<FileSystemPath>,
/// Chunks are placed at this path /// Chunks are placed at this path
...@@ -191,13 +191,13 @@ pub struct BrowserChunkingContext { ...@@ -191,13 +191,13 @@ pub struct BrowserChunkingContext {
asset_root_path: ResolvedVc<FileSystemPath>, asset_root_path: ResolvedVc<FileSystemPath>,
/// Base path that will be prepended to all chunk URLs when loading them. /// Base path that will be prepended 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_base_path: ResolvedVc<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: ResolvedVc<Option<RcStr>>, chunk_suffix_path: 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: ResolvedVc<Option<RcStr>>, asset_base_path: Option<RcStr>,
/// Enable HMR for this chunking /// Enable HMR for this chunking
enable_hot_module_replacement: bool, enable_hot_module_replacement: bool,
/// Enable tracing for this chunking /// Enable tracing for this chunking
...@@ -226,7 +226,7 @@ impl BrowserChunkingContext { ...@@ -226,7 +226,7 @@ impl BrowserChunkingContext {
pub fn builder( pub fn builder(
root_path: ResolvedVc<FileSystemPath>, root_path: ResolvedVc<FileSystemPath>,
output_root: ResolvedVc<FileSystemPath>, output_root: ResolvedVc<FileSystemPath>,
output_root_to_root_path: ResolvedVc<RcStr>, output_root_to_root_path: RcStr,
client_root: ResolvedVc<FileSystemPath>, client_root: ResolvedVc<FileSystemPath>,
chunk_root_path: ResolvedVc<FileSystemPath>, chunk_root_path: ResolvedVc<FileSystemPath>,
asset_root_path: ResolvedVc<FileSystemPath>, asset_root_path: ResolvedVc<FileSystemPath>,
...@@ -243,9 +243,9 @@ impl BrowserChunkingContext { ...@@ -243,9 +243,9 @@ impl BrowserChunkingContext {
chunk_root_path, chunk_root_path,
should_use_file_source_map_uris: false, should_use_file_source_map_uris: false,
asset_root_path, asset_root_path,
chunk_base_path: ResolvedVc::cell(None), chunk_base_path: None,
chunk_suffix_path: ResolvedVc::cell(None), chunk_suffix_path: None,
asset_base_path: ResolvedVc::cell(None), asset_base_path: None,
enable_hot_module_replacement: false, enable_hot_module_replacement: false,
enable_tracing: false, enable_tracing: false,
environment, environment,
...@@ -272,13 +272,13 @@ impl BrowserChunkingContext { ...@@ -272,13 +272,13 @@ impl BrowserChunkingContext {
} }
/// Returns the asset base path. /// Returns the asset base path.
pub fn chunk_base_path(&self) -> Vc<Option<RcStr>> { pub fn chunk_base_path(&self) -> Option<RcStr> {
*self.chunk_base_path self.chunk_base_path.clone()
} }
/// Returns the asset suffix path. /// Returns the asset suffix path.
pub fn chunk_suffix_path(&self) -> Vc<Option<RcStr>> { pub fn chunk_suffix_path(&self) -> Option<RcStr> {
*self.chunk_suffix_path self.chunk_suffix_path.clone()
} }
/// Returns the source map type. /// Returns the source map type.
...@@ -367,7 +367,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -367,7 +367,7 @@ impl ChunkingContext for BrowserChunkingContext {
if let Some(name) = &self.name { if let Some(name) = &self.name {
Vc::cell(name.clone()) Vc::cell(name.clone())
} else { } else {
Vc::cell("unknown".into()) Vc::cell(rcstr!("unknown"))
} }
} }
...@@ -383,7 +383,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -383,7 +383,7 @@ impl ChunkingContext for BrowserChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
fn output_root_to_root_path(&self) -> Vc<RcStr> { fn output_root_to_root_path(&self) -> Vc<RcStr> {
*self.output_root_to_root_path Vc::cell(self.output_root_to_root_path.clone())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -446,7 +446,6 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -446,7 +446,6 @@ impl ChunkingContext for BrowserChunkingContext {
format!( format!(
"{}{}", "{}{}",
self.asset_base_path self.asset_base_path
.await?
.as_ref() .as_ref()
.map(|s| s.as_str()) .map(|s| s.as_str())
.unwrap_or("/"), .unwrap_or("/"),
......
...@@ -60,7 +60,7 @@ impl EcmascriptBrowserChunk { ...@@ -60,7 +60,7 @@ impl EcmascriptBrowserChunk {
impl ValueToString for EcmascriptBrowserChunk { impl ValueToString for EcmascriptBrowserChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("Ecmascript Dev Chunk".into()) Vc::cell(rcstr!("Ecmascript Dev Chunk"))
} }
} }
...@@ -103,7 +103,7 @@ impl OutputAsset for EcmascriptBrowserChunk { ...@@ -103,7 +103,7 @@ impl OutputAsset for EcmascriptBrowserChunk {
let ident = this.ident_for_path(); let ident = this.ident_for_path();
Ok(this Ok(this
.chunking_context .chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, ".js".into())) .chunk_path(Some(Vc::upcast(self)), ident, rcstr!(".js")))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -158,21 +158,11 @@ impl GenerateSourceMap for EcmascriptBrowserChunk { ...@@ -158,21 +158,11 @@ impl GenerateSourceMap for EcmascriptBrowserChunk {
} }
} }
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("dev ecmascript chunk".into())
}
#[turbo_tasks::function]
fn introspectable_details() -> Vc<RcStr> {
Vc::cell("generates a development ecmascript chunk".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for EcmascriptBrowserChunk { impl Introspectable for EcmascriptBrowserChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
introspectable_type() Vc::cell(rcstr!("dev ecmascript chunk"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -182,14 +172,14 @@ impl Introspectable for EcmascriptBrowserChunk { ...@@ -182,14 +172,14 @@ impl Introspectable for EcmascriptBrowserChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
fn details(&self) -> Vc<RcStr> { fn details(&self) -> Vc<RcStr> {
introspectable_details() Vc::cell(rcstr!("generates a development ecmascript chunk"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> { async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let mut children = FxIndexSet::default(); let mut children = FxIndexSet::default();
let chunk = ResolvedVc::upcast::<Box<dyn Introspectable>>(self.chunk); let chunk = ResolvedVc::upcast::<Box<dyn Introspectable>>(self.chunk);
children.insert((ResolvedVc::cell("chunk".into()), chunk)); children.insert((rcstr!("chunk"), chunk));
Ok(Vc::cell(children)) Ok(Vc::cell(children))
} }
} }
...@@ -78,7 +78,11 @@ impl EcmascriptBrowserEvaluateChunk { ...@@ -78,7 +78,11 @@ impl EcmascriptBrowserEvaluateChunk {
let chunking_context = this.chunking_context.await?; let chunking_context = this.chunking_context.await?;
let environment = this.chunking_context.environment(); let environment = this.chunking_context.environment();
let output_root_to_root_path = this.chunking_context.output_root_to_root_path(); let output_root_to_root_path = this
.chunking_context
.output_root_to_root_path()
.owned()
.await?;
let source_maps = *this let source_maps = *this
.chunking_context .chunking_context
.reference_chunk_source_maps(Vc::upcast(self)) .reference_chunk_source_maps(Vc::upcast(self))
...@@ -242,7 +246,7 @@ impl EcmascriptBrowserEvaluateChunk { ...@@ -242,7 +246,7 @@ impl EcmascriptBrowserEvaluateChunk {
impl ValueToString for EcmascriptBrowserEvaluateChunk { impl ValueToString for EcmascriptBrowserEvaluateChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("Ecmascript Browser Evaluate Chunk".into()) Vc::cell(rcstr!("Ecmascript Browser Evaluate Chunk"))
} }
} }
...@@ -254,7 +258,7 @@ impl OutputAsset for EcmascriptBrowserEvaluateChunk { ...@@ -254,7 +258,7 @@ impl OutputAsset for EcmascriptBrowserEvaluateChunk {
let ident = self.ident_for_path(); let ident = self.ident_for_path();
Ok(this Ok(this
.chunking_context .chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, ".js".into())) .chunk_path(Some(Vc::upcast(self)), ident, rcstr!(".js")))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -64,7 +64,7 @@ impl EcmascriptDevChunkList { ...@@ -64,7 +64,7 @@ impl EcmascriptDevChunkList {
impl ValueToString for EcmascriptDevChunkList { impl ValueToString for EcmascriptDevChunkList {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("Ecmascript Dev Chunk List".into()) Vc::cell(rcstr!("Ecmascript Dev Chunk List"))
} }
} }
...@@ -90,7 +90,7 @@ impl OutputAsset for EcmascriptDevChunkList { ...@@ -90,7 +90,7 @@ impl OutputAsset for EcmascriptDevChunkList {
let ident = AssetIdent::new(Value::new(ident)); let ident = AssetIdent::new(Value::new(ident));
Ok(this Ok(this
.chunking_context .chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, ".js".into())) .chunk_path(Some(Vc::upcast(self)), ident, rcstr!(".js")))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Value, Vc}; use turbo_tasks::{ResolvedVc, Value, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
...@@ -12,12 +13,14 @@ use turbopack_resolve::{ ...@@ -12,12 +13,14 @@ use turbopack_resolve::{
#[turbo_tasks::function] #[turbo_tasks::function]
fn react_refresh_request() -> Vc<Request> { fn react_refresh_request() -> Vc<Request> {
Request::parse_string("@next/react-refresh-utils/dist/runtime".into()) Request::parse_string(rcstr!("@next/react-refresh-utils/dist/runtime"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn react_refresh_request_in_next() -> Vc<Request> { fn react_refresh_request_in_next() -> Vc<Request> {
Request::parse_string("next/dist/compiled/@next/react-refresh-utils/dist/runtime".into()) Request::parse_string(rcstr!(
"next/dist/compiled/@next/react-refresh-utils/dist/runtime"
))
} }
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -84,7 +87,7 @@ impl Issue for ReactRefreshResolvingIssue { ...@@ -84,7 +87,7 @@ impl Issue for ReactRefreshResolvingIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> { fn title(&self) -> Vc<StyledString> {
StyledString::Text("Could not resolve React Refresh runtime".into()).cell() StyledString::Text(rcstr!("Could not resolve React Refresh runtime")).cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -101,13 +104,13 @@ impl Issue for ReactRefreshResolvingIssue { ...@@ -101,13 +104,13 @@ impl Issue for ReactRefreshResolvingIssue {
fn description(&self) -> Vc<OptionStyledString> { fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some( Vc::cell(Some(
StyledString::Line(vec![ StyledString::Line(vec![
StyledString::Text( StyledString::Text(rcstr!(
"React Refresh will be disabled.\nTo enable React Refresh, install the ".into(), "React Refresh will be disabled.\nTo enable React Refresh, install the "
), )),
StyledString::Code("react-refresh".into()), StyledString::Code(rcstr!("react-refresh")),
StyledString::Text(" and ".into()), StyledString::Text(rcstr!(" and ")),
StyledString::Code("@next/react-refresh-utils".into()), StyledString::Code(rcstr!("@next/react-refresh-utils")),
StyledString::Text(" modules.".into()), StyledString::Text(rcstr!(" modules.")),
]) ])
.resolved_cell(), .resolved_cell(),
)) ))
......
...@@ -8,7 +8,7 @@ use std::{ ...@@ -8,7 +8,7 @@ use std::{
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
ReadConsistency, ResolvedVc, TransientInstance, TryJoinIterExt, TurboTasks, Value, Vc, ReadConsistency, ResolvedVc, TransientInstance, TryJoinIterExt, TurboTasks, Value, Vc,
apply_effects, apply_effects,
...@@ -208,12 +208,12 @@ async fn build_internal( ...@@ -208,12 +208,12 @@ async fn build_internal(
.into(); .into();
let root_path = project_fs.root().to_resolved().await?; let root_path = project_fs.root().to_resolved().await?;
let project_path = root_path.join(project_relative).to_resolved().await?; let project_path = root_path.join(project_relative).to_resolved().await?;
let build_output_root = output_fs.root().join("dist".into()).to_resolved().await?; let build_output_root = output_fs.root().join(rcstr!("dist")).to_resolved().await?;
let node_env = NodeEnv::Production.cell(); let node_env = NodeEnv::Production.cell();
let build_output_root_to_root_path = project_path let build_output_root_to_root_path = project_path
.join("dist".into()) .join(rcstr!("dist"))
.await? .await?
.get_relative_path_to(&*root_path.await?) .get_relative_path_to(&*root_path.await?)
.context("Project path is in root path")?; .context("Project path is in root path")?;
...@@ -230,7 +230,7 @@ async fn build_internal( ...@@ -230,7 +230,7 @@ async fn build_internal(
NodeJsChunkingContext::builder( NodeJsChunkingContext::builder(
project_path, project_path,
build_output_root, build_output_root,
ResolvedVc::cell(build_output_root_to_root_path.clone()), build_output_root_to_root_path.clone(),
build_output_root, build_output_root,
build_output_root, build_output_root,
build_output_root, build_output_root,
...@@ -276,7 +276,7 @@ async fn build_internal( ...@@ -276,7 +276,7 @@ async fn build_internal(
.await?) .await?)
.to_vec(); .to_vec();
let origin = PlainResolveOrigin::new(asset_context, project_fs.root().join("_".into())); let origin = PlainResolveOrigin::new(asset_context, project_fs.root().join(rcstr!("_")));
let project_dir = &project_dir; let project_dir = &project_dir;
let entries = async move { let entries = async move {
entry_requests entry_requests
...@@ -318,7 +318,7 @@ async fn build_internal( ...@@ -318,7 +318,7 @@ async fn build_internal(
let mut builder = BrowserChunkingContext::builder( let mut builder = BrowserChunkingContext::builder(
project_path, project_path,
build_output_root, build_output_root,
ResolvedVc::cell(build_output_root_to_root_path), build_output_root_to_root_path,
build_output_root, build_output_root,
build_output_root, build_output_root,
build_output_root, build_output_root,
...@@ -369,7 +369,7 @@ async fn build_internal( ...@@ -369,7 +369,7 @@ async fn build_internal(
let mut builder = NodeJsChunkingContext::builder( let mut builder = NodeJsChunkingContext::builder(
project_path, project_path,
build_output_root, build_output_root,
ResolvedVc::cell(build_output_root_to_root_path), build_output_root_to_root_path,
build_output_root, build_output_root,
build_output_root, build_output_root,
build_output_root, build_output_root,
...@@ -433,7 +433,7 @@ async fn build_internal( ...@@ -433,7 +433,7 @@ async fn build_internal(
.unwrap() .unwrap()
.into(), .into(),
) )
.with_extension("entry.js".into()), .with_extension(rcstr!("entry.js")),
), ),
ChunkGroup::Entry( ChunkGroup::Entry(
[ResolvedVc::upcast(ecmascript)].into_iter().collect(), [ResolvedVc::upcast(ecmascript)].into_iter().collect(),
...@@ -458,7 +458,7 @@ async fn build_internal( ...@@ -458,7 +458,7 @@ async fn build_internal(
.unwrap() .unwrap()
.into(), .into(),
) )
.with_extension("entry.js".into()), .with_extension(rcstr!("entry.js")),
EvaluatableAssets::one(*ResolvedVc::upcast(ecmascript)), EvaluatableAssets::one(*ResolvedVc::upcast(ecmascript)),
module_graph, module_graph,
OutputAssets::empty(), OutputAssets::empty(),
......
...@@ -11,7 +11,7 @@ use std::{ ...@@ -11,7 +11,7 @@ use std::{
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use owo_colors::OwoColorize; use owo_colors::OwoColorize;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
NonLocalValue, OperationVc, ResolvedVc, TransientInstance, TurboTasks, UpdateInfo, Value, Vc, NonLocalValue, OperationVc, ResolvedVc, TransientInstance, TurboTasks, UpdateInfo, Value, Vc,
trace::TraceRawVcs, trace::TraceRawVcs,
...@@ -271,16 +271,16 @@ async fn source( ...@@ -271,16 +271,16 @@ async fn source(
let env = load_env(*root_path); let env = load_env(*root_path);
let build_output_root = output_fs let build_output_root = output_fs
.root() .root()
.join(".turbopack/build".into()) .join(rcstr!(".turbopack/build"))
.to_resolved() .to_resolved()
.await?; .await?;
let build_output_root_to_root_path = project_path let build_output_root_to_root_path = project_path
.join(".turbopack/build".into()) .join(rcstr!(".turbopack/build"))
.await? .await?
.get_relative_path_to(&*root_path.await?) .get_relative_path_to(&*root_path.await?)
.context("Project path is in root path")?; .context("Project path is in root path")?;
let build_output_root_to_root_path = ResolvedVc::cell(build_output_root_to_root_path); let build_output_root_to_root_path = build_output_root_to_root_path;
let build_chunking_context = NodeJsChunkingContext::builder( let build_chunking_context = NodeJsChunkingContext::builder(
root_path, root_path,
...@@ -288,11 +288,11 @@ async fn source( ...@@ -288,11 +288,11 @@ async fn source(
build_output_root_to_root_path, build_output_root_to_root_path,
build_output_root, build_output_root,
build_output_root build_output_root
.join("chunks".into()) .join(rcstr!("chunks"))
.to_resolved() .to_resolved()
.await?, .await?,
build_output_root build_output_root
.join("assets".into()) .join(rcstr!("assets"))
.to_resolved() .to_resolved()
.await?, .await?,
node_build_environment().to_resolved().await?, node_build_environment().to_resolved().await?,
...@@ -328,7 +328,7 @@ async fn source( ...@@ -328,7 +328,7 @@ async fn source(
execution_context, execution_context,
entry_requests, entry_requests,
server_root, server_root,
Vc::cell("/ROOT".into()), rcstr!("/ROOT"),
env, env,
eager_compile, eager_compile,
NodeEnv::Development.cell(), NodeEnv::Development.cell(),
...@@ -338,7 +338,7 @@ async fn source( ...@@ -338,7 +338,7 @@ async fn source(
.to_resolved() .to_resolved()
.await?; .await?;
let static_source = ResolvedVc::upcast( let static_source = ResolvedVc::upcast(
StaticAssetsContentSource::new(Default::default(), project_path.join("public".into())) StaticAssetsContentSource::new(Default::default(), project_path.join(rcstr!("public")))
.to_resolved() .to_resolved()
.await?, .await?,
); );
...@@ -354,7 +354,7 @@ async fn source( ...@@ -354,7 +354,7 @@ async fn source(
let main_source = ResolvedVc::upcast(main_source); let main_source = ResolvedVc::upcast(main_source);
Ok(Vc::upcast(PrefixedRouterContentSource::new( Ok(Vc::upcast(PrefixedRouterContentSource::new(
Default::default(), Default::default(),
vec![("__turbopack__".into(), introspect)], vec![(rcstr!("__turbopack__"), introspect)],
*main_source, *main_source,
))) )))
} }
......
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Value, Vc}; use turbo_tasks::{ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Value, Vc};
use turbo_tasks_env::ProcessEnv; use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -36,7 +36,7 @@ use crate::{ ...@@ -36,7 +36,7 @@ use crate::{
pub async fn get_client_chunking_context( pub async fn get_client_chunking_context(
root_path: ResolvedVc<FileSystemPath>, root_path: ResolvedVc<FileSystemPath>,
server_root: ResolvedVc<FileSystemPath>, server_root: ResolvedVc<FileSystemPath>,
server_root_to_root_path: ResolvedVc<RcStr>, server_root_to_root_path: RcStr,
environment: ResolvedVc<Environment>, environment: ResolvedVc<Environment>,
) -> Result<Vc<Box<dyn ChunkingContext>>> { ) -> Result<Vc<Box<dyn ChunkingContext>>> {
Ok(Vc::upcast( Ok(Vc::upcast(
...@@ -45,8 +45,8 @@ pub async fn get_client_chunking_context( ...@@ -45,8 +45,8 @@ pub async fn get_client_chunking_context(
server_root, server_root,
server_root_to_root_path, server_root_to_root_path,
server_root, server_root,
server_root.join("/_chunks".into()).to_resolved().await?, server_root.join(rcstr!("/_chunks")).to_resolved().await?,
server_root.join("/_assets".into()).to_resolved().await?, server_root.join(rcstr!("/_assets")).to_resolved().await?,
environment, environment,
RuntimeType::Development, RuntimeType::Development,
) )
...@@ -76,7 +76,7 @@ pub async fn get_client_runtime_entries( ...@@ -76,7 +76,7 @@ pub async fn get_client_runtime_entries(
runtime_entries.push( runtime_entries.push(
RuntimeEntry::Request( RuntimeEntry::Request(
request.to_resolved().await?, request.to_resolved().await?,
project_path.join("_".into()).to_resolved().await?, project_path.join(rcstr!("_")).to_resolved().await?,
) )
.resolved_cell(), .resolved_cell(),
) )
...@@ -84,7 +84,7 @@ pub async fn get_client_runtime_entries( ...@@ -84,7 +84,7 @@ pub async fn get_client_runtime_entries(
runtime_entries.push( runtime_entries.push(
RuntimeEntry::Source(ResolvedVc::upcast( RuntimeEntry::Source(ResolvedVc::upcast(
FileSource::new(embed_file_path("entry/bootstrap.ts".into())) FileSource::new(embed_file_path(rcstr!("entry/bootstrap.ts")))
.to_resolved() .to_resolved()
.await?, .await?,
)) ))
...@@ -100,7 +100,7 @@ pub async fn create_web_entry_source( ...@@ -100,7 +100,7 @@ pub async fn create_web_entry_source(
execution_context: Vc<ExecutionContext>, execution_context: Vc<ExecutionContext>,
entry_requests: Vec<Vc<Request>>, entry_requests: Vec<Vc<Request>>,
server_root: Vc<FileSystemPath>, server_root: Vc<FileSystemPath>,
server_root_to_root_path: ResolvedVc<RcStr>, server_root_to_root_path: RcStr,
_env: Vc<Box<dyn ProcessEnv>>, _env: Vc<Box<dyn ProcessEnv>>,
eager_compile: bool, eager_compile: bool,
node_env: Vc<NodeEnv>, node_env: Vc<NodeEnv>,
...@@ -118,7 +118,7 @@ pub async fn create_web_entry_source( ...@@ -118,7 +118,7 @@ pub async fn create_web_entry_source(
let chunking_context = get_client_chunking_context( let chunking_context = get_client_chunking_context(
root_path, root_path,
server_root, server_root,
*server_root_to_root_path, server_root_to_root_path,
compile_time_info.environment(), compile_time_info.environment(),
) )
.to_resolved() .to_resolved()
...@@ -127,7 +127,7 @@ pub async fn create_web_entry_source( ...@@ -127,7 +127,7 @@ pub async fn create_web_entry_source(
let runtime_entries = entries.resolve_entries(asset_context); let runtime_entries = entries.resolve_entries(asset_context);
let origin = PlainResolveOrigin::new(asset_context, root_path.join("_".into())); let origin = PlainResolveOrigin::new(asset_context, root_path.join(rcstr!("_")));
let entries = entry_requests let entries = entry_requests
.into_iter() .into_iter()
.map(|request| async move { .map(|request| async move {
...@@ -196,7 +196,7 @@ pub async fn create_web_entry_source( ...@@ -196,7 +196,7 @@ pub async fn create_web_entry_source(
.await?; .await?;
let entry_asset = Vc::upcast(DevHtmlAsset::new( let entry_asset = Vc::upcast(DevHtmlAsset::new(
server_root.join("index.html".into()).to_resolved().await?, server_root.join(rcstr!("index.html")).to_resolved().await?,
entries, entries,
)); ));
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_tasks::{ReadRef, ResolvedVc, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{ReadRef, ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::Xxh3Hash64Hasher; use turbo_tasks_hash::Xxh3Hash64Hasher;
...@@ -40,11 +39,6 @@ impl ChunksData { ...@@ -40,11 +39,6 @@ impl ChunksData {
} }
} }
#[turbo_tasks::function]
fn module_chunk_reference_description() -> Vc<RcStr> {
Vc::cell("module chunk".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ChunkData { impl ChunkData {
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -5,7 +5,7 @@ use std::{ ...@@ -5,7 +5,7 @@ use std::{
use anyhow::{Context, Result, anyhow}; use anyhow::{Context, Result, anyhow};
use swc_core::ecma::preset_env::{Version, Versions}; use swc_core::ecma::preset_env::{Version, Versions};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TaskInput, Value, Vc}; use turbo_tasks::{ResolvedVc, TaskInput, Value, Vc};
use turbo_tasks_env::ProcessEnv; use turbo_tasks_env::ProcessEnv;
...@@ -146,7 +146,7 @@ impl Environment { ...@@ -146,7 +146,7 @@ impl Environment {
let env = self; let env = self;
match env.execution { match env.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => { ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(vec![".js".into(), ".node".into(), ".json".into()]) Vc::cell(vec![rcstr!(".js"), rcstr!(".node"), rcstr!(".json")])
} }
ExecutionEnvironment::EdgeWorker(_) | ExecutionEnvironment::Browser(_) => { ExecutionEnvironment::EdgeWorker(_) | ExecutionEnvironment::Browser(_) => {
Vc::<Vec<RcStr>>::default() Vc::<Vec<RcStr>>::default()
...@@ -174,11 +174,11 @@ impl Environment { ...@@ -174,11 +174,11 @@ impl Environment {
let env = self; let env = self;
match env.execution { match env.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => { ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(vec!["node".into()]) Vc::cell(vec![rcstr!("node")])
} }
ExecutionEnvironment::Browser(_) => Vc::<Vec<RcStr>>::default(), ExecutionEnvironment::Browser(_) => Vc::<Vec<RcStr>>::default(),
ExecutionEnvironment::EdgeWorker(_) => { ExecutionEnvironment::EdgeWorker(_) => {
Vc::cell(vec!["edge-light".into(), "worker".into()]) Vc::cell(vec![rcstr!("edge-light"), rcstr!("worker")])
} }
ExecutionEnvironment::Custom(_) => todo!(), ExecutionEnvironment::Custom(_) => todo!(),
} }
...@@ -302,7 +302,7 @@ pub struct RuntimeVersions(#[turbo_tasks(trace_ignore)] pub Versions); ...@@ -302,7 +302,7 @@ pub struct RuntimeVersions(#[turbo_tasks(trace_ignore)] pub Versions);
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_current_nodejs_version(env: Vc<Box<dyn ProcessEnv>>) -> Result<Vc<RcStr>> { pub async fn get_current_nodejs_version(env: Vc<Box<dyn ProcessEnv>>) -> Result<Vc<RcStr>> {
let path_read = env.read("PATH".into()).await?; let path_read = env.read(rcstr!("PATH")).await?;
let path = path_read.as_ref().context("env must have PATH")?; let path = path_read.as_ref().context("env must have PATH")?;
let mut cmd = Command::new("node"); let mut cmd = Command::new("node");
cmd.arg("--version"); cmd.arg("--version");
......
...@@ -9,7 +9,7 @@ use turbo_tasks::{FxIndexSet, ResolvedVc, Vc}; ...@@ -9,7 +9,7 @@ use turbo_tasks::{FxIndexSet, ResolvedVc, Vc};
type VcDynIntrospectable = ResolvedVc<Box<dyn Introspectable>>; type VcDynIntrospectable = ResolvedVc<Box<dyn Introspectable>>;
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct IntrospectableChildren(FxIndexSet<(ResolvedVc<RcStr>, VcDynIntrospectable)>); pub struct IntrospectableChildren(FxIndexSet<(RcStr, VcDynIntrospectable)>);
#[turbo_tasks::value_trait] #[turbo_tasks::value_trait]
pub trait Introspectable { pub trait Introspectable {
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use super::{ use super::{
...@@ -20,16 +20,11 @@ impl IntrospectableModule { ...@@ -20,16 +20,11 @@ impl IntrospectableModule {
} }
} }
#[turbo_tasks::function]
fn ty() -> Vc<RcStr> {
Vc::cell("asset".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for IntrospectableModule { impl Introspectable for IntrospectableModule {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
ty() Vc::cell(rcstr!("asset"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use super::{ use super::{
...@@ -25,16 +25,11 @@ impl IntrospectableOutputAsset { ...@@ -25,16 +25,11 @@ impl IntrospectableOutputAsset {
} }
} }
#[turbo_tasks::function]
fn ty() -> Vc<RcStr> {
Vc::cell("output asset".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for IntrospectableOutputAsset { impl Introspectable for IntrospectableOutputAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
ty() Vc::cell(rcstr!("output asset"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use super::{Introspectable, utils::content_to_details}; use super::{Introspectable, utils::content_to_details};
...@@ -17,16 +17,11 @@ impl IntrospectableSource { ...@@ -17,16 +17,11 @@ impl IntrospectableSource {
} }
} }
#[turbo_tasks::function]
fn ty() -> Vc<RcStr> {
Vc::cell("source".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for IntrospectableSource { impl Introspectable for IntrospectableSource {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
ty() Vc::cell(rcstr!("source"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexSet, ResolvedVc, Vc}; use turbo_tasks::{FxIndexSet, ResolvedVc, Vc};
use turbo_tasks_fs::FileContent; use turbo_tasks_fs::FileContent;
...@@ -13,39 +13,32 @@ use crate::{ ...@@ -13,39 +13,32 @@ use crate::{
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences},
}; };
#[turbo_tasks::function] fn reference_ty() -> RcStr {
fn reference_ty() -> Vc<RcStr> { rcstr!("reference")
Vc::cell("reference".into())
} }
#[turbo_tasks::function] fn parallel_reference_ty() -> RcStr {
fn parallel_reference_ty() -> Vc<RcStr> { rcstr!("parallel reference")
Vc::cell("parallel reference".into())
} }
#[turbo_tasks::function] fn parallel_inherit_async_reference_ty() -> RcStr {
fn parallel_inherit_async_reference_ty() -> Vc<RcStr> { rcstr!("parallel reference (inherit async module)")
Vc::cell("parallel reference (inherit async module)".into())
} }
#[turbo_tasks::function] fn async_reference_ty() -> RcStr {
fn async_reference_ty() -> Vc<RcStr> { rcstr!("async reference")
Vc::cell("async reference".into())
} }
#[turbo_tasks::function] fn isolated_reference_ty() -> RcStr {
fn isolated_reference_ty() -> Vc<RcStr> { rcstr!("isolated reference")
Vc::cell("isolated reference".into())
} }
#[turbo_tasks::function] fn shared_reference_ty() -> RcStr {
fn shared_reference_ty() -> Vc<RcStr> { rcstr!("shared reference")
Vc::cell("shared reference".into())
} }
#[turbo_tasks::function] fn traced_reference_ty() -> RcStr {
fn traced_reference_ty() -> Vc<RcStr> { rcstr!("traced reference")
Vc::cell("traced reference".into())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -59,7 +52,7 @@ pub async fn content_to_details(content: Vc<AssetContent>) -> Result<Vc<RcStr>> ...@@ -59,7 +52,7 @@ pub async fn content_to_details(content: Vc<AssetContent>) -> Result<Vc<RcStr>>
Err(_) => Vc::cell(format!("{} binary bytes", content.len()).into()), Err(_) => Vc::cell(format!("{} binary bytes", content.len()).into()),
} }
} }
FileContent::NotFound => Vc::cell("not found".into()), FileContent::NotFound => Vc::cell(rcstr!("not found")),
}, },
AssetContent::Redirect { target, link_type } => { AssetContent::Redirect { target, link_type } => {
Vc::cell(format!("redirect to {target} with type {link_type:?}").into()) Vc::cell(format!("redirect to {target} with type {link_type:?}").into())
...@@ -75,21 +68,27 @@ pub async fn children_from_module_references( ...@@ -75,21 +68,27 @@ pub async fn children_from_module_references(
let mut children = FxIndexSet::default(); let mut children = FxIndexSet::default();
let references = references.await?; let references = references.await?;
for &reference in &*references { for &reference in &*references {
let mut key = key; let key = if let Some(chunkable) =
if let Some(chunkable) =
ResolvedVc::try_downcast::<Box<dyn ChunkableModuleReference>>(reference) ResolvedVc::try_downcast::<Box<dyn ChunkableModuleReference>>(reference)
{ {
match &*chunkable.chunking_type().await? { match &*chunkable.chunking_type().await? {
None => {} None => key.clone(),
Some(ChunkingType::Parallel { .. }) => key = parallel_reference_ty(), Some(ChunkingType::Parallel { inherit_async, .. }) => {
Some(ChunkingType::Async) => key = async_reference_ty(), if *inherit_async {
Some(ChunkingType::Isolated { .. }) => key = isolated_reference_ty(), parallel_inherit_async_reference_ty()
Some(ChunkingType::Shared { .. }) => key = shared_reference_ty(), } else {
Some(ChunkingType::Traced) => key = traced_reference_ty(), parallel_reference_ty()
}
} }
Some(ChunkingType::Async) => async_reference_ty(),
Some(ChunkingType::Isolated { .. }) => isolated_reference_ty(),
Some(ChunkingType::Shared { .. }) => shared_reference_ty(),
Some(ChunkingType::Traced) => traced_reference_ty(),
} }
} else {
key.clone()
};
let key = key.to_resolved().await?;
for &module in reference for &module in reference
.resolve_reference() .resolve_reference()
.resolve() .resolve()
...@@ -98,7 +97,10 @@ pub async fn children_from_module_references( ...@@ -98,7 +97,10 @@ pub async fn children_from_module_references(
.await? .await?
.iter() .iter()
{ {
children.insert((key, IntrospectableModule::new(*module).to_resolved().await?)); children.insert((
key.clone(),
IntrospectableModule::new(*module).to_resolved().await?,
));
} }
for &output_asset in reference for &output_asset in reference
.resolve_reference() .resolve_reference()
...@@ -107,7 +109,7 @@ pub async fn children_from_module_references( ...@@ -107,7 +109,7 @@ pub async fn children_from_module_references(
.iter() .iter()
{ {
children.insert(( children.insert((
key, key.clone(),
IntrospectableOutputAsset::new(*output_asset) IntrospectableOutputAsset::new(*output_asset)
.to_resolved() .to_resolved()
.await?, .await?,
...@@ -121,12 +123,12 @@ pub async fn children_from_module_references( ...@@ -121,12 +123,12 @@ pub async fn children_from_module_references(
pub async fn children_from_output_assets( pub async fn children_from_output_assets(
references: Vc<OutputAssets>, references: Vc<OutputAssets>,
) -> Result<Vc<IntrospectableChildren>> { ) -> Result<Vc<IntrospectableChildren>> {
let key = reference_ty().to_resolved().await?; let key = reference_ty();
let mut children = FxIndexSet::default(); let mut children = FxIndexSet::default();
let references = references.await?; let references = references.await?;
for &reference in &*references { for &reference in &*references {
children.insert(( children.insert((
key, key.clone(),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(reference)) IntrospectableOutputAsset::new(*ResolvedVc::upcast(reference))
.to_resolved() .to_resolved()
.await?, .await?,
......
...@@ -49,7 +49,7 @@ impl ModuleReferences { ...@@ -49,7 +49,7 @@ impl ModuleReferences {
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct SingleModuleReference { pub struct SingleModuleReference {
asset: ResolvedVc<Box<dyn Module>>, asset: ResolvedVc<Box<dyn Module>>,
description: ResolvedVc<RcStr>, description: RcStr,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -64,7 +64,7 @@ impl ModuleReference for SingleModuleReference { ...@@ -64,7 +64,7 @@ impl ModuleReference for SingleModuleReference {
impl ValueToString for SingleModuleReference { impl ValueToString for SingleModuleReference {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
*self.description Vc::cell(self.description.clone())
} }
} }
...@@ -73,7 +73,7 @@ impl SingleModuleReference { ...@@ -73,7 +73,7 @@ impl SingleModuleReference {
/// Create a new [Vc<SingleModuleReference>] that resolves to the given /// Create a new [Vc<SingleModuleReference>] that resolves to the given
/// asset. /// asset.
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: ResolvedVc<RcStr>) -> Vc<Self> { pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: RcStr) -> Vc<Self> {
Self::cell(SingleModuleReference { asset, description }) Self::cell(SingleModuleReference { asset, description })
} }
...@@ -87,13 +87,13 @@ impl SingleModuleReference { ...@@ -87,13 +87,13 @@ impl SingleModuleReference {
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct SingleChunkableModuleReference { pub struct SingleChunkableModuleReference {
asset: ResolvedVc<Box<dyn Module>>, asset: ResolvedVc<Box<dyn Module>>,
description: ResolvedVc<RcStr>, description: RcStr,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl SingleChunkableModuleReference { impl SingleChunkableModuleReference {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: ResolvedVc<RcStr>) -> Vc<Self> { pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: RcStr) -> Vc<Self> {
Self::cell(SingleChunkableModuleReference { asset, description }) Self::cell(SingleChunkableModuleReference { asset, description })
} }
} }
...@@ -121,7 +121,7 @@ impl ModuleReference for SingleChunkableModuleReference { ...@@ -121,7 +121,7 @@ impl ModuleReference for SingleChunkableModuleReference {
impl ValueToString for SingleChunkableModuleReference { impl ValueToString for SingleChunkableModuleReference {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
*self.description Vc::cell(self.description.clone())
} }
} }
...@@ -129,7 +129,7 @@ impl ValueToString for SingleChunkableModuleReference { ...@@ -129,7 +129,7 @@ impl ValueToString for SingleChunkableModuleReference {
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct SingleOutputAssetReference { pub struct SingleOutputAssetReference {
asset: ResolvedVc<Box<dyn OutputAsset>>, asset: ResolvedVc<Box<dyn OutputAsset>>,
description: ResolvedVc<RcStr>, description: RcStr,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -144,7 +144,7 @@ impl ModuleReference for SingleOutputAssetReference { ...@@ -144,7 +144,7 @@ impl ModuleReference for SingleOutputAssetReference {
impl ValueToString for SingleOutputAssetReference { impl ValueToString for SingleOutputAssetReference {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
*self.description Vc::cell(self.description.clone())
} }
} }
...@@ -153,10 +153,7 @@ impl SingleOutputAssetReference { ...@@ -153,10 +153,7 @@ impl SingleOutputAssetReference {
/// Create a new [Vc<SingleOutputAssetReference>] that resolves to the given /// Create a new [Vc<SingleOutputAssetReference>] that resolves to the given
/// asset. /// asset.
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new( pub fn new(asset: ResolvedVc<Box<dyn OutputAsset>>, description: RcStr) -> Vc<Self> {
asset: ResolvedVc<Box<dyn OutputAsset>>,
description: ResolvedVc<RcStr>,
) -> Vc<Self> {
Self::cell(SingleOutputAssetReference { asset, description }) Self::cell(SingleOutputAssetReference { asset, description })
} }
......
...@@ -10,7 +10,7 @@ use anyhow::{Result, bail}; ...@@ -10,7 +10,7 @@ use anyhow::{Result, bail};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::{Instrument, Level}; use tracing::{Instrument, Level};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, SliceMap, TaskInput, FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, SliceMap, TaskInput,
TryJoinIterExt, Value, ValueToString, Vc, trace::TraceRawVcs, TryJoinIterExt, Value, ValueToString, Vc, trace::TraceRawVcs,
...@@ -1270,7 +1270,7 @@ async fn imports_field(lookup_path: Vc<FileSystemPath>) -> Result<Vc<ImportsFiel ...@@ -1270,7 +1270,7 @@ async fn imports_field(lookup_path: Vc<FileSystemPath>) -> Result<Vc<ImportsFiel
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn package_json() -> Vc<Vec<RcStr>> { pub fn package_json() -> Vc<Vec<RcStr>> {
Vc::cell(vec!["package.json".into()]) Vc::cell(vec![rcstr!("package.json")])
} }
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
...@@ -1326,7 +1326,7 @@ pub async fn find_context_file_or_package_key( ...@@ -1326,7 +1326,7 @@ pub async fn find_context_file_or_package_key(
package_key: Value<RcStr>, package_key: Value<RcStr>,
) -> Result<Vc<FindContextFileResult>> { ) -> Result<Vc<FindContextFileResult>> {
let mut refs = Vec::new(); let mut refs = Vec::new();
let package_json_path = lookup_path.join("package.json".into()); let package_json_path = lookup_path.join(rcstr!("package.json"));
if let Some(package_json_path) = exists(package_json_path, &mut refs).await? { if let Some(package_json_path) = exists(package_json_path, &mut refs).await? {
if let Some(json) = &*read_package_json(*package_json_path).await? { if let Some(json) = &*read_package_json(*package_json_path).await? {
if json.get(&**package_key).is_some() { if json.get(&**package_key).is_some() {
...@@ -1519,7 +1519,7 @@ pub async fn resolve_raw( ...@@ -1519,7 +1519,7 @@ pub async fn resolve_raw(
.and_then(|pat| pat.filter_could_not_match("/ROOT/fsd8nz8og54z")) .and_then(|pat| pat.filter_could_not_match("/ROOT/fsd8nz8og54z"))
{ {
let path = Pattern::new(pat); let path = Pattern::new(pat);
let matches = read_matches(lookup_dir.root(), "/ROOT/".into(), true, path).await?; let matches = read_matches(lookup_dir.root(), rcstr!("/ROOT/"), true, path).await?;
if matches.len() > 10000 { if matches.len() > 10000 {
let path_str = path.to_string().await?; let path_str = path.to_string().await?;
println!( println!(
...@@ -1538,7 +1538,7 @@ pub async fn resolve_raw( ...@@ -1538,7 +1538,7 @@ pub async fn resolve_raw(
} }
{ {
let matches = read_matches(lookup_dir, "".into(), force_in_lookup_dir, path).await?; let matches = read_matches(lookup_dir, rcstr!(""), force_in_lookup_dir, path).await?;
if matches.len() > 10000 { if matches.len() > 10000 {
println!( println!(
"WARN: resolving pattern {} in {} leads to {} results", "WARN: resolving pattern {} in {} leads to {} results",
...@@ -1834,7 +1834,7 @@ async fn resolve_internal_inline( ...@@ -1834,7 +1834,7 @@ async fn resolve_internal_inline(
let mut results = Vec::new(); let mut results = Vec::new();
let matches = read_matches( let matches = read_matches(
lookup_path, lookup_path,
"".into(), rcstr!(""),
*force_in_lookup_dir, *force_in_lookup_dir,
Pattern::new(path.clone()).resolve().await?, Pattern::new(path.clone()).resolve().await?,
) )
...@@ -1927,7 +1927,7 @@ async fn resolve_internal_inline( ...@@ -1927,7 +1927,7 @@ async fn resolve_internal_inline(
fragment, fragment,
} => { } => {
let mut new_pat = path.clone(); let mut new_pat = path.clone();
new_pat.push_front(RcStr::from(".").into()); new_pat.push_front(rcstr!(".").into());
let relative = let relative =
Request::relative(Value::new(new_pat), query.clone(), fragment.clone(), true); Request::relative(Value::new(new_pat), query.clone(), fragment.clone(), true);
...@@ -2101,7 +2101,7 @@ async fn resolve_into_folder( ...@@ -2101,7 +2101,7 @@ async fn resolve_into_folder(
package_path: ResolvedVc<FileSystemPath>, package_path: ResolvedVc<FileSystemPath>,
options: Vc<ResolveOptions>, options: Vc<ResolveOptions>,
) -> Result<Vc<ResolveResult>> { ) -> Result<Vc<ResolveResult>> {
let package_json_path = package_path.join("package.json".into()); let package_json_path = package_path.join(rcstr!("package.json"));
let options_value = options.await?; let options_value = options.await?;
for resolve_into_package in options_value.into_package.iter() { for resolve_into_package in options_value.into_package.iter() {
...@@ -2133,7 +2133,7 @@ async fn resolve_into_folder( ...@@ -2133,7 +2133,7 @@ async fn resolve_into_folder(
// we continue to try other alternatives // we continue to try other alternatives
if !result.is_unresolvable_ref() { if !result.is_unresolvable_ref() {
let mut result: ResolveResultBuilder = let mut result: ResolveResultBuilder =
result.with_request_ref(".".into()).into(); result.with_request_ref(rcstr!(".")).into();
result.affecting_sources.push(ResolvedVc::upcast( result.affecting_sources.push(ResolvedVc::upcast(
FileSource::new(package_json_path).to_resolved().await?, FileSource::new(package_json_path).to_resolved().await?,
)); ));
...@@ -2166,7 +2166,7 @@ async fn resolve_into_folder( ...@@ -2166,7 +2166,7 @@ async fn resolve_into_folder(
Ok(resolve_internal_inline(*package_path, request, options) Ok(resolve_internal_inline(*package_path, request, options)
.await? .await?
.with_request(".".into())) .with_request(rcstr!(".")))
} }
#[tracing::instrument(level = Level::TRACE, skip_all)] #[tracing::instrument(level = Level::TRACE, skip_all)]
...@@ -2231,23 +2231,23 @@ async fn resolve_relative_request( ...@@ -2231,23 +2231,23 @@ async fn resolve_relative_request(
Some((base, "js")) => ( Some((base, "js")) => (
base, base,
vec![ vec![
Pattern::Constant(".ts".into()), Pattern::Constant(rcstr!(".ts")),
Pattern::Constant(".tsx".into()), Pattern::Constant(rcstr!(".tsx")),
Pattern::Constant(".js".into()), Pattern::Constant(rcstr!(".js")),
], ],
), ),
Some((base, "mjs")) => ( Some((base, "mjs")) => (
base, base,
vec![ vec![
Pattern::Constant(".mts".into()), Pattern::Constant(rcstr!(".mts")),
Pattern::Constant(".mjs".into()), Pattern::Constant(rcstr!(".mjs")),
], ],
), ),
Some((base, "cjs")) => ( Some((base, "cjs")) => (
base, base,
vec![ vec![
Pattern::Constant(".cts".into()), Pattern::Constant(rcstr!(".cts")),
Pattern::Constant(".cjs".into()), Pattern::Constant(rcstr!(".cjs")),
], ],
), ),
_ => { _ => {
...@@ -2269,7 +2269,7 @@ async fn resolve_relative_request( ...@@ -2269,7 +2269,7 @@ async fn resolve_relative_request(
let mut results = Vec::new(); let mut results = Vec::new();
let matches = read_matches( let matches = read_matches(
lookup_path, lookup_path,
"".into(), rcstr!(""),
force_in_lookup_dir, force_in_lookup_dir,
Pattern::new(new_path).resolve().await?, Pattern::new(new_path).resolve().await?,
) )
...@@ -2588,7 +2588,7 @@ async fn resolve_module_request( ...@@ -2588,7 +2588,7 @@ async fn resolve_module_request(
FindPackageItem::PackageFile(package_path) => { FindPackageItem::PackageFile(package_path) => {
if path.is_match("") { if path.is_match("") {
let resolved = resolved( let resolved = resolved(
RequestKey::new(".".into()), RequestKey::new(rcstr!(".")),
*package_path, *package_path,
lookup_path, lookup_path,
request, request,
...@@ -2606,13 +2606,13 @@ async fn resolve_module_request( ...@@ -2606,13 +2606,13 @@ async fn resolve_module_request(
let module_result = let module_result =
merge_results_with_affecting_sources(results, result.affecting_sources.clone()) merge_results_with_affecting_sources(results, result.affecting_sources.clone())
.with_replaced_request_key(".".into(), Value::new(RequestKey::new(module.into()))); .with_replaced_request_key(rcstr!("."), Value::new(RequestKey::new(module.into())));
if options_value.prefer_relative { if options_value.prefer_relative {
let module_prefix: RcStr = format!("./{module}").into(); let module_prefix: RcStr = format!("./{module}").into();
let pattern = Pattern::concat([ let pattern = Pattern::concat([
module_prefix.clone().into(), module_prefix.clone().into(),
RcStr::from("/").into(), rcstr!("/").into(),
path.clone(), path.clone(),
]); ]);
let relative = Request::relative(Value::new(pattern), query, fragment, true) let relative = Request::relative(Value::new(pattern), query, fragment, true)
...@@ -2652,7 +2652,7 @@ async fn resolve_into_package( ...@@ -2652,7 +2652,7 @@ async fn resolve_into_package(
conditions, conditions,
unspecified_conditions, unspecified_conditions,
} => { } => {
let package_json_path = package_path.join("package.json".into()); let package_json_path = package_path.join(rcstr!("package.json"));
let ExportsFieldResult::Some(exports_field) = let ExportsFieldResult::Some(exports_field) =
&*exports_field(package_json_path).await? &*exports_field(package_json_path).await?
else { else {
...@@ -2700,7 +2700,7 @@ async fn resolve_into_package( ...@@ -2700,7 +2700,7 @@ async fn resolve_into_package(
if could_match_others { if could_match_others {
let mut new_pat = path.clone(); let mut new_pat = path.clone();
new_pat.push_front(RcStr::from(".").into()); new_pat.push_front(rcstr!(".").into());
let relative = Request::relative(Value::new(new_pat), query, fragment, true) let relative = Request::relative(Value::new(new_pat), query, fragment, true)
.to_resolved() .to_resolved()
...@@ -2911,7 +2911,7 @@ async fn handle_exports_imports_field( ...@@ -2911,7 +2911,7 @@ async fn handle_exports_imports_field(
for (result_path, conditions) in results { for (result_path, conditions) in results {
if let Some(result_path) = result_path.with_normalized_path() { if let Some(result_path) = result_path.with_normalized_path() {
let request = Request::parse(Value::new(Pattern::Concatenation(vec![ let request = Request::parse(Value::new(Pattern::Concatenation(vec![
Pattern::Constant("./".into()), Pattern::Constant(rcstr!("./")),
result_path, result_path,
]))) ])))
.to_resolved() .to_resolved()
......
...@@ -2,7 +2,7 @@ use std::{collections::BTreeMap, future::Future, pin::Pin}; ...@@ -2,7 +2,7 @@ use std::{collections::BTreeMap, future::Future, pin::Pin};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, NonLocalValue, ResolvedVc, TryJoinIterExt, Value, ValueToString, Vc, FxIndexSet, NonLocalValue, ResolvedVc, TryJoinIterExt, Value, ValueToString, Vc,
debug::ValueDebugFormat, trace::TraceRawVcs, debug::ValueDebugFormat, trace::TraceRawVcs,
...@@ -463,9 +463,9 @@ impl ValueToString for ImportMapResult { ...@@ -463,9 +463,9 @@ impl ValueToString for ImportMapResult {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn to_string(&self) -> Result<Vc<RcStr>> { async fn to_string(&self) -> Result<Vc<RcStr>> {
match self { match self {
ImportMapResult::Result(_) => Ok(Vc::cell("Resolved by import map".into())), ImportMapResult::Result(_) => Ok(Vc::cell(rcstr!("Resolved by import map"))),
ImportMapResult::External(_, _, _) => Ok(Vc::cell("TODO external".into())), ImportMapResult::External(_, _, _) => Ok(Vc::cell(rcstr!("TODO external"))),
ImportMapResult::AliasExternal { .. } => Ok(Vc::cell("TODO external".into())), ImportMapResult::AliasExternal { .. } => Ok(Vc::cell(rcstr!("TODO external"))),
ImportMapResult::Alias(request, context) => { ImportMapResult::Alias(request, context) => {
let s = if let Some(path) = context { let s = if let Some(path) = context {
let path = path.to_string().await?; let path = path.to_string().await?;
...@@ -491,7 +491,7 @@ impl ValueToString for ImportMapResult { ...@@ -491,7 +491,7 @@ impl ValueToString for ImportMapResult {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Ok(Vc::cell(strings.join(" | ").into())) Ok(Vc::cell(strings.join(" | ").into()))
} }
ImportMapResult::NoEntry => Ok(Vc::cell("No import map entry".into())), ImportMapResult::NoEntry => Ok(Vc::cell(rcstr!("No import map entry"))),
} }
} }
} }
......
use anyhow::{Ok, Result}; use anyhow::{Ok, Result};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use regex::Regex; use regex::Regex;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, Value, ValueToString, Vc};
use super::pattern::Pattern; use super::pattern::Pattern;
...@@ -124,7 +124,7 @@ impl Request { ...@@ -124,7 +124,7 @@ impl Request {
path: Pattern::Constant(path), path: Pattern::Constant(path),
.. ..
} => path.clone(), } => path.clone(),
Request::Empty => "".into(), Request::Empty => rcstr!(""),
Request::PackageInternal { Request::PackageInternal {
path: Pattern::Constant(path), path: Pattern::Constant(path),
.. ..
...@@ -158,7 +158,7 @@ impl Request { ...@@ -158,7 +158,7 @@ impl Request {
if let Some(remainder) = r.strip_prefix("//") { if let Some(remainder) = r.strip_prefix("//") {
return Ok(Request::Uri { return Ok(Request::Uri {
protocol: "//".into(), protocol: rcstr!("//"),
remainder: remainder.into(), remainder: remainder.into(),
query: RcStr::default(), query: RcStr::default(),
fragment: RcStr::default(), fragment: RcStr::default(),
...@@ -380,12 +380,12 @@ impl Request { ...@@ -380,12 +380,12 @@ impl Request {
Self::parse(Value::new(pat)) Self::parse(Value::new(pat))
} }
Request::PackageInternal { path } => { Request::PackageInternal { path } => {
let mut pat = Pattern::Constant("./".into()); let mut pat = Pattern::Constant(rcstr!("./"));
pat.push(path.clone()); pat.push(path.clone());
Self::parse(Value::new(pat)) Self::parse(Value::new(pat))
} }
Request::Unknown { path } => { Request::Unknown { path } => {
let mut pat = Pattern::Constant("./".into()); let mut pat = Pattern::Constant(rcstr!("./"));
pat.push(path.clone()); pat.push(path.clone());
Self::parse(Value::new(pat)) Self::parse(Value::new(pat))
} }
...@@ -717,7 +717,7 @@ impl Request { ...@@ -717,7 +717,7 @@ impl Request {
} }
Request::ServerRelative { path, .. } => path.clone(), Request::ServerRelative { path, .. } => path.clone(),
Request::Windows { path, .. } => path.clone(), Request::Windows { path, .. } => path.clone(),
Request::Empty => Pattern::Constant("".into()), Request::Empty => Pattern::Constant(rcstr!("")),
Request::PackageInternal { path } => path.clone(), Request::PackageInternal { path } => path.clone(),
Request::DataUri { Request::DataUri {
media_type, media_type,
...@@ -785,7 +785,7 @@ impl ValueToString for Request { ...@@ -785,7 +785,7 @@ impl ValueToString for Request {
} }
Request::ServerRelative { path, .. } => format!("server relative {path}").into(), Request::ServerRelative { path, .. } => format!("server relative {path}").into(),
Request::Windows { path, .. } => format!("windows {path}").into(), Request::Windows { path, .. } => format!("windows {path}").into(),
Request::Empty => "empty".into(), Request::Empty => rcstr!("empty"),
Request::PackageInternal { path } => format!("package internal {path}").into(), Request::PackageInternal { path } => format!("package internal {path}").into(),
Request::DataUri { Request::DataUri {
media_type, media_type,
...@@ -802,7 +802,7 @@ impl ValueToString for Request { ...@@ -802,7 +802,7 @@ impl ValueToString for Request {
.. ..
} => format!("uri \"{protocol}\" \"{remainder}\"").into(), } => format!("uri \"{protocol}\" \"{remainder}\"").into(),
Request::Unknown { path } => format!("unknown {path}").into(), Request::Unknown { path } => format!("unknown {path}").into(),
Request::Dynamic => "dynamic".into(), Request::Dynamic => rcstr!("dynamic"),
Request::Alternatives { requests } => { Request::Alternatives { requests } => {
let vec = requests.iter().map(|i| i.to_string()).try_join().await?; let vec = requests.iter().map(|i| i.to_string()).try_join().await?;
vec.iter() vec.iter()
...@@ -835,7 +835,7 @@ mod tests { ...@@ -835,7 +835,7 @@ mod tests {
fn test_split_query_fragment() { fn test_split_query_fragment() {
assert_eq!( assert_eq!(
( (
Pattern::Constant("foo".into()), Pattern::Constant(rcstr!("foo")),
RcStr::default(), RcStr::default(),
RcStr::default() RcStr::default()
), ),
...@@ -845,42 +845,42 @@ mod tests { ...@@ -845,42 +845,42 @@ mod tests {
// from `import './foo'`, ditto for fragments. // from `import './foo'`, ditto for fragments.
assert_eq!( assert_eq!(
( (
Pattern::Constant("foo".into()), Pattern::Constant(rcstr!("foo")),
RcStr::from("?"), rcstr!("?"),
RcStr::default() RcStr::default()
), ),
split_off_query_fragment("foo?") split_off_query_fragment("foo?")
); );
assert_eq!( assert_eq!(
( (
Pattern::Constant("foo".into()), Pattern::Constant(rcstr!("foo")),
RcStr::default(), RcStr::default(),
RcStr::from("#") rcstr!("#")
), ),
split_off_query_fragment("foo#") split_off_query_fragment("foo#")
); );
assert_eq!( assert_eq!(
( (
Pattern::Constant("foo".into()), Pattern::Constant(rcstr!("foo")),
RcStr::from("?bar=baz"), rcstr!("?bar=baz"),
RcStr::default() RcStr::default()
), ),
split_off_query_fragment("foo?bar=baz") split_off_query_fragment("foo?bar=baz")
); );
assert_eq!( assert_eq!(
( (
Pattern::Constant("foo".into()), Pattern::Constant(rcstr!("foo")),
RcStr::default(), RcStr::default(),
RcStr::from("#stuff?bar=baz") rcstr!("#stuff?bar=baz")
), ),
split_off_query_fragment("foo#stuff?bar=baz") split_off_query_fragment("foo#stuff?bar=baz")
); );
assert_eq!( assert_eq!(
( (
Pattern::Constant("foo".into()), Pattern::Constant(rcstr!("foo")),
RcStr::from("?bar=baz"), rcstr!("?bar=baz"),
RcStr::from("#stuff") rcstr!("#stuff")
), ),
split_off_query_fragment("foo?bar=baz#stuff") split_off_query_fragment("foo?bar=baz#stuff")
); );
......
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ValueToString, Vc}; use turbo_tasks::{ValueToString, Vc};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent, FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent,
...@@ -53,6 +53,6 @@ impl FileSystem for ServerFileSystem { ...@@ -53,6 +53,6 @@ impl FileSystem for ServerFileSystem {
impl ValueToString for ServerFileSystem { impl ValueToString for ServerFileSystem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("root-of-the-server".into()) Vc::cell(rcstr!("root-of-the-server"))
} }
} }
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, NonLocalValue, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, FxIndexSet, NonLocalValue, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat,
trace::TraceRawVcs, trace::TraceRawVcs,
...@@ -77,9 +77,9 @@ impl OutputAsset for SourceMapAsset { ...@@ -77,9 +77,9 @@ impl OutputAsset for SourceMapAsset {
chunking_context, chunking_context,
ident_for_path, ident_for_path,
} => chunking_context } => chunking_context
.chunk_path(Some(Vc::upcast(self)), *ident_for_path, ".js".into()) .chunk_path(Some(Vc::upcast(self)), *ident_for_path, rcstr!(".js"))
.append(".map".into()), .append(rcstr!(".map")),
PathType::Fixed { path } => path.append(".map".into()), PathType::Fixed { path } => path.append(rcstr!(".map")),
}) })
} }
} }
...@@ -98,21 +98,11 @@ impl Asset for SourceMapAsset { ...@@ -98,21 +98,11 @@ impl Asset for SourceMapAsset {
} }
} }
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("source map".into())
}
#[turbo_tasks::function]
fn introspectable_details() -> Vc<RcStr> {
Vc::cell("source map of an asset".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for SourceMapAsset { impl Introspectable for SourceMapAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
introspectable_type() Vc::cell(rcstr!("source map"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -122,7 +112,7 @@ impl Introspectable for SourceMapAsset { ...@@ -122,7 +112,7 @@ impl Introspectable for SourceMapAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
fn details(&self) -> Vc<RcStr> { fn details(&self) -> Vc<RcStr> {
introspectable_details() Vc::cell(rcstr!("source map of an asset"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -131,7 +121,7 @@ impl Introspectable for SourceMapAsset { ...@@ -131,7 +121,7 @@ impl Introspectable for SourceMapAsset {
if let Some(asset) = if let Some(asset) =
ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.generate_source_map) ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.generate_source_map)
{ {
children.insert((ResolvedVc::cell("asset".into()), asset)); children.insert((rcstr!("asset"), asset));
} }
Ok(Vc::cell(children)) Ok(Vc::cell(children))
} }
......
...@@ -411,21 +411,11 @@ pub trait CssChunkItem: ChunkItem { ...@@ -411,21 +411,11 @@ pub trait CssChunkItem: ChunkItem {
fn content(self: Vc<Self>) -> Vc<CssChunkItemContent>; fn content(self: Vc<Self>) -> Vc<CssChunkItemContent>;
} }
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("css chunk".into())
}
#[turbo_tasks::function]
fn entry_module_key() -> Vc<RcStr> {
Vc::cell("entry module".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for CssChunk { impl Introspectable for CssChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
introspectable_type() Vc::cell(rcstr!("css chunk"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -461,7 +451,7 @@ impl Introspectable for CssChunk { ...@@ -461,7 +451,7 @@ impl Introspectable for CssChunk {
.iter() .iter()
.map(|chunk_item| async move { .map(|chunk_item| async move {
Ok(( Ok((
entry_module_key().to_resolved().await?, rcstr!("entry module"),
IntrospectableModule::new(chunk_item.module()) IntrospectableModule::new(chunk_item.module())
.to_resolved() .to_resolved()
.await?, .await?,
...@@ -482,7 +472,7 @@ pub struct CssChunkType {} ...@@ -482,7 +472,7 @@ pub struct CssChunkType {}
impl ValueToString for CssChunkType { impl ValueToString for CssChunkType {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("css".into()) Vc::cell(rcstr!("css"))
} }
} }
......
...@@ -100,7 +100,7 @@ impl OutputAsset for SingleItemCssChunk { ...@@ -100,7 +100,7 @@ impl OutputAsset for SingleItemCssChunk {
Ok(self.await?.chunking_context.chunk_path( Ok(self.await?.chunking_context.chunk_path(
Some(Vc::upcast(self)), Some(Vc::upcast(self)),
self.ident_for_path(), self.ident_for_path(),
".single.css".into(), rcstr!(".single.css"),
)) ))
} }
...@@ -156,21 +156,11 @@ impl GenerateSourceMap for SingleItemCssChunk { ...@@ -156,21 +156,11 @@ impl GenerateSourceMap for SingleItemCssChunk {
} }
} }
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("single asset css chunk".into())
}
#[turbo_tasks::function]
fn entry_module_key() -> Vc<RcStr> {
Vc::cell("entry module".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for SingleItemCssChunk { impl Introspectable for SingleItemCssChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
introspectable_type() Vc::cell(rcstr!("single asset css chunk"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -13,7 +13,7 @@ use rustc_hash::FxHashMap; ...@@ -13,7 +13,7 @@ use rustc_hash::FxHashMap;
use smallvec::smallvec; use smallvec::smallvec;
use swc_core::base::sourcemap::SourceMapBuilder; use swc_core::base::sourcemap::SourceMapBuilder;
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{FileContent, FileSystemPath, rope::Rope}; use turbo_tasks_fs::{FileContent, FileSystemPath, rope::Rope};
use turbopack_core::{ use turbopack_core::{
...@@ -434,7 +434,7 @@ async fn process_content( ...@@ -434,7 +434,7 @@ async fn process_content(
ParsingIssue { ParsingIssue {
file: fs_path_vc, file: fs_path_vc,
msg: ResolvedVc::cell(err.to_string().into()), msg: err.to_string().into(),
source, source,
} }
.resolved_cell() .resolved_cell()
...@@ -471,7 +471,7 @@ async fn process_content( ...@@ -471,7 +471,7 @@ async fn process_content(
}; };
ParsingIssue { ParsingIssue {
file: fs_path_vc, file: fs_path_vc,
msg: ResolvedVc::cell(e.to_string().into()), msg: e.to_string().into(),
source, source,
} }
.resolved_cell() .resolved_cell()
...@@ -520,9 +520,8 @@ impl CssError { ...@@ -520,9 +520,8 @@ impl CssError {
CssError::CssSelectorInModuleNotPure { selector } => { CssError::CssSelectorInModuleNotPure { selector } => {
ParsingIssue { ParsingIssue {
file, file,
msg: ResolvedVc::cell( msg: format!("{CSS_MODULE_ERROR}, (lightningcss, {selector})").into(),
format!("{CSS_MODULE_ERROR}, (lightningcss, {selector})").into(),
),
source: None, source: None,
} }
.resolved_cell() .resolved_cell()
...@@ -617,7 +616,7 @@ fn generate_css_source_map(source_map: &parcel_sourcemap::SourceMap) -> Result<R ...@@ -617,7 +616,7 @@ fn generate_css_source_map(source_map: &parcel_sourcemap::SourceMap) -> Result<R
#[turbo_tasks::value] #[turbo_tasks::value]
struct ParsingIssue { struct ParsingIssue {
msg: ResolvedVc<RcStr>, msg: RcStr,
file: ResolvedVc<FileSystemPath>, file: ResolvedVc<FileSystemPath>,
source: Option<IssueSource>, source: Option<IssueSource>,
} }
...@@ -636,7 +635,7 @@ impl Issue for ParsingIssue { ...@@ -636,7 +635,7 @@ impl Issue for ParsingIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> { fn title(&self) -> Vc<StyledString> {
StyledString::Text("Parsing css source code failed".into()).cell() StyledString::Text(rcstr!("Parsing css source code failed")).cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -650,7 +649,7 @@ impl Issue for ParsingIssue { ...@@ -650,7 +649,7 @@ impl Issue for ParsingIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn description(&self) -> Result<Vc<OptionStyledString>> { async fn description(&self) -> Result<Vc<OptionStyledString>> {
Ok(Vc::cell(Some( Ok(Vc::cell(Some(
StyledString::Text(self.msg.await?.as_str().into()).resolved_cell(), StyledString::Text(self.msg.clone()).resolved_cell(),
))) )))
} }
} }
......
...@@ -40,11 +40,6 @@ pub struct DevHtmlAsset { ...@@ -40,11 +40,6 @@ pub struct DevHtmlAsset {
body: Option<RcStr>, body: Option<RcStr>,
} }
#[turbo_tasks::function]
fn dev_html_chunk_reference_description() -> Vc<RcStr> {
Vc::cell("dev html chunk".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl OutputAsset for DevHtmlAsset { impl OutputAsset for DevHtmlAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -2,7 +2,7 @@ use std::{borrow::Cow, fmt::Display}; ...@@ -2,7 +2,7 @@ use std::{borrow::Cow, fmt::Display};
use anyhow::Result; use anyhow::Result;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadRef, ResolvedVc, TryJoinIterExt, Vc}; use turbo_tasks::{ReadRef, ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::{File, json::parse_json_with_source_context}; use turbo_tasks_fs::{File, json::parse_json_with_source_context};
use turbopack_core::{ use turbopack_core::{
...@@ -22,22 +22,30 @@ pub struct IntrospectionSource { ...@@ -22,22 +22,30 @@ pub struct IntrospectionSource {
pub roots: FxHashSet<ResolvedVc<Box<dyn Introspectable>>>, pub roots: FxHashSet<ResolvedVc<Box<dyn Introspectable>>>,
} }
fn introspection_source() -> RcStr {
rcstr!("introspection-source")
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for IntrospectionSource { impl Introspectable for IntrospectionSource {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
Vc::cell("introspection-source".into()) Vc::cell(introspection_source())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn title(&self) -> Vc<RcStr> { fn title(&self) -> Vc<RcStr> {
Vc::cell("introspection-source".into()) Vc::cell(introspection_source())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn children(&self) -> Vc<IntrospectableChildren> { fn children(&self) -> Vc<IntrospectableChildren> {
let name = ResolvedVc::cell("root".into()); Vc::cell(
Vc::cell(self.roots.iter().map(|root| (name, *root)).collect()) self.roots
.iter()
.map(|root| (rcstr!("root"), *root))
.collect(),
)
} }
} }
...@@ -127,9 +135,7 @@ impl GetContentSourceContent for IntrospectionSource { ...@@ -127,9 +135,7 @@ impl GetContentSourceContent for IntrospectionSource {
let has_children = !children.is_empty(); let has_children = !children.is_empty();
let children = children let children = children
.iter() .iter()
.map(|&(name, child)| async move { .map(|(name, child)| async move {
let name = name.await;
let name = str_or_err(&name);
let ty = child.ty().await; let ty = child.ty().await;
let ty = str_or_err(&ty); let ty = str_or_err(&ty);
let title = child.title().await; let title = child.title().await;
......
...@@ -2,7 +2,7 @@ use std::{collections::VecDeque, iter::once}; ...@@ -2,7 +2,7 @@ use std::{collections::VecDeque, iter::once};
use anyhow::Result; use anyhow::Result;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
Completion, FxIndexMap, FxIndexSet, ResolvedVc, State, TryJoinIterExt, Value, ValueToString, Completion, FxIndexMap, FxIndexSet, ResolvedVc, State, TryJoinIterExt, Value, ValueToString,
Vc, fxindexset, Vc, fxindexset,
...@@ -177,7 +177,7 @@ async fn expand( ...@@ -177,7 +177,7 @@ async fn expand(
} }
for (sub_path, asset) in assets { for (sub_path, asset) in assets {
if &*sub_path == "index.html" { if &*sub_path == "index.html" {
map.insert("".into(), asset); map.insert(rcstr!(""), asset);
} else if let Some(p) = sub_path.strip_suffix("/index.html") { } else if let Some(p) = sub_path.strip_suffix("/index.html") {
map.insert(p.into(), asset); map.insert(p.into(), asset);
map.insert(format!("{p}/").into(), asset); map.insert(format!("{p}/").into(), asset);
...@@ -192,7 +192,7 @@ async fn expand( ...@@ -192,7 +192,7 @@ async fn expand(
fn get_sub_paths(sub_path: &str) -> ([RcStr; 3], usize) { fn get_sub_paths(sub_path: &str) -> ([RcStr; 3], usize) {
let sub_paths_buffer: [RcStr; 3]; let sub_paths_buffer: [RcStr; 3];
let n = if sub_path == "index.html" { let n = if sub_path == "index.html" {
sub_paths_buffer = ["".into(), sub_path.into(), Default::default()]; sub_paths_buffer = [rcstr!(""), sub_path.into(), Default::default()];
2 2
} else if let Some(p) = sub_path.strip_suffix("/index.html") { } else if let Some(p) = sub_path.strip_suffix("/index.html") {
sub_paths_buffer = [p.into(), format!("{p}/").into(), sub_path.into()]; sub_paths_buffer = [p.into(), format!("{p}/").into(), sub_path.into()];
...@@ -293,16 +293,11 @@ impl ContentSourceSideEffect for AssetGraphGetContentSourceContent { ...@@ -293,16 +293,11 @@ impl ContentSourceSideEffect for AssetGraphGetContentSourceContent {
} }
} }
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("asset graph content source".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for AssetGraphContentSource { impl Introspectable for AssetGraphContentSource {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
introspectable_type() Vc::cell(rcstr!("asset graph content source"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -315,23 +310,20 @@ impl Introspectable for AssetGraphContentSource { ...@@ -315,23 +310,20 @@ impl Introspectable for AssetGraphContentSource {
Vc::cell(if let Some(expanded) = &self.expanded { Vc::cell(if let Some(expanded) = &self.expanded {
format!("{} assets expanded", expanded.get().len()).into() format!("{} assets expanded", expanded.get().len()).into()
} else { } else {
"eager".into() rcstr!("eager")
}) })
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn children(self: Vc<Self>) -> Result<Vc<IntrospectableChildren>> { async fn children(self: Vc<Self>) -> Result<Vc<IntrospectableChildren>> {
let this = self.await?; let this = self.await?;
let key = ResolvedVc::cell("root".into());
let inner_key = ResolvedVc::cell("inner".into());
let expanded_key = ResolvedVc::cell("expanded".into());
let root_assets = this.root_assets.await?; let root_assets = this.root_assets.await?;
let root_asset_children = root_assets let root_asset_children = root_assets
.iter() .iter()
.map(|&asset| async move { .map(|&asset| async move {
Ok(( Ok((
key, rcstr!("root"),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset)) IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset))
.to_resolved() .to_resolved()
.await?, .await?,
...@@ -346,7 +338,7 @@ impl Introspectable for AssetGraphContentSource { ...@@ -346,7 +338,7 @@ impl Introspectable for AssetGraphContentSource {
.filter(|&a| !root_assets.contains(a)) .filter(|&a| !root_assets.contains(a))
.map(|&asset| async move { .map(|&asset| async move {
Ok(( Ok((
inner_key, rcstr!("inner"),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset)) IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset))
.to_resolved() .to_resolved()
.await?, .await?,
...@@ -360,7 +352,7 @@ impl Introspectable for AssetGraphContentSource { ...@@ -360,7 +352,7 @@ impl Introspectable for AssetGraphContentSource {
.into_iter() .into_iter()
.chain(expanded_asset_children) .chain(expanded_asset_children)
.chain(once(( .chain(once((
expanded_key, rcstr!("expanded"),
ResolvedVc::upcast(FullyExpanded(self.to_resolved().await?).resolved_cell()), ResolvedVc::upcast(FullyExpanded(self.to_resolved().await?).resolved_cell()),
))) )))
.collect(), .collect(),
...@@ -368,11 +360,6 @@ impl Introspectable for AssetGraphContentSource { ...@@ -368,11 +360,6 @@ impl Introspectable for AssetGraphContentSource {
} }
} }
#[turbo_tasks::function]
fn fully_expanded_introspectable_type() -> Vc<RcStr> {
Vc::cell("fully expanded asset graph content source".into())
}
#[turbo_tasks::value] #[turbo_tasks::value]
struct FullyExpanded(ResolvedVc<AssetGraphContentSource>); struct FullyExpanded(ResolvedVc<AssetGraphContentSource>);
...@@ -380,7 +367,7 @@ struct FullyExpanded(ResolvedVc<AssetGraphContentSource>); ...@@ -380,7 +367,7 @@ struct FullyExpanded(ResolvedVc<AssetGraphContentSource>);
impl Introspectable for FullyExpanded { impl Introspectable for FullyExpanded {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
fully_expanded_introspectable_type() Vc::cell(rcstr!("fully expanded asset graph content source"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -391,14 +378,16 @@ impl Introspectable for FullyExpanded { ...@@ -391,14 +378,16 @@ impl Introspectable for FullyExpanded {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> { async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let source = self.0.await?; let source = self.0.await?;
let key = ResolvedVc::cell("asset".into());
let expanded_assets = let expanded_assets =
expand(&*source.root_assets.await?, &*source.root_path.await?, None).await?; expand(&*source.root_assets.await?, &*source.root_path.await?, None).await?;
let children = expanded_assets let children = expanded_assets
.iter() .iter()
.map(|(_k, &v)| async move { .map(|(_k, &v)| async move {
Ok((key, IntrospectableOutputAsset::new(*v).to_resolved().await?)) Ok((
rcstr!("asset"),
IntrospectableOutputAsset::new(*v).to_resolved().await?,
))
}) })
.try_join() .try_join()
.await? .await?
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
use turbopack_core::introspect::{Introspectable, IntrospectableChildren}; use turbopack_core::introspect::{Introspectable, IntrospectableChildren};
...@@ -47,7 +47,7 @@ impl ContentSource for CombinedContentSource { ...@@ -47,7 +47,7 @@ impl ContentSource for CombinedContentSource {
impl Introspectable for CombinedContentSource { impl Introspectable for CombinedContentSource {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
Vc::cell("combined content source".into()) Vc::cell(rcstr!("combined content source"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -85,7 +85,6 @@ impl Introspectable for CombinedContentSource { ...@@ -85,7 +85,6 @@ impl Introspectable for CombinedContentSource {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> { async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let source = ResolvedVc::cell("source".into());
Ok(Vc::cell( Ok(Vc::cell(
self.sources self.sources
.iter() .iter()
...@@ -95,7 +94,7 @@ impl Introspectable for CombinedContentSource { ...@@ -95,7 +94,7 @@ impl Introspectable for CombinedContentSource {
.await? .await?
.into_iter() .into_iter()
.flatten() .flatten()
.map(|i| (source, i)) .map(|i| (rcstr!("source"), i))
.collect(), .collect(),
)) ))
} }
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, ResolvedVc, State, TryJoinIterExt, Value, Vc}; use turbo_tasks::{Completion, ResolvedVc, State, Value, Vc};
use turbopack_core::introspect::{Introspectable, IntrospectableChildren}; use turbopack_core::introspect::{Introspectable, IntrospectableChildren};
use super::{ use super::{
...@@ -90,38 +90,20 @@ impl MapGetContentSourceContent for ConditionalContentSourceMapper { ...@@ -90,38 +90,20 @@ impl MapGetContentSourceContent for ConditionalContentSourceMapper {
} }
} }
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("conditional content source".into())
}
#[turbo_tasks::function]
fn activator_key() -> Vc<RcStr> {
Vc::cell("activator".into())
}
#[turbo_tasks::function]
fn action_key() -> Vc<RcStr> {
Vc::cell("action".into())
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Introspectable for ConditionalContentSource { impl Introspectable for ConditionalContentSource {
#[turbo_tasks::function] #[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> { fn ty(&self) -> Vc<RcStr> {
introspectable_type() Vc::cell(rcstr!("conditional content source"))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn details(&self) -> Vc<RcStr> { fn details(&self) -> Vc<RcStr> {
Vc::cell( Vc::cell(if *self.activated.get() {
if *self.activated.get() { rcstr!("activated")
"activated"
} else { } else {
"not activated" rcstr!("not activated")
} })
.into(),
)
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -139,16 +121,12 @@ impl Introspectable for ConditionalContentSource { ...@@ -139,16 +121,12 @@ impl Introspectable for ConditionalContentSource {
Ok(Vc::cell( Ok(Vc::cell(
[ [
ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.activator) ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.activator)
.map(|i| (activator_key(), i)), .map(|i| (rcstr!("activator"), i)),
ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.action) ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.action)
.map(|i| (action_key(), i)), .map(|i| (rcstr!("action"), i)),
] ]
.into_iter() .into_iter()
.flatten() .flatten()
.map(|(k, v)| async move { Ok((k.to_resolved().await?, v)) })
.try_join()
.await?
.into_iter()
.collect(), .collect(),
)) ))
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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