Unverified Commit 22899755 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] Adopt rcstr! more consistently (#80552)

Replace construction of `RcStr` instances on constant strings with the `rcstr!` macro which can shift construction costs to compile time and eliminate reference counting.

Performance impacts from all the dropped ref counts are minor but do exist

![image.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/AwJ29EfoPcPdLSwCZxAz/e82b0e64-5803-4883-a89f-3090f1e937ce.png)

There is also a small progression in max heap which makes sense, laying out the static rcstrs should be a somewhat easier job compared to mimalloc.
parent f6431004
......@@ -17,7 +17,7 @@ use next_api::{
use serde_json::json;
use tempfile::TempDir;
use tokio::runtime::Runtime;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
TransientInstance, TurboTasks, TurboTasksApi, Vc, backend::Backend, trace::TraceRawVcs,
};
......@@ -182,7 +182,7 @@ impl HmrBenchmark {
let test_app = create_test_app(module_count)?;
let project_container = {
let container = ProjectContainer::new(RcStr::from("hmr-benchmark"), true)
let container = ProjectContainer::new(rcstr!("hmr-benchmark"), true)
.to_resolved()
.await?;
......@@ -193,7 +193,7 @@ impl HmrBenchmark {
root_path: RcStr::from(root_path),
project_path: RcStr::from(project_path.clone()),
next_config: load_next_config(),
js_config: RcStr::from("{}"),
js_config: rcstr!("{}"),
env: vec![],
define_env: DefineEnv {
client: vec![],
......@@ -205,14 +205,14 @@ impl HmrBenchmark {
poll_interval: None,
},
dev: true,
encryption_key: RcStr::from("test-key"),
build_id: RcStr::from("development"),
encryption_key: rcstr!("test-key"),
build_id: rcstr!("development"),
preview_props: DraftModeOptions {
preview_mode_id: RcStr::from("development"),
preview_mode_encryption_key: RcStr::from("test-key"),
preview_mode_signing_key: RcStr::from("test-key"),
preview_mode_id: rcstr!("development"),
preview_mode_encryption_key: rcstr!("test-key"),
preview_mode_signing_key: rcstr!("test-key"),
},
browserslist_query: RcStr::from("last 2 versions"),
browserslist_query: rcstr!("last 2 versions"),
no_mangling: false,
current_node_js_version: RcStr::from("18.0.0"),
};
......
......@@ -12,7 +12,7 @@ use next_core::{
};
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
CollectiblesSource, FxIndexMap, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt,
ValueToString, Vc,
......@@ -440,15 +440,16 @@ impl Issue for CssGlobalImportIssue {
#[turbo_tasks::function]
async fn title(&self) -> Vc<StyledString> {
StyledString::Stack(vec![
StyledString::Text("Failed to compile".into()),
StyledString::Text(
StyledString::Text(rcstr!("Failed to compile")),
StyledString::Text(rcstr!(
"Global CSS cannot be imported from files other than your Custom <App>. Due to \
the Global nature of stylesheets, and to avoid conflicts, Please move all \
first-party global CSS imports to pages/_app.js. Or convert the import to \
Component-Level CSS (CSS Modules)."
.into(),
),
StyledString::Text("Read more: https://nextjs.org/docs/messages/css-global".into()),
)),
StyledString::Text(rcstr!(
"Read more: https://nextjs.org/docs/messages/css-global"
)),
])
.cell()
}
......
......@@ -8,7 +8,7 @@ use next_core::{
util::NextRuntime,
};
use swc_core::{
atoms::Atom,
atoms::{Atom, atom},
common::comments::Comments,
ecma::{
ast::{
......@@ -321,7 +321,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> {
ModuleItem::ModuleDecl(
ModuleDecl::ExportDefaultExpr(..) | ModuleDecl::ExportDefaultDecl(..),
) => {
exports.push("default".into());
exports.push(atom!("default"));
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(decl)) => match &decl.decl {
Decl::Class(c) => {
......@@ -354,7 +354,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> {
);
}
ExportSpecifier::Default(_) => {
exports.push("default".into());
exports.push(atom!("default"));
}
ExportSpecifier::Namespace(e) => {
exports.push(e.name.atom().clone());
......
......@@ -2,7 +2,7 @@ use anyhow::Result;
use rustc_hash::FxHashSet;
use serde::Serialize;
use tracing::{Level, instrument};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, ValueToString, Vc, fxindexmap,
};
......@@ -94,7 +94,7 @@ where
};
for asset in entry_assets {
let path = RcStr::from(normalize_client_path(&asset.path().await?.path));
let path = normalize_client_path(&asset.path().await?.path);
let Some(asset_len) = *asset.size_bytes().await? else {
continue;
......@@ -108,7 +108,7 @@ where
parents: if let Some(parents) = asset_parents.get(&asset) {
parents
.iter()
.map(async |c| Ok(normalize_client_path(&c.path().await?.path).into()))
.map(async |c| Ok(normalize_client_path(&c.path().await?.path)))
.try_join()
.await?
} else {
......@@ -117,7 +117,7 @@ where
children: if let Some(children) = asset_children.get(&asset) {
children
.iter()
.map(async |c| Ok(normalize_client_path(&c.path().await?.path).into()))
.map(async |c| Ok(normalize_client_path(&c.path().await?.path)))
.try_join()
.await?
} else {
......@@ -132,7 +132,7 @@ where
}
assets.push(WebpackStatsAsset {
ty: "asset".into(),
ty: rcstr!("asset"),
name: path.clone(),
chunk_names: vec![path],
size: asset_len,
......@@ -191,7 +191,7 @@ where
})
}
fn normalize_client_path(path: &str) -> String {
fn normalize_client_path(path: &str) -> RcStr {
let next_re = regex::Regex::new(r"^_next/").unwrap();
next_re.replace(path, ".next/").into()
}
......
......@@ -11,7 +11,7 @@ use next_api::{
project::{ProjectContainer, ProjectOptions},
route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk},
};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadConsistency, ResolvedVc, TransientInstance, TurboTasks, Vc, get_effects};
use turbo_tasks_backend::{NoopBackingStorage, TurboTasksBackend};
use turbo_tasks_malloc::TurboMalloc;
......@@ -41,7 +41,7 @@ pub async fn main_inner(
let project = tt
.run_once(async {
let project = ProjectContainer::new("next-build-test".into(), options.dev);
let project = ProjectContainer::new(rcstr!("next-build-test"), options.dev);
let project = project.to_resolved().await?;
project.initialize(options).await?;
Ok(project)
......
......@@ -12,6 +12,7 @@ use next_core::tracing_presets::{
TRACING_NEXT_TURBOPACK_TARGETS,
};
use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt};
use turbo_rcstr::rcstr;
use turbo_tasks::TurboTasks;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_malloc::TurboMalloc;
......@@ -159,30 +160,30 @@ fn main() {
let canonical_path = std::fs::canonicalize(absolute_dir).unwrap();
let options = ProjectOptions {
build_id: "test".into(),
build_id: rcstr!("test"),
define_env: DefineEnv {
client: vec![],
edge: vec![],
nodejs: vec![],
},
dev: true,
encryption_key: "deadbeef".into(),
encryption_key: rcstr!("deadbeef"),
env: vec![],
js_config: include_str!("../jsConfig.json").into(),
next_config: include_str!("../nextConfig.json").into(),
preview_props: next_api::project::DraftModeOptions {
preview_mode_encryption_key: "deadbeef".into(),
preview_mode_id: "test".into(),
preview_mode_signing_key: "deadbeef".into(),
preview_mode_encryption_key: rcstr!("deadbeef"),
preview_mode_id: rcstr!("test"),
preview_mode_signing_key: rcstr!("deadbeef"),
},
project_path: canonical_path.to_string_lossy().into(),
root_path: "/".into(),
root_path: rcstr!("/"),
watch: Default::default(),
browserslist_query: "last 1 Chrome versions, last 1 Firefox versions, last 1 \
Safari versions, last 1 Edge versions"
.into(),
no_mangling: false,
current_node_js_version: "18.0.0".into(),
current_node_js_version: rcstr!("18.0.0"),
};
let json = serde_json::to_string_pretty(&options).unwrap();
......
use anyhow::{Context, Result, bail};
use turbo_rcstr::rcstr;
use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{
......@@ -92,8 +93,8 @@ pub async fn bootstrap(
.await?;
let mut inner_assets = inner_assets.owned().await?;
inner_assets.insert("ENTRY".into(), asset);
inner_assets.insert("BOOTSTRAP_CONFIG".into(), config_asset);
inner_assets.insert(rcstr!("ENTRY"), asset);
inner_assets.insert(rcstr!("BOOTSTRAP_CONFIG"), config_asset);
let asset = asset_context
.process(
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Vc, fxindexmap};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{context::AssetContext, module::Module, reference_type::ReferenceType};
......@@ -27,15 +27,15 @@ pub async fn get_middleware_module(
project_root: FileSystemPath,
userland_module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_MIDDLEWARE_MODULE";
let inner = rcstr!("INNER_MIDDLEWARE_MODULE");
// Load the file from the next.js codebase.
let source = load_next_js_template(
"middleware.js",
project_root,
fxindexmap! {
"VAR_USERLAND" => INNER.into(),
"VAR_DEFINITION_PAGE" => "/middleware".into(),
"VAR_USERLAND" => inner.clone(),
"VAR_DEFINITION_PAGE" => rcstr!("/middleware"),
},
FxIndexMap::default(),
FxIndexMap::default(),
......@@ -43,7 +43,7 @@ pub async fn get_middleware_module(
.await?;
let inner_assets = fxindexmap! {
INNER.into() => userland_module
inner => userland_module
};
let module = asset_context
......
use std::io::Write;
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc, fxindexmap};
use turbo_tasks_fs::{self, File, FileSystemPath, rope::RopeBuilder};
use turbopack::ModuleAssetContext;
......@@ -92,7 +92,7 @@ pub async fn get_app_page_entry(
"VAR_MODULE_GLOBAL_ERROR" => if inner_assets.contains_key(GLOBAL_ERROR) {
GLOBAL_ERROR.into()
} else {
"next/dist/client/components/builtin/global-error".into()
rcstr!("next/dist/client/components/builtin/global-error")
},
},
fxindexmap! {
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc, fxindexmap};
use turbo_tasks_fs::FileSystemPath;
use turbopack::ModuleAssetContext;
......@@ -57,18 +57,17 @@ pub async fn get_app_route_entry(
let path = source.ident().path().owned().await?;
const INNER: &str = "INNER_APP_ROUTE";
let inner = rcstr!("INNER_APP_ROUTE");
let output_type: RcStr = next_config
.await?
.output
.as_ref()
.map(|o| match o {
OutputType::Standalone => "\"standalone\"".to_string(),
OutputType::Export => "\"export\"".to_string(),
OutputType::Standalone => rcstr!("\"standalone\""),
OutputType::Export => rcstr!("\"export\""),
})
.map(RcStr::from)
.unwrap_or_else(|| "\"\"".into());
.unwrap_or(rcstr!("\"\""));
// Load the file from the next.js codebase.
let virtual_source = load_next_js_template(
......@@ -81,7 +80,7 @@ pub async fn get_app_route_entry(
// TODO(alexkirsz) Is this necessary?
"VAR_DEFINITION_BUNDLE_PATH" => "".to_string().into(),
"VAR_RESOLVED_PAGE_PATH" => path.value_to_string().owned().await?,
"VAR_USERLAND" => INNER.into(),
"VAR_USERLAND" => inner.clone(),
},
fxindexmap! {
"nextConfigOutput" => output_type
......@@ -100,7 +99,7 @@ pub async fn get_app_route_entry(
.await?;
let inner_assets = fxindexmap! {
INNER.into() => userland_module
inner => userland_module
};
let mut rsc_entry = module_asset_context
......@@ -137,7 +136,7 @@ async fn wrap_edge_route(
page: AppPage,
next_config: Vc<NextConfig>,
) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_ROUTE_ENTRY";
let inner = rcstr!("INNER_ROUTE_ENTRY");
let next_config = &*next_config.await?;
......@@ -145,7 +144,7 @@ async fn wrap_edge_route(
"edge-app-route.js",
project_root.clone(),
fxindexmap! {
"VAR_USERLAND" => INNER.into(),
"VAR_USERLAND" => inner.clone(),
"VAR_PAGE" => page.to_string().into(),
},
fxindexmap! {
......@@ -156,7 +155,7 @@ async fn wrap_edge_route(
.await?;
let inner_assets = fxindexmap! {
INNER.into() => entry
inner => entry
};
let wrapped = asset_context
......
......@@ -5,6 +5,7 @@
use anyhow::{Ok, Result, bail};
use base64::{display::Base64Display, engine::general_purpose::STANDARD};
use indoc::{formatdoc, indoc};
use turbo_rcstr::rcstr;
use turbo_tasks::Vc;
use turbo_tasks_fs::{self, File, FileContent, FileSystemPath};
use turbopack::ModuleAssetContext;
......@@ -83,12 +84,12 @@ pub async fn get_app_metadata_route_entry(
page.0.pop();
if is_multi_dynamic {
page.push(PageSegment::Dynamic("__metadata_id__".into()))?;
page.push(PageSegment::Dynamic(rcstr!("__metadata_id__")))?;
} else {
// if page last segment is sitemap, change to sitemap.xml
if page.last() == Some(&PageSegment::Static("sitemap".into())) {
if page.last() == Some(&PageSegment::Static(rcstr!("sitemap"))) {
page.0.pop();
page.push(PageSegment::Static("sitemap.xml".into()))?
page.push(PageSegment::Static(rcstr!("sitemap.xml")))?
}
};
// Push /route back
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::resolve::{ExternalTraced, ExternalType, options::ImportMapping};
......@@ -12,10 +12,10 @@ pub async fn get_postcss_package_mapping(
) -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![
// Prefer the local installed version over the next.js version
ImportMapping::PrimaryAlternative("postcss".into(), Some(project_path.clone()))
ImportMapping::PrimaryAlternative(rcstr!("postcss"), Some(project_path.clone()))
.resolved_cell(),
ImportMapping::PrimaryAlternative(
"postcss".into(),
rcstr!("postcss"),
Some(get_next_package(project_path.clone()).owned().await?),
)
.resolved_cell(),
......
......@@ -1170,10 +1170,10 @@ impl Issue for InvalidLoaderRuleError {
.into(),
),
StyledString::Text(
"Check out the documentation here for more information:".into(),
rcstr!("Check out the documentation here for more information:"),
),
StyledString::Text(
"https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders".into(),
rcstr!("https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders"),
),
]).resolved_cell())))
}
......
use anyhow::Result;
use indoc::formatdoc;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc, fxindexmap};
use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{
......@@ -51,7 +51,7 @@ pub fn wrap_edge_entry(
);
let inner_assets = fxindexmap! {
"MODULE".into() => entry
rcstr!("MODULE") => entry
};
Ok(asset_context
......
use std::{cmp::Ordering, collections::BTreeSet};
use anyhow::{Context, Result, bail};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::FxIndexSet;
use super::options::{FontData, FontWeights};
......@@ -47,8 +47,8 @@ pub(super) fn get_font_axes(
.axes;
let ital = {
let has_italic = styles.contains(&"italic".into());
let has_normal = styles.contains(&"normal".into());
let has_italic = styles.contains(&rcstr!("italic"));
let has_normal = styles.contains(&rcstr!("normal"));
let mut set = FxIndexSet::default();
if has_normal {
set.insert(FontStyle::Normal);
......@@ -291,6 +291,7 @@ mod tests {
use std::collections::BTreeSet;
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::fxindexset;
use turbo_tasks_fs::json::parse_json_with_source_context;
......@@ -381,12 +382,12 @@ mod tests {
"Inter",
&FontWeights::Variable,
&[],
&Some(vec!["slnt".into()]),
&Some(vec![rcstr!("slnt")]),
)?,
FontAxes {
wght: FontAxesWeights::Variable(Some("100..900".into())),
wght: FontAxesWeights::Variable(Some(rcstr!("100..900"))),
ital: fxindexset! {},
variable_axes: Some(vec![("slnt".into(), "-10..0".into())])
variable_axes: Some(vec![(rcstr!("slnt"), rcstr!("-10..0"))])
}
);
Ok(())
......@@ -422,10 +423,10 @@ mod tests {
"Inter",
&FontWeights::Variable,
&[],
&Some(vec!["slnt".into()]),
&Some(vec![rcstr!("slnt")]),
)?,
FontAxes {
variable_axes: Some(vec![("slnt".into(), "-10..0".into())]),
variable_axes: Some(vec![(rcstr!("slnt"), rcstr!("-10..0"))]),
wght: FontAxesWeights::Variable(None),
..Default::default()
}
......@@ -493,9 +494,9 @@ mod tests {
wght: FontAxesWeights::Fixed(BTreeSet::from([500])),
ital: fxindexset! {FontStyle::Normal},
variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()),
("opsz".into(), "8..144".into()),
("wdth".into(), "50..150".into()),
(rcstr!("GRAD"), rcstr!("-50..100")),
(rcstr!("opsz"), rcstr!("8..144")),
(rcstr!("wdth"), rcstr!("50..150")),
])
},
"optional"
......@@ -535,9 +536,9 @@ mod tests {
wght: FontAxesWeights::Fixed(BTreeSet::from([500, 300])),
ital: fxindexset! {FontStyle::Normal, FontStyle::Italic},
variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()),
("opsz".into(), "8..144".into()),
("wdth".into(), "50..150".into()),
(rcstr!("GRAD"), rcstr!("-50..100")),
(rcstr!("opsz"), rcstr!("8..144")),
(rcstr!("wdth"), rcstr!("50..150")),
])
},
"optional"
......@@ -557,8 +558,8 @@ mod tests {
"Nabla",
&FontAxes {
variable_axes: Some(vec![
("EDPT".into(), "0..200".into()),
("EHLT".into(), "0..24".into()),
(rcstr!("EDPT"), rcstr!("0..200")),
(rcstr!("EHLT"), rcstr!("0..24")),
]),
..Default::default()
},
......
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs};
/// The top-most structure encoded into the query param in requests to
......@@ -112,7 +112,7 @@ fn default_preload() -> bool {
}
fn default_display() -> RcStr {
"swap".into()
rcstr!("swap")
}
#[cfg(test)]
......
......@@ -38,7 +38,7 @@ impl Source for StructuredImageFileSource {
self.image
.ident()
.with_modifier(rcstr!("structured image object"))
.rename_as("*.mjs".into())
.rename_as(rcstr!("*.mjs"))
}
}
......
This diff is collapsed.
......@@ -5,7 +5,7 @@ use itertools::Itertools;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexSet, ResolvedVc, TaskInput, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc,
trace::TraceRawVcs,
......@@ -71,17 +71,13 @@ impl ClientReferenceManifest {
async move {
let mut entry_manifest: ClientReferenceManifest = Default::default();
let mut references = FxIndexSet::default();
let chunk_suffix_path = next_config.chunk_suffix_path().await?;
let chunk_suffix_path = next_config.chunk_suffix_path().owned().await?;
let prefix_path = next_config
.computed_asset_prefix()
.owned()
.await?
.as_ref()
.map(|p| p.clone())
.unwrap_or_default();
let suffix_path = chunk_suffix_path
.as_ref()
.map(|p| p.to_string())
.unwrap_or("".into());
let suffix_path = chunk_suffix_path.unwrap_or_default();
// TODO: Add `suffix` to the manifest for React to use.
// entry_manifest.module_loading.prefix = prefix_path;
......@@ -267,7 +263,7 @@ impl ClientReferenceManifest {
entry_manifest.client_modules.module_exports.insert(
get_client_reference_module_key(&server_path, "*"),
ManifestNodeEntry {
name: "*".into(),
name: rcstr!("*"),
id: (&*client_chunk_item_id).into(),
chunks: client_chunks_paths,
// This should of course be client_is_async, but SSR can become
......@@ -280,9 +276,9 @@ impl ClientReferenceManifest {
let mut ssr_manifest_node = ManifestNode::default();
ssr_manifest_node.module_exports.insert(
"*".into(),
rcstr!("*"),
ManifestNodeEntry {
name: "*".into(),
name: rcstr!("*"),
id: (&*ssr_chunk_item_id).into(),
chunks: ssr_chunks_paths,
// See above
......@@ -292,9 +288,9 @@ impl ClientReferenceManifest {
let mut rsc_manifest_node = ManifestNode::default();
rsc_manifest_node.module_exports.insert(
"*".into(),
rcstr!("*"),
ManifestNodeEntry {
name: "*".into(),
name: rcstr!("*"),
id: (&*rsc_chunk_item_id).into(),
chunks: vec![],
r#async: rsc_is_async,
......
......@@ -519,6 +519,8 @@ pub struct ClientBuildManifest<'a> {
#[cfg(test)]
mod tests {
use turbo_rcstr::rcstr;
use super::*;
#[test]
......@@ -529,20 +531,20 @@ mod tests {
locale: false,
has: None,
missing: None,
original_source: "".into(),
original_source: rcstr!(""),
},
MiddlewareMatcher {
regexp: Some(".*".into()),
regexp: Some(rcstr!(".*")),
locale: true,
has: Some(vec![RouteHas::Query {
key: "foo".into(),
key: rcstr!("foo"),
value: None,
}]),
missing: Some(vec![RouteHas::Query {
key: "bar".into(),
value: Some("value".into()),
key: rcstr!("bar"),
value: Some(rcstr!("value")),
}]),
original_source: "source".into(),
original_source: rcstr!("source"),
},
];
......
......@@ -238,7 +238,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
// have an extension in the request we try to append ".js"
// automatically
request_str.push_str(".js");
request = request.append_path(".js".into()).resolve().await?;
request = request.append_path(rcstr!(".js")).resolve().await?;
continue;
}
// this can't resolve with node.js from the original location, so bundle it
......@@ -271,7 +271,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
.into(),
),
StyledString::Code(format!("npm install {package}").into()),
StyledString::Text(" from the project directory.".into()),
StyledString::Text(rcstr!(" from the project directory.")),
]);
};
......@@ -293,9 +293,9 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
let FindContextFileResult::Found(package_json_from_original_location, _) =
&*package_json_from_original_location.await?
else {
return unable_to_externalize(vec![StyledString::Text(
"The package.json of the package can't be found.".into(),
)]);
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package can't be found."
))]);
};
let FileJsonContent::Content(package_json_file) =
&*package_json_file.read_json().await?
......@@ -309,17 +309,17 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
let FileJsonContent::Content(package_json_from_original_location) =
&*package_json_from_original_location.read_json().await?
else {
return unable_to_externalize(vec![StyledString::Text(
"The package.json of the package can't be parsed.".into(),
)]);
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package can't be parsed."
))]);
};
let (Some(name), Some(version)) = (
package_json_file.get("name").and_then(|v| v.as_str()),
package_json_file.get("version").and_then(|v| v.as_str()),
) else {
return unable_to_externalize(vec![StyledString::Text(
"The package.json of the package has no name or version.".into(),
)]);
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package has no name or version."
))]);
};
let (Some(name2), Some(version2)) = (
package_json_from_original_location
......@@ -354,15 +354,15 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
let external_type = match (file_type, is_esm) {
(FileType::UnsupportedExtension, _) => {
// unsupported file type, bundle it
return unable_to_externalize(vec![StyledString::Text(
"Only .mjs, .cjs, .js, .json, or .node can be handled by Node.js.".into(),
)]);
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"Only .mjs, .cjs, .js, .json, or .node can be handled by Node.js."
))]);
}
(FileType::InvalidPackageJson, _) => {
// invalid package.json, bundle it
return unable_to_externalize(vec![StyledString::Text(
"The package.json can't be found or parsed.".into(),
)]);
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json can't be found or parsed."
))]);
}
// commonjs without esm is always external
(FileType::CommonJs, false) => ExternalType::CommonJs,
......
......@@ -101,8 +101,8 @@ impl EcmascriptChunkPlaceable for NextServerComponentModule {
let mut exports = BTreeMap::new();
exports.insert(
"default".into(),
EsmExport::ImportedBinding(module_reference, "default".into(), false),
rcstr!("default"),
EsmExport::ImportedBinding(module_reference, rcstr!("default"), false),
);
Ok(EcmascriptExports::EsmExports(
......
......@@ -101,8 +101,8 @@ impl EcmascriptChunkPlaceable for NextServerUtilityModule {
let mut exports = BTreeMap::new();
exports.insert(
"default".into(),
EsmExport::ImportedBinding(module_reference, "default".into(), false),
rcstr!("default"),
EsmExport::ImportedBinding(module_reference, rcstr!("default"), false),
);
Ok(EcmascriptExports::EsmExports(
......
use anyhow::Result;
use once_cell::sync::Lazy;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbopack_core::{
chunk::{ChunkableModuleReference, ChunkingType, ChunkingTypeOption},
......@@ -44,7 +44,7 @@ impl ModuleReference for NextServerUtilityModuleReference {
}
}
pub static NEXT_SERVER_UTILITY_MERGE_TAG: Lazy<RcStr> = Lazy::new(|| "next-server-utility".into());
pub static NEXT_SERVER_UTILITY_MERGE_TAG: Lazy<RcStr> = Lazy::new(|| rcstr!("next-server-utility"));
#[turbo_tasks::value_impl]
impl ChunkableModuleReference for NextServerUtilityModuleReference {
......
......@@ -158,7 +158,7 @@ pub(crate) fn get_invalid_client_only_resolve_plugin(
) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new(
root,
"client-only".into(),
rcstr!("client-only"),
vec![
"'client-only' cannot be imported from a Server Component module. It should only be \
used from a Client Component."
......@@ -175,7 +175,7 @@ pub(crate) fn get_invalid_server_only_resolve_plugin(
) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new(
root,
"server-only".into(),
rcstr!("server-only"),
vec![
"'server-only' cannot be imported from a Client Component module. It should only be \
used from a Server Component."
......@@ -190,7 +190,7 @@ pub(crate) fn get_invalid_styled_jsx_resolve_plugin(
) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new(
root,
"styled-jsx".into(),
rcstr!("styled-jsx"),
vec![
"'client-only' cannot be imported from a Server Component module. It should only be \
used from a Client Component."
......@@ -222,7 +222,9 @@ impl AfterResolvePlugin for NextExternalResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new(
self.project_path.root().owned().await?,
Glob::new("**/next/dist/**/*.{external,runtime.dev,runtime.prod}.js".into()),
Glob::new(rcstr!(
"**/next/dist/**/*.{external,runtime.dev,runtime.prod}.js"
)),
))
}
......@@ -276,7 +278,7 @@ impl AfterResolvePlugin for NextNodeSharedRuntimeResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new(
self.root.root().owned().await?,
Glob::new("**/next/dist/**/*.shared-runtime.js".into()),
Glob::new(rcstr!("**/next/dist/**/*.shared-runtime.js")),
))
}
......@@ -401,7 +403,7 @@ impl AfterResolvePlugin for NextSharedRuntimeResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new(
self.root.root().owned().await?,
Glob::new("**/next/dist/esm/**/*.shared-runtime.js".into()),
Glob::new(rcstr!("**/next/dist/esm/**/*.shared-runtime.js")),
))
}
......
use anyhow::Result;
use async_trait::async_trait;
use next_custom_transforms::transforms::fonts::*;
use swc_core::ecma::{ast::Program, atoms::Atom, visit::VisitMutWith};
use swc_core::{
atoms::atom,
ecma::{ast::Program, atoms::Atom, visit::VisitMutWith},
};
use turbo_tasks::ResolvedVc;
use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext};
......@@ -11,10 +14,10 @@ use super::module_rule_match_js_no_url;
/// Returns a rule which applies the Next.js font transform.
pub fn get_next_font_transform_rule(enable_mdx_rs: bool) -> ModuleRule {
let font_loaders = vec![
"next/font/google".into(),
"@next/font/google".into(),
"next/font/local".into(),
"@next/font/local".into(),
atom!("next/font/google"),
atom!("@next/font/google"),
atom!("next/font/local"),
atom!("@next/font/local"),
];
let transformer =
......
......@@ -116,7 +116,7 @@ pub async fn is_babel_loader_available(project_path: FileSystemPath) -> Result<V
let result = resolve(
project_path.clone(),
ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined),
Request::parse(Pattern::Constant("babel-loader/package.json".into())),
Request::parse(Pattern::Constant(rcstr!("babel-loader/package.json"))),
node_cjs_resolve_options(project_path),
);
let assets = result.primary_sources().await?;
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::WebpackLoadersOptions;
......@@ -46,7 +46,7 @@ pub async fn webpack_loader_options(
fn loader_runner_package_mapping() -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![
ImportMapping::External(
Some("next/dist/compiled/loader-runner".into()),
Some(rcstr!("next/dist/compiled/loader-runner")),
ExternalType::CommonJs,
ExternalTraced::Untraced,
)
......
......@@ -2,6 +2,7 @@ use std::mem::take;
use anyhow::{Result, bail};
use serde_json::Value as JsonValue;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbopack::module_options::{LoaderRuleItem, OptionWebpackRules, WebpackRules};
use turbopack_node::transforms::webpack::WebpackLoaderItem;
......@@ -41,7 +42,7 @@ pub async fn maybe_add_sass_loader(
.or(sass_options.get("additionalData"));
let rule = rules.get_mut(pattern);
let sass_loader = WebpackLoaderItem {
loader: "next/dist/compiled/sass-loader".into(),
loader: rcstr!("next/dist/compiled/sass-loader"),
options: take(
serde_json::json!({
"implementation": sass_options.get("implementation"),
......@@ -54,7 +55,7 @@ pub async fn maybe_add_sass_loader(
),
};
let resolve_url_loader = WebpackLoaderItem {
loader: "next/dist/build/webpack/loaders/resolve-url-loader/index".into(),
loader: rcstr!("next/dist/build/webpack/loaders/resolve-url-loader/index"),
options: take(
serde_json::json!({
//https://github.com/vercel/turbo/blob/d527eb54be384a4658243304cecd547d09c05c6b/crates/turbopack-node/src/transforms/webpack.rs#L191
......
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{self, FileJsonContent, FileSystemPath};
use turbopack::{
......@@ -161,11 +162,11 @@ pub async fn get_jsx_transform_options(
// https://github.com/vercel/next.js/blob/3dc2c1c7f8441cdee31da9f7e0986d654c7fd2e7/packages/next/src/build/swc/options.ts#L112
// This'll be ignored if ts|jsconfig explicitly specifies importSource
import_source: if is_emotion_enabled && !is_rsc_context {
Some("@emotion/react".into())
Some(rcstr!("@emotion/react"))
} else {
None
},
runtime: Some("automatic".into()),
runtime: Some(rcstr!("automatic")),
react_refresh: enable_react_refresh,
};
......
......@@ -105,7 +105,7 @@ pub async fn pathname_for_path(
};
let path = match (path_ty, path) {
// "/" is special-cased to "/index" for data routes.
(PathType::Data, "") => "/index".into(),
(PathType::Data, "") => rcstr!("/index"),
// `get_path_to` always strips the leading `/` from the path, so we need to add
// it back here.
(_, path) => format!("/{path}").into(),
......@@ -141,7 +141,7 @@ pub async fn get_transpiled_packages(
let default_transpiled_packages: Vec<RcStr> = load_next_js_templateon(
project_path,
"dist/lib/default-transpiled-packages.json".into(),
rcstr!("dist/lib/default-transpiled-packages.json"),
)
.await?;
......@@ -280,8 +280,10 @@ impl Issue for NextSourceConfigParsingIssue {
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text("Next.js can't recognize the exported `config` field in route".into())
.cell()
StyledString::Text(rcstr!(
"Next.js can't recognize the exported `config` field in route"
))
.cell()
}
#[turbo_tasks::function]
......@@ -553,7 +555,7 @@ pub async fn parse_config_from_source(
if let Expr::Lit(Lit::Str(str_value)) = &**init {
let mut config = NextSourceConfig::default();
let runtime = str_value.value.to_string();
let runtime = &str_value.value;
match runtime.as_str() {
"edge" | "experimental-edge" => {
config.runtime = NextRuntime::Edge;
......
use rustc_hash::{FxHashMap, FxHashSet};
use serde::Deserialize;
use swc_core::{
atoms::atom,
common::{util::take::Take, SyntaxContext, DUMMY_SP},
ecma::{
ast::{
......@@ -113,7 +114,7 @@ impl VisitMut for CjsOptimizer {
obj: Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: Ident::new(
"require".into(),
atom!("require"),
DUMMY_SP,
self.unresolved_ctxt,
)
......
......@@ -5,7 +5,7 @@ use std::{
use pathdiff::diff_paths;
use swc_core::{
atoms::Atom,
atoms::{atom, Atom},
common::{errors::HANDLER, FileName, Span, DUMMY_SP},
ecma::{
ast::{
......@@ -264,7 +264,7 @@ impl Fold for NextDynamicPatcher {
let mut props =
vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new(
"loadableGenerated".into(),
atom!("loadableGenerated"),
DUMMY_SP,
)),
value: generated,
......@@ -432,7 +432,7 @@ impl VisitMut for DynamicImportTransitionAdder<'_> {
ObjectLit {
span: DUMMY_SP,
props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new("with".into(), DUMMY_SP)),
key: PropName::Ident(IdentName::new(atom!("with"), DUMMY_SP)),
value: with_transition(self.transition_name).into(),
})))],
}
......@@ -453,7 +453,7 @@ impl VisitMut for DynamicImportTransitionAdder<'_> {
fn module_id_options(module_id: Expr) -> Vec<PropOrSpread> {
vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new("modules".into(), DUMMY_SP)),
key: PropName::Ident(IdentName::new(atom!("modules"), DUMMY_SP)),
value: Box::new(Expr::Array(ArrayLit {
elems: vec![Some(ExprOrSpread {
expr: Box::new(module_id),
......@@ -466,7 +466,7 @@ fn module_id_options(module_id: Expr) -> Vec<PropOrSpread> {
fn webpack_options(module_id: Expr) -> Vec<PropOrSpread> {
vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new("webpack".into(), DUMMY_SP)),
key: PropName::Ident(IdentName::new(atom!("webpack"), DUMMY_SP)),
value: Box::new(Expr::Arrow(ArrowExpr {
params: vec![],
body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Array(ArrayLit {
......@@ -512,7 +512,7 @@ impl NextDynamicPatcher {
local: id_ident,
imported: Some(
Ident::new(
"__turbopack_module_id__".into(),
atom!("__turbopack_module_id__"),
DUMMY_SP,
Default::default(),
)
......@@ -541,7 +541,7 @@ impl NextDynamicPatcher {
fn exec_expr_when_resolve_weak_available(expr: &Expr) -> Expr {
let undefined_str_literal = Expr::Lit(Lit::Str(Str {
span: DUMMY_SP,
value: "undefined".into(),
value: atom!("undefined"),
raw: None,
}));
......
use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{
atoms::Atom,
atoms::{atom, Atom},
ecma::{
ast::{
Expr, Id, ImportDecl, ImportNamedSpecifier, ImportSpecifier, MemberExpr, MemberProp,
......@@ -80,7 +80,7 @@ impl Visit for Analyzer<'_> {
Some(imported) => (local.to_id(), orig_name(imported)),
_ => (local.to_id(), local.sym.clone()),
},
ImportSpecifier::Default(s) => (s.local.to_id(), "default".into()),
ImportSpecifier::Default(s) => (s.local.to_id(), atom!("default")),
ImportSpecifier::Namespace(s) => {
self.data
.namespace_imports
......
......@@ -3,7 +3,7 @@ use std::{cell::RefCell, mem::take, rc::Rc};
use easy_error::{bail, Error};
use rustc_hash::FxHashSet;
use swc_core::{
atoms::Atom,
atoms::{atom, Atom},
common::{
errors::HANDLER,
pass::{Repeat, Repeated},
......@@ -443,7 +443,7 @@ impl Fold for NextSsg {
match &i {
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(e)) if e.specifiers.is_empty() => {
return ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP }))
return ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP }));
}
_ => {}
}
......@@ -469,9 +469,9 @@ impl Fold for NextSsg {
name: Pat::Ident(
IdentName::new(
if self.state.is_prerenderer {
"__N_SSG".into()
atom!("__N_SSG")
} else {
"__N_SSP".into()
atom!("__N_SSP")
},
DUMMY_SP,
)
......
......@@ -4,6 +4,7 @@
use serde::Deserialize;
use swc_core::{
atoms::atom,
common::DUMMY_SP,
ecma::{
ast::*,
......@@ -71,18 +72,18 @@ fn wrap_expr_with_env_prod_condition(call: CallExpr) -> Expr {
left: Box::new(Expr::Member(MemberExpr {
obj: (Box::new(Expr::Member(MemberExpr {
obj: (Box::new(Expr::Ident(Ident {
sym: "process".into(),
sym: atom!("process"),
span: DUMMY_SP,
..Default::default()
}))),
prop: MemberProp::Ident(IdentName {
sym: "env".into(),
sym: atom!("env"),
span: DUMMY_SP,
}),
span: DUMMY_SP,
}))),
prop: (MemberProp::Ident(IdentName {
sym: "__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE".into(),
sym: atom!("__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE"),
span: DUMMY_SP,
})),
span: DUMMY_SP,
......
......@@ -445,7 +445,7 @@ impl<C: Comments> ServerActions<C> {
new_params.push(Param {
span: DUMMY_SP,
decorators: vec![],
pat: Pat::Ident(IdentName::new("$$ACTION_CLOSURE_BOUND".into(), DUMMY_SP).into()),
pat: Pat::Ident(IdentName::new(atom!("$$ACTION_CLOSURE_BOUND"), DUMMY_SP).into()),
});
}
......@@ -597,7 +597,7 @@ impl<C: Comments> ServerActions<C> {
new_params.push(Param {
span: DUMMY_SP,
decorators: vec![],
pat: Pat::Ident(IdentName::new("$$ACTION_CLOSURE_BOUND".into(), DUMMY_SP).into()),
pat: Pat::Ident(IdentName::new(atom!("$$ACTION_CLOSURE_BOUND"), DUMMY_SP).into()),
});
}
......@@ -1620,7 +1620,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// export default function foo() {}
self.exported_idents.push((
ident.clone(),
"default".into(),
atom!("default"),
ref_id,
));
} else {
......@@ -1638,7 +1638,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
self.exported_idents.push((
new_ident.clone(),
"default".into(),
atom!("default"),
ref_id,
));
......@@ -1694,7 +1694,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
self.exported_idents.push((
new_ident.clone(),
"default".into(),
atom!("default"),
self.generate_server_reference_id(
"default",
is_cache,
......@@ -1723,7 +1723,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// export default foo
self.exported_idents.push((
ident.clone(),
"default".into(),
atom!("default"),
self.generate_server_reference_id(
"default",
in_cache_file,
......@@ -1741,7 +1741,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
self.exported_idents.push((
new_ident.clone(),
"default".into(),
atom!("default"),
self.generate_server_reference_id(
"default",
in_cache_file,
......@@ -1858,7 +1858,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
],
src: Box::new(Str {
span: DUMMY_SP,
value: "private-next-rsc-action-client-wrapper".into(),
value: atom!("private-next-rsc-action-client-wrapper"),
raw: None,
}),
type_only: false,
......@@ -1990,7 +1990,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
})],
src: Box::new(Str {
span: DUMMY_SP,
value: "private-next-rsc-action-validate".into(),
value: atom!("private-next-rsc-action-validate"),
raw: None,
}),
type_only: false,
......@@ -2040,7 +2040,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
})],
src: Box::new(Str {
span: DUMMY_SP,
value: "private-next-rsc-cache-wrapper".into(),
value: atom!("private-next-rsc-cache-wrapper"),
raw: None,
}),
type_only: false,
......@@ -2065,7 +2065,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
})],
src: Box::new(Str {
span: DUMMY_SP,
value: "private-next-rsc-server-reference".into(),
value: atom!("private-next-rsc-server-reference"),
raw: None,
}),
type_only: false,
......@@ -2094,7 +2094,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
],
src: Box::new(Str {
span: DUMMY_SP,
value: "private-next-rsc-action-encryption".into(),
value: atom!("private-next-rsc-action-encryption"),
raw: None,
}),
type_only: false,
......@@ -2142,7 +2142,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
ServerActionsMode::Turbopack => {
new.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: Box::new(Expr::Lit(Lit::Str(
"use turbopack no side effects".into(),
atom!("use turbopack no side effects").into(),
))),
span: DUMMY_SP,
})));
......@@ -2165,7 +2165,8 @@ impl<C: Comments> VisitMut for ServerActions<C> {
vec![
ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: Box::new(Expr::Lit(Lit::Str(
"use turbopack no side effects".into(),
atom!("use turbopack no side effects")
.into(),
))),
span: DUMMY_SP,
})),
......
......@@ -11,6 +11,7 @@ use next_custom_transforms::transforms::{
};
use rustc_hash::FxHashSet;
use swc_core::{
atoms::atom,
common::{FileName, Mark},
ecma::{
parser::{EsSyntax, Syntax},
......@@ -21,6 +22,7 @@ use swc_core::{
},
};
use testing::fixture;
use turbo_rcstr::rcstr;
fn syntax() -> Syntax {
Syntax::Es(EsSyntax {
......@@ -125,8 +127,8 @@ fn next_font_loaders_errors(input: PathBuf) {
syntax(),
&|_tr| {
next_font_loaders(FontLoaderConfig {
relative_file_path_from_root: "pages/test.tsx".into(),
font_loaders: vec!["@next/font/google".into(), "cool-fonts".into()],
relative_file_path_from_root: atom!("pages/test.tsx"),
font_loaders: vec![atom!("@next/font/google"), atom!("cool-fonts")],
})
},
&input,
......@@ -231,7 +233,7 @@ fn use_cache_not_allowed(input: PathBuf) {
is_development: true,
use_cache_enabled: false,
hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]),
cache_kinds: FxHashSet::from_iter([rcstr!("x")]),
},
tr.comments.as_ref().clone(),
tr.cm.clone(),
......
......@@ -184,11 +184,11 @@ impl VisitMut for TransformVisitor {
callee: Callee::Expr(Box::new(Expr::Member(MemberExpr {
span: new_error_expr.span,
obj: Box::new(Expr::Ident(Ident::new(
"Object".into(),
rcstr!("Object"),
new_error_expr.span,
Default::default(),
))),
prop: MemberProp::Ident("defineProperty".into()),
prop: MemberProp::Ident(rcstr!("defineProperty")),
}))), // Object.defineProperty(
args: vec![
ExprOrSpread {
......@@ -199,7 +199,7 @@ impl VisitMut for TransformVisitor {
spread: None,
expr: Box::new(Expr::Lit(Lit::Str(Str {
span: new_error_expr.span,
value: "__NEXT_ERROR_CODE".into(),
value: rcstr!("__NEXT_ERROR_CODE"),
raw: None,
}))), // "__NEXT_ERROR_CODE"
},
......@@ -209,7 +209,7 @@ impl VisitMut for TransformVisitor {
span: new_error_expr.span,
props: vec![
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident("value".into()),
key: PropName::Ident(rcstr!("value")),
value: Box::new(Expr::Lit(Lit::Str(Str {
span: new_error_expr.span,
value: code.into(),
......@@ -217,14 +217,14 @@ impl VisitMut for TransformVisitor {
}))),
}))),
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident("enumerable".into()),
key: PropName::Ident(rcstr!("enumerable")),
value: Box::new(Expr::Lit(Lit::Bool(Bool {
span: new_error_expr.span,
value: false,
}))),
}))),
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident("configurable".into()),
key: PropName::Ident(rcstr!("configurable")),
value: Box::new(Expr::Lit(Lit::Bool(Bool {
span: new_error_expr.span,
value: true,
......
......@@ -10,7 +10,7 @@ use std::{
use anyhow::Result;
use sha2::{Digest, Sha256};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadConsistency, TurboTasks, UpdateInfo, Vc, util::FormatDuration};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{
......@@ -35,7 +35,7 @@ async fn main() -> Result<()> {
let task = tt.spawn_root_task(|| {
Box::pin(async {
let root = current_dir().unwrap().to_str().unwrap().into();
let disk_fs = DiskFileSystem::new("project".into(), root);
let disk_fs = DiskFileSystem::new(rcstr!("project"), root);
disk_fs.await?.start_watching(None).await?;
// Smart Pointer cast
......
......@@ -10,7 +10,7 @@ use std::{
use anyhow::Result;
use sha2::{Digest, Sha256};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadConsistency, TurboTasks, UpdateInfo, Vc, util::FormatDuration};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{
......@@ -32,13 +32,13 @@ async fn main() -> Result<()> {
let task = tt.spawn_root_task(|| {
Box::pin(async {
let root = current_dir().unwrap().to_str().unwrap().into();
let disk_fs = DiskFileSystem::new("project".into(), root);
let disk_fs = DiskFileSystem::new(rcstr!("project"), root);
disk_fs.await?.start_watching(None).await?;
// Smart Pointer cast
let fs: Vc<Box<dyn FileSystem>> = Vc::upcast(disk_fs);
let input = fs.root().await?.join("crates")?;
let glob = Glob::new("**/*.rs".into());
let glob = Glob::new(rcstr!("**/*.rs"));
let glob_result = input.read_glob(glob);
let dir_hash = hash_glob_result(glob_result);
print_hash(dir_hash).await?;
......
use anyhow::Result;
use regex::bytes::{Regex, RegexBuilder};
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc;
use crate::globset::parse;
......@@ -100,7 +100,7 @@ impl Glob {
#[turbo_tasks::function]
pub async fn alternatives(globs: Vec<Vc<Glob>>) -> Result<Vc<Self>> {
match globs.len() {
0 => Ok(Glob::new("".into())),
0 => Ok(Glob::new(rcstr!(""))),
1 => Ok(globs.into_iter().next().unwrap()),
_ => {
let mut new_glob = String::new();
......
......@@ -193,7 +193,7 @@ pub mod tests {
io::prelude::*,
};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, ReadRef, Vc, apply_effects};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
......@@ -224,11 +224,11 @@ pub mod tests {
));
let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path));
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let read_dir = fs
.root()
.await?
.read_glob(Glob::new("**".into()))
.read_glob(Glob::new(rcstr!("**")))
.await
.unwrap();
assert_eq!(read_dir.results.len(), 2);
......@@ -253,7 +253,7 @@ pub mod tests {
let read_dir = fs
.root()
.await?
.read_glob(Glob::new("**/bar".into()))
.read_glob(Glob::new(rcstr!("**/bar")))
.await
.unwrap();
assert_eq!(read_dir.results.len(), 0);
......@@ -294,11 +294,11 @@ pub mod tests {
));
let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path));
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let read_dir = fs
.root()
.await?
.read_glob(Glob::new("*.js".into()))
.read_glob(Glob::new(rcstr!("*.js")))
.await
.unwrap();
assert_eq!(read_dir.results.len(), 1);
......@@ -331,7 +331,7 @@ pub mod tests {
#[turbo_tasks::function(operation)]
pub fn track_star_star_glob(path: FileSystemPath) -> Vc<Completion> {
path.track_glob(Glob::new("**".into()), false)
path.track_glob(Glob::new(rcstr!("**")), false)
}
#[cfg(unix)]
......@@ -375,7 +375,7 @@ pub mod tests {
));
let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path));
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let dir = fs.root().await?.join("dir")?;
let read_dir = track_star_star_glob(dir.clone())
.read_strongly_consistent()
......@@ -405,7 +405,7 @@ pub mod tests {
// Modify a symlink target file
let write_result = write(
fs.root().await?.join("link_target.js")?,
"new_contents".into(),
rcstr!("new_contents"),
);
write_result.read_strongly_consistent().await?;
apply_effects(write_result).await?;
......@@ -445,11 +445,13 @@ pub mod tests {
));
let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path));
use turbo_rcstr::rcstr;
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let err = fs
.root()
.await?
.track_glob(Glob::new("**".into()), false)
.track_glob(Glob::new(rcstr!("**")), false)
.await
.expect_err("Should have detected an infinite loop");
......@@ -462,7 +464,7 @@ pub mod tests {
let err = fs
.root()
.await?
.track_glob(Glob::new("**".into()), false)
.track_glob(Glob::new(rcstr!("**")), false)
.await
.expect_err("Should have detected an infinite loop");
......@@ -501,11 +503,11 @@ pub mod tests {
));
let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path));
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let err = fs
.root()
.await?
.read_glob(Glob::new("**".into()))
.read_glob(Glob::new(rcstr!("**")))
.await
.expect_err("Should have detected an infinite loop");
......@@ -518,7 +520,7 @@ pub mod tests {
let err = fs
.root()
.await?
.track_glob(Glob::new("**".into()), false)
.track_glob(Glob::new(rcstr!("**")), false)
.await
.expect_err("Should have detected an infinite loop");
......
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ValueDefault, ValueToString, Vc};
use super::{FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent};
......@@ -21,7 +21,7 @@ impl VirtualFileSystem {
/// [`Vc<VirtualFileSystem>`].
pub fn new() -> Vc<Self> {
Self::cell(VirtualFileSystem {
name: "virtual file system".into(),
name: rcstr!("virtual file system"),
})
}
......
......@@ -44,23 +44,23 @@ impl fmt::Display for NodeEnv {
}
}
async fn foreign_code_context_condition() -> Result<ContextCondition> {
Ok(ContextCondition::InDirectory("node_modules".to_string()))
fn foreign_code_context_condition() -> ContextCondition {
ContextCondition::InDirectory("node_modules".to_string())
}
#[turbo_tasks::function]
pub async fn get_client_import_map(project_path: FileSystemPath) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty();
import_map.insert_singleton_alias("@swc/helpers", project_path.clone());
import_map.insert_singleton_alias("styled-jsx", project_path.clone());
import_map.insert_singleton_alias("react", project_path.clone());
import_map.insert_singleton_alias("react-dom", project_path.clone());
import_map.insert_singleton_alias(rcstr!("@swc/helpers"), project_path.clone());
import_map.insert_singleton_alias(rcstr!("styled-jsx"), project_path.clone());
import_map.insert_singleton_alias(rcstr!("react"), project_path.clone());
import_map.insert_singleton_alias(rcstr!("react-dom"), project_path.clone());
import_map.insert_wildcard_alias(
"@vercel/turbopack-ecmascript-runtime/",
rcstr!("@vercel/turbopack-ecmascript-runtime/"),
ImportMapping::PrimaryAlternative(
"./*".into(),
rcstr!("./*"),
Some(
turbopack_ecmascript_runtime::embed_fs()
.root()
......@@ -84,7 +84,7 @@ pub async fn get_client_resolve_options_context(
.await?;
let module_options_context = ResolveOptionsContext {
enable_node_modules: Some(project_path.root().owned().await?),
custom_conditions: vec![node_env.await?.to_string().into(), "browser".into()],
custom_conditions: vec![node_env.await?.to_string().into(), rcstr!("browser")],
import_map: Some(next_client_import_map),
browser: true,
module: true,
......@@ -94,7 +94,7 @@ pub async fn get_client_resolve_options_context(
enable_typescript: true,
enable_react: true,
rules: vec![(
foreign_code_context_condition().await?,
foreign_code_context_condition(),
module_options_context.clone().resolved_cell(),
)],
..module_options_context
......@@ -161,7 +161,7 @@ async fn get_client_module_options_context(
},
enable_postcss_transform: Some(PostCssTransformOptions::default().resolved_cell()),
rules: vec![(
foreign_code_context_condition().await?,
foreign_code_context_condition(),
module_options_context.clone().resolved_cell(),
)],
module_rules: vec![module_rules],
......
......@@ -3,7 +3,7 @@ use std::{env::current_dir, path::PathBuf};
use anyhow::{Context, Result};
use dunce::canonicalize;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, TaskInput, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::{DiskFileSystem, FileSystem};
......@@ -56,12 +56,12 @@ pub fn normalize_entries(entries: &Option<Vec<String>>) -> Vec<RcStr> {
entries
.as_ref()
.map(|v| v.iter().map(|v| RcStr::from(&**v)).collect())
.unwrap_or_else(|| vec!["src/entry".into()])
.unwrap_or_else(|| vec![rcstr!("src/entry")])
}
#[turbo_tasks::function]
pub async fn project_fs(project_dir: RcStr, watch: bool) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new("project".into(), project_dir);
let disk_fs = DiskFileSystem::new(rcstr!("project"), project_dir);
if watch {
disk_fs.await?.start_watching(None).await?;
}
......@@ -70,6 +70,6 @@ pub async fn project_fs(project_dir: RcStr, watch: bool) -> Result<Vc<Box<dyn Fi
#[turbo_tasks::function]
pub fn output_fs(project_dir: RcStr) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new("output".into(), project_dir);
let disk_fs = DiskFileSystem::new(rcstr!("output"), project_dir);
Ok(Vc::upcast(disk_fs))
}
......@@ -3,6 +3,7 @@ use std::{collections::HashSet, sync::atomic::AtomicBool};
use anyhow::{Context, Result};
use rustc_hash::FxHashMap;
use smallvec::{SmallVec, smallvec};
use turbo_rcstr::rcstr;
use turbo_tasks::{FxIndexSet, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc};
use super::{
......@@ -150,7 +151,7 @@ pub async fn make_chunk_group(
chunking_context,
chunk_items,
chunk_item_batch_groups,
"".into(),
rcstr!(""),
ResolvedVc::cell(referenced_output_assets),
)
.await?;
......
use anyhow::Result;
use rustc_hash::FxHashSet;
use tracing::Instrument;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use crate::{
......@@ -49,7 +50,7 @@ pub async fn make_style_production_chunks(
vec![&ChunkItemOrBatchWithInfo::ChunkItem {
chunk_item: chunk_item.clone(),
size: 0,
asset_ident: "".into(),
asset_ident: rcstr!(""),
}],
vec![],
&mut String::new(),
......
......@@ -236,6 +236,11 @@ impl From<String> for FreeVarReference {
Self::Value(value.into())
}
}
impl From<RcStr> for FreeVarReference {
fn from(value: RcStr) -> Self {
Self::Value(value.into())
}
}
impl From<&str> for FreeVarReference {
fn from(value: &str) -> Self {
......@@ -366,6 +371,7 @@ impl CompileTimeInfoBuilder {
#[cfg(test)]
mod test {
use turbo_rcstr::rcstr;
use turbo_tasks::FxIndexMap;
use crate::compile_time_info::{DefinableNameSegment, FreeVarReference, FreeVarReferences};
......@@ -377,20 +383,26 @@ mod test {
FOO = "bar",
FOO = false,
Buffer = FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(),
request: rcstr!("node:buffer"),
lookup_path: None,
export: Some("Buffer".into()),
export: Some(rcstr!("Buffer")),
},
),
FreeVarReferences(FxIndexMap::from_iter(vec![
(vec!["FOO".into()], FreeVarReference::Value("bar".into())),
(vec!["FOO".into()], FreeVarReference::Value(false.into())),
(
vec!["Buffer".into()],
vec![rcstr!("FOO").into()],
FreeVarReference::Value(rcstr!("bar").into())
),
(
vec![rcstr!("FOO").into()],
FreeVarReference::Value(false.into())
),
(
vec![rcstr!("Buffer").into()],
FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(),
request: rcstr!("node:buffer"),
lookup_path: None,
export: Some("Buffer".into()),
export: Some(rcstr!("Buffer")),
}
),
]))
......@@ -407,21 +419,34 @@ mod test {
),
FreeVarReferences(FxIndexMap::from_iter(vec![
(
vec!["x".into(), DefinableNameSegment::TypeOf],
FreeVarReference::Value("a".into())
vec![rcstr!("x").into(), DefinableNameSegment::TypeOf],
FreeVarReference::Value(rcstr!("a").into())
),
(
vec!["x".into(), "y".into(), DefinableNameSegment::TypeOf],
FreeVarReference::Value("b".into())
vec![
rcstr!("x").into(),
rcstr!("y").into(),
DefinableNameSegment::TypeOf
],
FreeVarReference::Value(rcstr!("b").into())
),
(
vec![
rcstr!("x").into(),
rcstr!("y").into(),
rcstr!("z").into(),
DefinableNameSegment::TypeOf
],
FreeVarReference::Value(rcstr!("b").into())
),
(
vec![
"x".into(),
"y".into(),
"z".into(),
rcstr!("x").into(),
rcstr!("y").into(),
rcstr!("z").into(),
DefinableNameSegment::TypeOf
],
FreeVarReference::Value("c".into())
FreeVarReference::Value(rcstr!("c").into())
)
]))
);
......
......@@ -112,7 +112,7 @@ impl Environment {
// browserslist correctly because CSS Modules in client components is double-processed,
// once for server once for browser.
{
Vc::cell("".into())
Vc::cell(rcstr!(""))
}
ExecutionEnvironment::Browser(browser_env) => {
Vc::cell(browser_env.await?.browserslist_query.clone())
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
......@@ -47,15 +47,15 @@ impl Issue for AnalyzeIssue {
#[turbo_tasks::function]
async fn title(&self) -> Result<Vc<StyledString>> {
let title = &**self.title.await?;
let title = &*self.title.await?;
Ok(if let Some(code) = self.code.as_ref() {
StyledString::Line(vec![
StyledString::Strong(code.clone()),
StyledString::Text(" ".into()),
StyledString::Text(title.into()),
StyledString::Text(rcstr!(" ")),
StyledString::Text(title.clone()),
])
} else {
StyledString::Text(title.into())
StyledString::Text(title.clone())
}
.cell())
}
......
......@@ -785,7 +785,7 @@ pub enum IssueStage {
CodeGen,
Unsupported,
Misc,
Other(String),
Other(RcStr),
}
impl Display for IssueStage {
......
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
......@@ -50,7 +51,7 @@ impl Issue for ModuleIssue {
pub async fn emit_unknown_module_type_error(source: Vc<Box<dyn Source>>) -> Result<()> {
ModuleIssue {
ident: source.ident().to_resolved().await?,
title: StyledString::Text("Unknown module type".into()).resolved_cell(),
title: StyledString::Text(rcstr!("Unknown module type")).resolved_cell(),
description: StyledString::Text(
r"This module doesn't have an associated type. Use a known file extension, or register a loader for it.
......
use std::fmt::Write;
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadRef, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
......@@ -36,8 +36,8 @@ impl Issue for ResolvingIssue {
async fn title(&self) -> Result<Vc<StyledString>> {
let request = self.request.request_pattern().to_string().owned().await?;
Ok(StyledString::Line(vec![
StyledString::Strong("Module not found".into()),
StyledString::Text(": Can't resolve ".into()),
StyledString::Strong(rcstr!("Module not found")),
StyledString::Text(rcstr!(": Can't resolve ")),
StyledString::Code(request),
])
.cell())
......
......@@ -702,6 +702,8 @@ pub trait AliasTemplate {
mod test {
use std::assert_matches::assert_matches;
use turbo_rcstr::rcstr;
use super::{AliasMap, AliasPattern, AliasTemplate};
use crate::resolve::pattern::Pattern;
......@@ -916,37 +918,37 @@ mod test {
assert_eq!(
map.lookup(&Pattern::Concatenation(vec![
Pattern::Constant("card/".into()),
Pattern::Constant(rcstr!("card/")),
Pattern::Dynamic
]))
.collect::<Vec<_>>(),
vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![
Pattern::Constant("src/cards/".into()),
Pattern::Constant(rcstr!("src/cards/")),
Pattern::Dynamic
]))]
);
assert_eq!(
map.lookup(&Pattern::Concatenation(vec![
Pattern::Constant("comp/".into()),
Pattern::Constant(rcstr!("comp/")),
Pattern::Dynamic,
Pattern::Constant("/x".into()),
Pattern::Constant(rcstr!("/x")),
]))
.collect::<Vec<_>>(),
vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![
Pattern::Constant("src/comps/".into()),
Pattern::Constant(rcstr!("src/comps/")),
Pattern::Dynamic,
Pattern::Constant("/x".into()),
Pattern::Constant(rcstr!("/x")),
]))]
);
assert_eq!(
map.lookup(&Pattern::Concatenation(vec![
Pattern::Constant("head/".into()),
Pattern::Constant(rcstr!("head/")),
Pattern::Dynamic,
Pattern::Constant("/x".into()),
Pattern::Constant(rcstr!("/x")),
]))
.collect::<Vec<_>>(),
vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![
Pattern::Constant("src/heads/".into()),
Pattern::Constant(rcstr!("src/heads/")),
Pattern::Dynamic,
]))]
);
......
use turbo_rcstr::rcstr;
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
......@@ -9,28 +10,28 @@ use super::options::{
#[turbo_tasks::function]
pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
let conditions: ResolutionConditions = [
("node".into(), ConditionValue::Set),
("require".into(), ConditionValue::Set),
(rcstr!("node"), ConditionValue::Set),
(rcstr!("require"), ConditionValue::Set),
]
.into();
let extensions = vec![".js".into(), ".json".into(), ".node".into()];
let extensions = vec![rcstr!(".js"), rcstr!(".json"), rcstr!(".node")];
ResolveOptions {
extensions,
modules: vec![ResolveModules::Nested(root, vec!["node_modules".into()])],
modules: vec![ResolveModules::Nested(root, vec![rcstr!("node_modules")])],
into_package: vec![
ResolveIntoPackage::ExportsField {
conditions: conditions.clone(),
unspecified_conditions: ConditionValue::Unset,
},
ResolveIntoPackage::MainField {
field: "main".into(),
field: rcstr!("main"),
},
],
in_package: vec![ResolveInPackage::ImportsField {
conditions,
unspecified_conditions: ConditionValue::Unset,
}],
default_files: vec!["index".into()],
default_files: vec![rcstr!("index")],
..Default::default()
}
.cell()
......@@ -39,29 +40,29 @@ pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
#[turbo_tasks::function]
pub fn node_esm_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
let conditions: ResolutionConditions = [
("node".into(), ConditionValue::Set),
("import".into(), ConditionValue::Set),
(rcstr!("node"), ConditionValue::Set),
(rcstr!("import"), ConditionValue::Set),
]
.into();
let extensions = vec![".js".into(), ".json".into(), ".node".into()];
let extensions = vec![rcstr!(".js"), rcstr!(".json"), rcstr!(".node")];
ResolveOptions {
fully_specified: true,
extensions,
modules: vec![ResolveModules::Nested(root, vec!["node_modules".into()])],
modules: vec![ResolveModules::Nested(root, vec![rcstr!("node_modules")])],
into_package: vec![
ResolveIntoPackage::ExportsField {
conditions: conditions.clone(),
unspecified_conditions: ConditionValue::Unset,
},
ResolveIntoPackage::MainField {
field: "main".into(),
field: rcstr!("main"),
},
],
in_package: vec![ResolveInPackage::ImportsField {
conditions,
unspecified_conditions: ConditionValue::Unset,
}],
default_files: vec!["index".into()],
default_files: vec![rcstr!("index")],
..Default::default()
}
.cell()
......
......@@ -335,7 +335,8 @@ impl ImportMap {
prefix: impl Into<RcStr> + 'a,
mapping: ResolvedVc<ImportMapping>,
) {
self.map.insert(AliasPattern::wildcard(prefix, ""), mapping);
self.map
.insert(AliasPattern::wildcard(prefix, rcstr!("")), mapping);
}
/// Inserts a wildcard alias with suffix into the import map.
......
......@@ -487,7 +487,7 @@ fn is_folder_shorthand(key: &str) -> bool {
/// we do the expansion here.
fn expand_folder_shorthand(key: &str, value: &mut SubpathValue) -> Result<AliasPattern> {
// Transform folder patterns into wildcard patterns.
let pattern = AliasPattern::wildcard(key, "");
let pattern = AliasPattern::wildcard(key, rcstr!(""));
// Transform templates into wildcard patterns as well.
for result in value.results_mut() {
......
......@@ -7,7 +7,7 @@ use ref_cast::RefCast;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use swc_sourcemap::{DecodedMap, SourceMap as RegularMap, SourceMapBuilder, SourceMapIndex};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::{
File, FileContent, FileSystem, FileSystemPath, VirtualFileSystem,
......@@ -548,7 +548,7 @@ impl SourceMap {
#[turbo_tasks::function]
fn sourcemap_content_fs_root() -> Vc<FileSystemPath> {
VirtualFileSystem::new_with_name("sourcemap-content".into()).root()
VirtualFileSystem::new_with_name(rcstr!("sourcemap-content")).root()
}
#[turbo_tasks::function]
......
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{
......@@ -37,7 +38,7 @@ impl OutputAsset for SingleItemCssChunkSourceMapAsset {
Some(Vc::upcast(self)),
this.chunk.ident_for_path(),
None,
".single.css".into(),
rcstr!(".single.css"),
)
.await?
.append(".map")?
......
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{
......@@ -34,7 +35,7 @@ impl OutputAsset for CssChunkSourceMapAsset {
.chunk
.await?
.chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, None, ".css".into())
.chunk_path(Some(Vc::upcast(self)), ident, None, rcstr!(".css"))
.await?
.append(".map")?
.cell())
......
......@@ -385,7 +385,7 @@ impl Issue for FatalStreamIssue {
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::Other("websocket".into()).cell()
IssueStage::Other(rcstr!("websocket")).cell()
}
#[turbo_tasks::function]
......
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{
code_builder::{Code, CodeBuilder},
......@@ -17,27 +18,27 @@ pub async fn get_nodejs_runtime_code(
let shared_runtime_utils_code = embed_static_code(
asset_context,
"shared/runtime-utils.ts".into(),
rcstr!("shared/runtime-utils.ts"),
generate_source_map,
);
let shared_base_external_utils_code = embed_static_code(
asset_context,
"shared-node/base-externals-utils.ts".into(),
rcstr!("shared-node/base-externals-utils.ts"),
generate_source_map,
);
let shared_node_external_utils_code = embed_static_code(
asset_context,
"shared-node/node-externals-utils.ts".into(),
rcstr!("shared-node/node-externals-utils.ts"),
generate_source_map,
);
let shared_node_wasm_utils_code = embed_static_code(
asset_context,
"shared-node/node-wasm-utils.ts".into(),
rcstr!("shared-node/node-wasm-utils.ts"),
generate_source_map,
);
let runtime_code = embed_static_code(
asset_context,
"nodejs/runtime.ts".into(),
rcstr!("nodejs/runtime.ts"),
generate_source_map,
);
......
......@@ -40,7 +40,7 @@ static ANNOTATION_CHUNKING_TYPE: Lazy<Atom> =
Lazy::new(|| crate::annotations::ANNOTATION_CHUNKING_TYPE.into());
/// Changes the type of the resolved module (only "json" is supported currently)
static ATTRIBUTE_MODULE_TYPE: Lazy<Atom> = Lazy::new(|| "type".into());
static ATTRIBUTE_MODULE_TYPE: Lazy<Atom> = Lazy::new(|| atom!("type"));
impl ImportAnnotations {
pub fn parse(with: Option<&ObjectLit>) -> ImportAnnotations {
......@@ -497,7 +497,7 @@ impl Visit for Analyzer<'_> {
Some(imported) => (local.to_id(), orig_name(imported)),
_ => (local.to_id(), local.sym.clone()),
},
ImportSpecifier::Default(s) => (s.local.to_id(), "default".into()),
ImportSpecifier::Default(s) => (s.local.to_id(), atom!("default")),
ImportSpecifier::Namespace(s) => {
self.data.namespace_imports.insert(s.local.to_id(), i);
continue;
......
......@@ -3960,8 +3960,8 @@ pub mod test_utils {
}
}
JsValue::FreeVar(ref var) => match &**var {
"__dirname" => "__dirname".into(),
"__filename" => "__filename".into(),
"__dirname" => rcstr!("__dirname").into(),
"__filename" => rcstr!("__filename").into(),
"require" => JsValue::unknown_if(
ignore,
......
use std::mem::take;
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::Vc;
use turbopack_core::compile_time_info::CompileTimeInfo;
use url::Url;
......@@ -162,7 +163,7 @@ pub fn object_assign(args: Vec<JsValue>) -> JsValue {
pub fn path_join(args: Vec<JsValue>) -> JsValue {
if args.is_empty() {
return ".".into();
return rcstr!(".").into();
}
let mut parts = Vec::new();
for item in args {
......@@ -203,9 +204,12 @@ pub fn path_join(args: Vec<JsValue>) -> JsValue {
for part in iter {
let is_str = part.as_str().is_some();
if last_is_str && is_str {
results.push("/".into());
results.push(rcstr!("/").into());
} else {
results.push(JsValue::alternatives(vec!["/".into(), "".into()]));
results.push(JsValue::alternatives(vec![
rcstr!("/").into(),
rcstr!("").into(),
]));
}
results.push(part);
last_is_str = is_str;
......@@ -246,7 +250,7 @@ pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue {
}
".." => {
if results.pop().is_none() {
results_final.push("..".into());
results_final.push(rcstr!("..").into());
}
}
_ => results.push(str.into()),
......@@ -274,9 +278,12 @@ pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue {
for part in iter {
let is_str = part.as_str().is_some();
if last_was_str && is_str {
results.push("/".into());
results.push(rcstr!("/").into());
} else {
results.push(JsValue::alternatives(vec!["/".into(), "".into()]));
results.push(JsValue::alternatives(vec![
rcstr!("/").into(),
rcstr!("").into(),
]));
}
results.push(part);
last_was_str = is_str;
......@@ -291,7 +298,7 @@ pub fn path_dirname(mut args: Vec<JsValue>) -> JsValue {
if let Some(i) = str.rfind('/') {
return JsValue::Constant(ConstantValue::Str(str[..i].to_string().into()));
} else {
return JsValue::Constant(ConstantValue::Str("".into()));
return JsValue::Constant(ConstantValue::Str(rcstr!("").into()));
}
} else if let JsValue::Concat(_, items) = arg
&& let Some(last) = items.last_mut()
......
......@@ -3,6 +3,7 @@ use std::sync::Arc;
use anyhow::{Context, Result, bail};
use bytes_str::BytesStr;
use swc_core::{
atoms::atom,
base::try_with_handler,
common::{
BytePos, FileName, FilePathMapping, GLOBALS, LineCol, Mark, SourceMap as SwcSourceMap,
......@@ -89,7 +90,7 @@ pub fn minify(code: Code, source_maps: bool, mangle: Option<MangleType>) -> Resu
..Default::default()
}),
mangle: mangle.map(|mangle| {
let reserved = vec!["AbortSignal".into()];
let reserved = vec![atom!("AbortSignal")];
match mangle {
MangleType::OptimalSize => MangleOptions {
reserved,
......
......@@ -310,14 +310,14 @@ async fn parse_file_content(
let (emitter, collector) = IssueEmitter::new(
source,
source_map.clone(),
Some("Ecmascript file had an error".into()),
Some(rcstr!("Ecmascript file had an error")),
);
let handler = Handler::with_emitter(true, false, Box::new(emitter));
let (emitter, collector_parse) = IssueEmitter::new(
source,
source_map.clone(),
Some("Parsing ecmascript source code failed".into()),
Some(rcstr!("Parsing ecmascript source code failed")),
);
let parser_handler = Handler::with_emitter(true, false, Box::new(emitter));
let globals = Arc::new(Globals::new());
......
......@@ -866,9 +866,9 @@ impl Issue for CircularReExport {
#[turbo_tasks::function]
async fn title(&self) -> Result<Vc<StyledString>> {
Ok(StyledString::Line(vec![
StyledString::Text("Export ".into()),
StyledString::Text(rcstr!("Export ")),
StyledString::Code(self.export.clone()),
StyledString::Text(" is a circular re-export".into()),
StyledString::Text(rcstr!(" is a circular re-export")),
])
.cell())
}
......@@ -887,20 +887,20 @@ impl Issue for CircularReExport {
async fn description(&self) -> Result<Vc<OptionStyledString>> {
Ok(Vc::cell(Some(
StyledString::Stack(vec![
StyledString::Line(vec![StyledString::Text("The export".into())]),
StyledString::Line(vec![StyledString::Text(rcstr!("The export"))]),
StyledString::Line(vec![
StyledString::Code(self.export.clone()),
StyledString::Text(" of module ".into()),
StyledString::Text(rcstr!(" of module ")),
StyledString::Strong(self.module.ident().to_string().owned().await?),
]),
StyledString::Line(vec![StyledString::Text(
"is a re-export of the export".into(),
)]),
StyledString::Line(vec![StyledString::Text(rcstr!(
"is a re-export of the export"
))]),
StyledString::Line(vec![
StyledString::Code(self.import.clone().unwrap_or_else(|| "*".into())),
StyledString::Text(" of module ".into()),
StyledString::Code(self.import.clone().unwrap_or_else(|| rcstr!("*"))),
StyledString::Text(rcstr!(" of module ")),
StyledString::Strong(self.module_cycle.ident().to_string().owned().await?),
StyledString::Text(".".into()),
StyledString::Text(rcstr!(".")),
]),
])
.resolved_cell(),
......
......@@ -39,7 +39,7 @@ use regex::Regex;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use swc_core::{
atoms::Atom,
atoms::{Atom, atom},
common::{
GLOBALS, Globals, Span, Spanned,
comments::{CommentKind, Comments},
......@@ -1469,7 +1469,7 @@ async fn compile_time_info_for_module_type(
DefinableNameSegment::Name(rcstr!("meta")),
DefinableNameSegment::TypeOf,
])
.or_insert("object".into());
.or_insert(rcstr!("object").into());
free_var_references
.entry(vec![
DefinableNameSegment::Name(rcstr!("exports")),
......@@ -1487,31 +1487,31 @@ async fn compile_time_info_for_module_type(
DefinableNameSegment::Name(rcstr!("require")),
DefinableNameSegment::TypeOf,
])
.or_insert("function".into());
.or_insert(rcstr!("function").into());
free_var_references
.entry(vec![DefinableNameSegment::Name(rcstr!("require"))])
.or_insert(require.into());
let dir_name: RcStr = rcstr!("__dirname");
let dir_name = rcstr!("__dirname");
free_var_references
.entry(vec![
DefinableNameSegment::Name(dir_name.clone()),
DefinableNameSegment::TypeOf,
])
.or_insert("string".into());
.or_insert(rcstr!("string").into());
free_var_references
.entry(vec![DefinableNameSegment::Name(dir_name)])
.or_insert(FreeVarReference::InputRelative(
InputRelativeConstant::DirName,
));
let file_name: RcStr = rcstr!("__filename");
let file_name = rcstr!("__filename");
free_var_references
.entry(vec![
DefinableNameSegment::Name(file_name.clone()),
DefinableNameSegment::TypeOf,
])
.or_insert("string".into());
.or_insert(rcstr!("string").into());
free_var_references
.entry(vec![DefinableNameSegment::Name(file_name)])
.or_insert(FreeVarReference::InputRelative(
......@@ -1519,16 +1519,16 @@ async fn compile_time_info_for_module_type(
));
// Compiletime rewrite the nodejs `global` to `globalThis`
let global: RcStr = rcstr!("global");
let global = rcstr!("global");
free_var_references
.entry(vec![
DefinableNameSegment::Name(global.clone()),
DefinableNameSegment::TypeOf,
])
.or_insert("object".into());
.or_insert(rcstr!("object").into());
free_var_references
.entry(vec![DefinableNameSegment::Name(global)])
.or_insert(FreeVarReference::Ident("globalThis".into()));
.or_insert(FreeVarReference::Ident(rcstr!("globalThis")));
free_var_references.extend(TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS.into_iter().map(
|(name, shortcut)| {
......@@ -1558,9 +1558,9 @@ async fn compile_time_info_for_module_type(
DefinableNameSegment::TypeOf,
])
.or_insert(if is_esm {
"undefined".into()
rcstr!("undefined").into()
} else {
"object".into()
rcstr!("object").into()
});
Ok(CompileTimeInfo {
environment: compile_time_info.environment,
......@@ -2268,7 +2268,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
WellKnownFunctionKind::PathJoin,
)),
vec![
JsValue::FreeVar("__dirname".into()),
JsValue::FreeVar(atom!("__dirname")),
pkg_or_dir.clone(),
],
),
......@@ -2328,9 +2328,9 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
WellKnownFunctionKind::PathJoin,
)),
vec![
JsValue::FreeVar("__dirname".into()),
JsValue::FreeVar(atom!("__dirname")),
p.into(),
"intl".into(),
atom!("intl").into(),
],
),
ImportAttributes::empty_ref(),
......@@ -3567,7 +3567,7 @@ impl From<Vec<AstParentKind>> for AstPath {
}
}
pub static TURBOPACK_HELPER: Lazy<Atom> = Lazy::new(|| "__turbopack-helper__".into());
pub static TURBOPACK_HELPER: Lazy<Atom> = Lazy::new(|| atom!("__turbopack-helper__"));
pub fn is_turbopack_helper_import(import: &ImportDecl) -> bool {
let annotations = ImportAnnotations::parse(import.with.as_deref());
......
......@@ -10,7 +10,7 @@ use swc_core::{
},
quote, quote_expr,
};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, Vc, debug::ValueDebugFormat,
trace::TraceRawVcs,
......@@ -341,9 +341,9 @@ async fn to_single_pattern_mapping(
// TODO implement mapping
CodeGenerationIssue {
severity: IssueSeverity::Bug,
title: StyledString::Text(
"pattern mapping is not implemented for this result".into(),
)
title: StyledString::Text(rcstr!(
"pattern mapping is not implemented for this result"
))
.resolved_cell(),
message: StyledString::Text(
format!(
......@@ -374,10 +374,10 @@ async fn to_single_pattern_mapping(
}
CodeGenerationIssue {
severity: IssueSeverity::Bug,
title: StyledString::Text("non-ecmascript placeable asset".into()).resolved_cell(),
message: StyledString::Text(
"asset is not placeable in ESM chunks, so it doesn't have a module id".into(),
)
title: StyledString::Text(rcstr!("non-ecmascript placeable asset")).resolved_cell(),
message: StyledString::Text(rcstr!(
"asset is not placeable in ESM chunks, so it doesn't have a module id"
))
.resolved_cell(),
path: origin.origin_path().owned().await?,
}
......
......@@ -3,7 +3,7 @@ use std::mem::take;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{
atoms::atom,
atoms::{Atom, atom},
base::SwcComments,
common::{
DUMMY_SP, Span, Spanned,
......@@ -37,6 +37,9 @@ pub struct Unreachable {
range: AstPathRange,
}
fn unreachable_atom() -> Atom {
atom!("TURBOPACK unreachable")
}
struct UnreachableModifier {
comments: SwcComments,
}
......@@ -49,7 +52,7 @@ impl AstModifier for UnreachableModifier {
*node = Expr::Lit(Lit::Str(Str {
span,
value: atom!("TURBOPACK unreachable"),
value: unreachable_atom(),
raw: None,
}));
}
......@@ -64,7 +67,7 @@ impl AstModifier for UnreachableModifier {
Comment {
kind: CommentKind::Line,
span: DUMMY_SP,
text: atom!("TURBOPACK unreachable"),
text: unreachable_atom(),
},
);
......@@ -111,7 +114,7 @@ impl UnreachableRangeModifier {
Comment {
kind: CommentKind::Line,
span: DUMMY_SP,
text: atom!("TURBOPACK unreachable"),
text: unreachable_atom(),
},
);
......
use std::fmt::{Display, Formatter};
use swc_core::ecma::ast::{Expr, MemberExpr, MemberProp};
use swc_core::{
atoms::atom,
ecma::ast::{Expr, MemberExpr, MemberProp},
};
use turbo_rcstr::rcstr;
use turbopack_core::compile_time_info::FreeVarReference;
pub struct TurbopackRuntimeFunctionShortcut {
......@@ -29,14 +33,14 @@ impl Display for TurbopackRuntimeFunctionShortcut {
impl From<&TurbopackRuntimeFunctionShortcut> for FreeVarReference {
fn from(val: &TurbopackRuntimeFunctionShortcut) -> Self {
FreeVarReference::Member("__turbopack_context__".into(), val.shortcut.into())
FreeVarReference::Member(rcstr!("__turbopack_context__"), val.shortcut.into())
}
}
impl From<&TurbopackRuntimeFunctionShortcut> for Expr {
fn from(val: &TurbopackRuntimeFunctionShortcut) -> Self {
Expr::Member(MemberExpr {
obj: Box::new(Expr::Ident("__turbopack_context__".into())),
obj: Box::new(Expr::Ident(atom!("__turbopack_context__").into())),
prop: MemberProp::Ident(val.shortcut.into()),
..Default::default()
})
......
......@@ -45,7 +45,7 @@ pub enum EcmascriptInputTransform {
runtime: ResolvedVc<Option<RcStr>>,
},
GlobalTypeofs {
window_value: String,
window_value: RcStr,
},
// These options are subset of swc_core::ecma::transforms::typescript::Config, but
// it doesn't derive `Copy` so repeating values in here
......
......@@ -10,6 +10,7 @@ use petgraph::{
};
use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{
atoms::atom,
common::{BytePos, DUMMY_SP, Spanned, SyntaxContext, comments::Comments, util::take::Take},
ecma::{
ast::{
......@@ -695,7 +696,7 @@ impl DepGraph {
is_type_only: false,
})],
src: if cfg!(test) {
Some(Box::new("__TURBOPACK_VAR__".into()))
Some(Box::new(atom!("__TURBOPACK_VAR__").into()))
} else {
None
},
......@@ -929,7 +930,7 @@ impl DepGraph {
),
ExportSpecifier::Default(s) => (
Some(ModuleExportName::Ident(Ident::new(
"default".into(),
atom!("default"),
DUMMY_SP,
Default::default(),
))),
......@@ -1076,7 +1077,7 @@ impl DepGraph {
items.insert(id, data);
}
exports.push((default_var.to_id(), "default".into()));
exports.push((default_var.to_id(), atom!("default")));
}
ModuleDecl::ExportDefaultExpr(export) => {
// Mirror what `EsmModuleItem::code_generation` does, these are live
......@@ -1140,7 +1141,7 @@ impl DepGraph {
{
// For export default __TURBOPACK__default__export__
exports.push((default_var.to_id(), "default".into()));
exports.push((default_var.to_id(), atom!("default")));
}
}
......
......@@ -3,10 +3,10 @@ use std::{collections::BTreeMap, fmt::Write, hash::Hash, path::PathBuf, sync::Ar
use anyhow::Error;
use serde::Deserialize;
use swc_core::{
atoms::atom,
common::{Mark, SourceMap, SyntaxContext, comments::SingleThreadedComments, util::take::Take},
ecma::{
ast::{EsVersion, Id, Module},
atoms::Atom,
codegen::text_writer::JsWriter,
parser::{EsSyntax, parse_file_as_module},
visit::VisitMutWith,
......@@ -175,7 +175,7 @@ fn run(input: PathBuf) {
)
.unwrap();
let uri_of_module: Atom = "entry.js".into();
let uri_of_module = atom!("entry.js");
let mut describe =
|is_debug: bool, title: &str, entries: Vec<ItemIdGroupKind>, skip_parts: bool| {
......
......@@ -265,7 +265,11 @@ mod tests {
Pattern::Constant(rcstr!("hello/world")),
js_value_to_pattern(&JsValue::Concat(
1,
vec!["hello".into(), "\\".into(), "world".into()]
vec![
rcstr!("hello").into(),
rcstr!("\\").into(),
rcstr!("world").into()
]
))
);
}
......
......@@ -12,25 +12,25 @@ use crate::TryDotenvProcessEnv;
pub async fn load_env(project_path: FileSystemPath) -> Result<Vc<Box<dyn ProcessEnv>>> {
let env: Vc<Box<dyn ProcessEnv>> = Vc::upcast(CommandLineProcessEnv::new());
let node_env = env.read(rcstr!("NODE_ENV")).await?;
let node_env = node_env.as_deref().unwrap_or("development");
let node_env = env.read(rcstr!("NODE_ENV")).owned().await?;
let node_env = node_env.unwrap_or(rcstr!("development"));
let env = Vc::upcast(CustomProcessEnv::new(
env,
Vc::cell(fxindexmap! {
rcstr!("NODE_ENV") => node_env.into(),
rcstr!("NODE_ENV") => node_env.clone(),
}),
));
let mut files = [
Some(format!(".env.{node_env}.local")),
Some(format!(".env.{node_env}.local").into()),
if node_env == "test" {
None
} else {
Some(".env.local".into())
Some(rcstr!(".env.local"))
},
Some(format!(".env.{node_env}")),
Some(".env".into()),
Some(format!(".env.{node_env}").into()),
Some(rcstr!(".env")),
]
.into_iter()
.flatten();
......
......@@ -321,7 +321,7 @@ pub async fn tsconfig_resolve_options(
})
.collect();
all_paths.insert(
key.to_string(),
RcStr::from(key.as_str()),
ImportMapping::primary_alternatives(entries, Some(context_dir.clone())),
);
} else {
......
......@@ -141,7 +141,7 @@ fn get_messages(js_results: JsResult) -> Vec<String> {
let mut messages = vec![];
if js_results.jest_result.test_results.is_empty() {
messages.push("No tests were run.".into());
messages.push("No tests were run.".to_string());
}
for test_result in js_results.jest_result.test_results {
......@@ -191,7 +191,7 @@ async fn run(resource: PathBuf, snapshot_mode: IssueSnapshotMode) -> Result<JsRe
// Set up a `tracing_subscriber` for debugging -- We can only do this when using nextest, as
// `cargo test` runs all execution test cases in the same process.
//
// Configuring `tracing_subscriber` requires proces-global side-effects. We can't use a
// Configuring `tracing_subscriber` requires process-global side-effects. We can't use a
// thread-local subscriber because we're not fully single-threaded, even with the
// `current_thread` tokio executor.
//
......@@ -359,7 +359,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
let mut import_map = ImportMap::empty();
import_map.insert_wildcard_alias(
"esm-external/",
rcstr!("esm-external/"),
ImportMapping::External(
Some(rcstr!("*")),
ExternalType::EcmaScriptModule,
......@@ -368,7 +368,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
.resolved_cell(),
);
import_map.insert_exact_alias(
"jest-circus",
rcstr!("jest-circus"),
ImportMapping::External(None, ExternalType::CommonJs, ExternalTraced::Untraced)
.resolved_cell(),
);
......
......@@ -79,7 +79,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) {
let input: RcStr = bench_input.input.clone().into();
async move {
let task = tt.spawn_once_task(async move {
let input_fs = DiskFileSystem::new("tests".into(), tests_root.clone());
let input_fs = DiskFileSystem::new(rcstr!("tests"), tests_root.clone());
let input = input_fs.root().await?.join(&input)?;
let input_dir = input.parent().parent();
......
......@@ -43,7 +43,7 @@ pub async fn node_evaluate_asset_context(
ImportMap::empty()
};
import_map.insert_wildcard_alias(
"@vercel/turbopack-node/",
rcstr!("@vercel/turbopack-node/"),
ImportMapping::PrimaryAlternative(
rcstr!("./*"),
Some(turbopack_node::embed_js::embed_fs().root().owned().await?),
......
......@@ -654,8 +654,8 @@ async fn externals_tracing_module_context(ty: ExternalType) -> Result<Vc<ModuleA
emulate_environment: Some(env),
loose_errors: true,
custom_conditions: match ty {
ExternalType::CommonJs => vec!["require".into()],
ExternalType::EcmaScriptModule => vec!["import".into()],
ExternalType::CommonJs => vec![rcstr!("require")],
ExternalType::EcmaScriptModule => vec![rcstr!("import")],
ExternalType::Url | ExternalType::Global | ExternalType::Script => vec![],
},
..Default::default()
......
......@@ -37,7 +37,10 @@ fn package_import_map_from_import_mapping(
package_mapping: ResolvedVc<ImportMapping>,
) -> Vc<ImportMap> {
let mut import_map = ImportMap::default();
import_map.insert_exact_alias(format!("@vercel/turbopack/{package_name}"), package_mapping);
import_map.insert_exact_alias(
RcStr::from(format!("@vercel/turbopack/{package_name}")),
package_mapping,
);
import_map.cell()
}
......@@ -48,7 +51,7 @@ fn package_import_map_from_context(
) -> Vc<ImportMap> {
let mut import_map = ImportMap::default();
import_map.insert_exact_alias(
format!("@vercel/turbopack/{package_name}"),
RcStr::from(format!("@vercel/turbopack/{package_name}")),
ImportMapping::PrimaryAlternative(package_name, Some(context_path)).resolved_cell(),
);
import_map.cell()
......@@ -181,8 +184,8 @@ impl ModuleOptions {
if let Some(enable_typeof_window_inlining) = enable_typeof_window_inlining {
transforms.push(EcmascriptInputTransform::GlobalTypeofs {
window_value: match enable_typeof_window_inlining {
TypeofWindow::Object => "object".to_string(),
TypeofWindow::Undefined => "undefined".to_string(),
TypeofWindow::Object => rcstr!("object"),
TypeofWindow::Undefined => rcstr!("undefined"),
},
});
}
......@@ -461,7 +464,7 @@ impl ModuleOptions {
.context("execution_context is required for the postcss_transform")?;
let import_map = if let Some(postcss_package) = options.postcss_package {
package_import_map_from_import_mapping("postcss".into(), *postcss_package)
package_import_map_from_import_mapping(rcstr!("postcss"), *postcss_package)
} else {
package_import_map_from_context(
rcstr!("postcss"),
......@@ -618,12 +621,12 @@ impl ModuleOptions {
webpack_loaders_options.loader_runner_package
{
package_import_map_from_import_mapping(
"loader-runner".into(),
rcstr!("loader-runner"),
*loader_runner_package,
)
} else {
package_import_map_from_context(
"loader-runner".into(),
rcstr!("loader-runner"),
path.context("need_path in ModuleOptions::new is incorrect")?,
)
};
......
......@@ -141,7 +141,7 @@ impl RuleCondition {
let content_type = &source.ident().await?.content_type;
return Ok(content_type
.as_ref()
.is_some_and(|ct| ct.starts_with(start)));
.is_some_and(|ct| ct.starts_with(start.as_str())));
}
RuleCondition::ContentTypeEmpty => {
return Ok(source.ident().await?.content_type.is_none());
......
......@@ -34,7 +34,7 @@ impl AfterResolvePlugin for UnsupportedSassResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new(
self.root.root().owned().await?,
Glob::new("**/*.{sass,scss}".into()),
Glob::new(rcstr!("**/*.{sass,scss}")),
))
}
......
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