Unverified Commit 3cf225c8 authored by Donny/강동윤's avatar Donny/강동윤 Committed by GitHub

feat(turbopack): Introduce `RcStr` (#66262)

# Turbopack

* https://github.com/vercel/turbo/pull/8272 <!-- Donny/강동윤 - feat:
Update `swc_core` to `v0.92.8` -->
* https://github.com/vercel/turbo/pull/8262 <!-- Alexander Lyon - add
crate to calculate prehashes -->
* https://github.com/vercel/turbo/pull/8174 <!-- Tobias Koppers - use
prehash to avoid rehashing the key in the task cache -->
* https://github.com/vercel/turbo/pull/7674 <!-- Alexander Lyon - [turbo
trace] add ability to filter by value and occurences -->
* https://github.com/vercel/turbo/pull/8287 <!-- Donny/강동윤 - feat:
Update `swc_core` to `v0.92.10` -->
* https://github.com/vercel/turbo/pull/8037 <!-- Alexander Lyon - create
turbo-static for compile time graph analysis -->
* https://github.com/vercel/turbo/pull/8293 <!-- Will Binns-Smith - Sync
Cargo.lock with Next.js -->
* https://github.com/vercel/turbo/pull/8239 <!-- Benjamin Woodruff -
Reduce amount of code generated by ValueDebugFormat -->
* https://github.com/vercel/turbo/pull/8304 <!-- Benjamin Woodruff -
Minor optimizations to the codegen of TaskFnInputFunction -->
* https://github.com/vercel/turbo/pull/8221 <!-- Donny/강동윤 - perf:
Introduce `RcStr` -->


### What?

I tried using `Arc<String>` in
https://github.com/vercel/turbo/pull/7772, but a team member suggested
creating a new type so we can replace underlying implementation easily
in the future.

### Why?

To reduce memory usage.

### How?

Closes PACK-2776
parent 750ae91e
This diff is collapsed.
...@@ -37,11 +37,11 @@ swc_core = { version = "0.92.10", features = [ ...@@ -37,11 +37,11 @@ swc_core = { version = "0.92.10", features = [
testing = { version = "0.35.25" } testing = { version = "0.35.25" }
# Turbo crates # Turbo crates
turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240531.2" } turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240605.1" }
# [TODO]: need to refactor embed_directory! macro usages, as well as resolving turbo_tasks::function, macros.. # [TODO]: need to refactor embed_directory! macro usages, as well as resolving turbo_tasks::function, macros..
turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240531.2" } turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240605.1" }
# [TODO]: need to refactor embed_directory! macro usage in next-core # [TODO]: need to refactor embed_directory! macro usage in next-core
turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240531.2" } turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240605.1" }
# General Deps # General Deps
......
...@@ -12,7 +12,7 @@ use next_core::app_structure::{ ...@@ -12,7 +12,7 @@ use next_core::app_structure::{
LoaderTree, MetadataItem, MetadataWithAltItem, LoaderTree, MetadataItem, MetadataWithAltItem,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{ReadRef, Vc}; use turbo_tasks::{RcStr, ReadRef, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::{ turbo::{
tasks::{ tasks::{
...@@ -27,12 +27,8 @@ use turbopack_binding::{ ...@@ -27,12 +27,8 @@ use turbopack_binding::{
use crate::register; use crate::register;
#[turbo_tasks::function] #[turbo_tasks::function]
async fn project_fs(project_dir: String, watching: bool) -> Result<Vc<Box<dyn FileSystem>>> { async fn project_fs(project_dir: RcStr, watching: bool) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new( let disk_fs = DiskFileSystem::new(PROJECT_FILESYSTEM_NAME.into(), project_dir, vec![]);
PROJECT_FILESYSTEM_NAME.to_string(),
project_dir.to_string(),
vec![],
);
if watching { if watching {
disk_fs.await?.start_watching_with_invalidation_reason()?; disk_fs.await?.start_watching_with_invalidation_reason()?;
} }
...@@ -42,8 +38,8 @@ async fn project_fs(project_dir: String, watching: bool) -> Result<Vc<Box<dyn Fi ...@@ -42,8 +38,8 @@ async fn project_fs(project_dir: String, watching: bool) -> Result<Vc<Box<dyn Fi
#[turbo_tasks::value] #[turbo_tasks::value]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct LoaderTreeForJs { struct LoaderTreeForJs {
segment: String, segment: RcStr,
parallel_routes: IndexMap<String, ReadRef<LoaderTreeForJs>>, parallel_routes: IndexMap<RcStr, ReadRef<LoaderTreeForJs>>,
#[turbo_tasks(trace_ignore)] #[turbo_tasks(trace_ignore)]
components: ComponentsForJs, components: ComponentsForJs,
#[turbo_tasks(trace_ignore)] #[turbo_tasks(trace_ignore)]
...@@ -57,13 +53,13 @@ enum EntrypointForJs { ...@@ -57,13 +53,13 @@ enum EntrypointForJs {
loader_tree: ReadRef<LoaderTreeForJs>, loader_tree: ReadRef<LoaderTreeForJs>,
}, },
AppRoute { AppRoute {
path: String, path: RcStr,
}, },
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct EntrypointsForJs(HashMap<String, EntrypointForJs>); struct EntrypointsForJs(HashMap<RcStr, EntrypointForJs>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
struct OptionEntrypointsForJs(Option<Vc<EntrypointsForJs>>); struct OptionEntrypointsForJs(Option<Vc<EntrypointsForJs>>);
...@@ -71,14 +67,14 @@ struct OptionEntrypointsForJs(Option<Vc<EntrypointsForJs>>); ...@@ -71,14 +67,14 @@ struct OptionEntrypointsForJs(Option<Vc<EntrypointsForJs>>);
async fn fs_path_to_path( async fn fs_path_to_path(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
path: Vc<FileSystemPath>, path: Vc<FileSystemPath>,
) -> Result<String> { ) -> Result<RcStr> {
match project_path.await?.get_path_to(&*path.await?) { match project_path.await?.get_path_to(&*path.await?) {
None => Err(anyhow!( None => Err(anyhow!(
"Path {} is not inside of the project path {}", "Path {} is not inside of the project path {}",
path.to_string().await?, path.to_string().await?,
project_path.to_string().await? project_path.to_string().await?
)), )),
Some(p) => Ok(p.to_string()), Some(p) => Ok(p.into()),
} }
} }
...@@ -86,21 +82,21 @@ async fn fs_path_to_path( ...@@ -86,21 +82,21 @@ async fn fs_path_to_path(
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct ComponentsForJs { struct ComponentsForJs {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
page: Option<String>, page: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
layout: Option<String>, layout: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>, error: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
loading: Option<String>, loading: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
template: Option<String>, template: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none", rename = "not-found")] #[serde(skip_serializing_if = "Option::is_none", rename = "not-found")]
not_found: Option<String>, not_found: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
default: Option<String>, default: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
route: Option<String>, route: Option<RcStr>,
metadata: MetadataForJs, metadata: MetadataForJs,
} }
...@@ -134,19 +130,19 @@ struct GlobalMetadataForJs { ...@@ -134,19 +130,19 @@ struct GlobalMetadataForJs {
#[serde(tag = "type", rename_all = "camelCase")] #[serde(tag = "type", rename_all = "camelCase")]
enum MetadataWithAltItemForJs { enum MetadataWithAltItemForJs {
Static { Static {
path: String, path: RcStr,
alt_path: Option<String>, alt_path: Option<RcStr>,
}, },
Dynamic { Dynamic {
path: String, path: RcStr,
}, },
} }
#[derive(Deserialize, Serialize, PartialEq, Eq, ValueDebugFormat)] #[derive(Deserialize, Serialize, PartialEq, Eq, ValueDebugFormat)]
#[serde(tag = "type", rename_all = "camelCase")] #[serde(tag = "type", rename_all = "camelCase")]
enum MetadataItemForJs { enum MetadataItemForJs {
Static { path: String }, Static { path: RcStr },
Dynamic { path: String }, Dynamic { path: RcStr },
} }
async fn prepare_components_for_js( async fn prepare_components_for_js(
...@@ -166,7 +162,7 @@ async fn prepare_components_for_js( ...@@ -166,7 +162,7 @@ async fn prepare_components_for_js(
} = &*components.await?; } = &*components.await?;
let mut result = ComponentsForJs::default(); let mut result = ComponentsForJs::default();
async fn add( async fn add(
result: &mut Option<String>, result: &mut Option<RcStr>,
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
value: &Option<Vc<FileSystemPath>>, value: &Option<Vc<FileSystemPath>>,
) -> Result<()> { ) -> Result<()> {
...@@ -305,7 +301,7 @@ async fn prepare_entrypoints_for_js( ...@@ -305,7 +301,7 @@ async fn prepare_entrypoints_for_js(
.await? .await?
.iter() .iter()
.map(|(key, value)| { .map(|(key, value)| {
let key = key.to_string(); let key = key.to_string().into();
async move { async move {
let value = match *value { let value = match *value {
Entrypoint::AppPage { loader_tree, .. } => EntrypointForJs::AppPage { Entrypoint::AppPage { loader_tree, .. } => EntrypointForJs::AppPage {
...@@ -330,19 +326,19 @@ async fn prepare_entrypoints_for_js( ...@@ -330,19 +326,19 @@ async fn prepare_entrypoints_for_js(
#[turbo_tasks::function] #[turbo_tasks::function]
async fn get_value( async fn get_value(
root_dir: String, root_dir: RcStr,
project_dir: String, project_dir: RcStr,
page_extensions: Vec<String>, page_extensions: Vec<RcStr>,
watching: bool, watching: bool,
) -> Result<Vc<OptionEntrypointsForJs>> { ) -> Result<Vc<OptionEntrypointsForJs>> {
let page_extensions = Vc::cell(page_extensions); let page_extensions = Vc::cell(page_extensions);
let fs = project_fs(root_dir.clone(), watching); let fs = project_fs(root_dir.clone(), watching);
let project_relative = project_dir.strip_prefix(&root_dir).unwrap(); let project_relative = project_dir.strip_prefix(&*root_dir).unwrap();
let project_relative = project_relative let project_relative = project_relative
.strip_prefix(MAIN_SEPARATOR) .strip_prefix(MAIN_SEPARATOR)
.unwrap_or(project_relative) .unwrap_or(project_relative)
.replace(MAIN_SEPARATOR, "/"); .replace(MAIN_SEPARATOR, "/");
let project_path = fs.root().join(project_relative); let project_path = fs.root().join(project_relative.into());
let app_dir = find_app_dir(project_path); let app_dir = find_app_dir(project_path);
...@@ -373,8 +369,8 @@ pub fn stream_entrypoints( ...@@ -373,8 +369,8 @@ pub fn stream_entrypoints(
let value = serde_json::to_value(value)?; let value = serde_json::to_value(value)?;
Ok(vec![value]) Ok(vec![value])
})?; })?;
let root_dir = Arc::new(root_dir); let root_dir = RcStr::from(root_dir);
let project_dir = Arc::new(project_dir); let project_dir = RcStr::from(project_dir);
let page_extensions = Arc::new(page_extensions); let page_extensions = Arc::new(page_extensions);
turbo_tasks.spawn_root_task(move || { turbo_tasks.spawn_root_task(move || {
let func: ThreadsafeFunction<Option<ReadRef<EntrypointsForJs>>> = func.clone(); let func: ThreadsafeFunction<Option<ReadRef<EntrypointsForJs>>> = func.clone();
...@@ -383,9 +379,9 @@ pub fn stream_entrypoints( ...@@ -383,9 +379,9 @@ pub fn stream_entrypoints(
let page_extensions: Arc<Vec<String>> = page_extensions.clone(); let page_extensions: Arc<Vec<String>> = page_extensions.clone();
Box::pin(async move { Box::pin(async move {
if let Some(entrypoints) = &*get_value( if let Some(entrypoints) = &*get_value(
(*root_dir).clone(), root_dir.clone(),
(*project_dir).clone(), project_dir.clone(),
page_extensions.iter().map(|s| s.to_string()).collect(), page_extensions.iter().map(|s| s.as_str().into()).collect(),
true, true,
) )
.await? .await?
...@@ -415,9 +411,9 @@ pub async fn get_entrypoints( ...@@ -415,9 +411,9 @@ pub async fn get_entrypoints(
let result = turbo_tasks let result = turbo_tasks
.run_once(async move { .run_once(async move {
let value = if let Some(entrypoints) = &*get_value( let value = if let Some(entrypoints) = &*get_value(
root_dir, root_dir.into(),
project_dir, project_dir.into(),
page_extensions.iter().map(|s| s.to_string()).collect(), page_extensions.iter().map(|s| s.as_str().into()).collect(),
false, false,
) )
.await? .await?
......
...@@ -57,7 +57,7 @@ impl From<WrittenEndpoint> for NapiWrittenEndpoint { ...@@ -57,7 +57,7 @@ impl From<WrittenEndpoint> for NapiWrittenEndpoint {
} => Self { } => Self {
r#type: "nodejs".to_string(), r#type: "nodejs".to_string(),
entry_path: Some(server_entry_path), entry_path: Some(server_entry_path),
client_paths, client_paths: client_paths.into_iter().map(From::from).collect(),
server_paths: server_paths.into_iter().map(From::from).collect(), server_paths: server_paths.into_iter().map(From::from).collect(),
..Default::default() ..Default::default()
}, },
...@@ -66,7 +66,7 @@ impl From<WrittenEndpoint> for NapiWrittenEndpoint { ...@@ -66,7 +66,7 @@ impl From<WrittenEndpoint> for NapiWrittenEndpoint {
client_paths, client_paths,
} => Self { } => Self {
r#type: "edge".to_string(), r#type: "edge".to_string(),
client_paths, client_paths: client_paths.into_iter().map(From::from).collect(),
server_paths: server_paths.into_iter().map(From::from).collect(), server_paths: server_paths.into_iter().map(From::from).collect(),
..Default::default() ..Default::default()
}, },
......
...@@ -22,7 +22,7 @@ use rand::Rng; ...@@ -22,7 +22,7 @@ use rand::Rng;
use tokio::{io::AsyncWriteExt, time::Instant}; use tokio::{io::AsyncWriteExt, time::Instant};
use tracing::Instrument; use tracing::Instrument;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry};
use turbo_tasks::{Completion, ReadRef, TransientInstance, TurboTasks, UpdateInfo, Vc}; use turbo_tasks::{Completion, RcStr, ReadRef, TransientInstance, TurboTasks, UpdateInfo, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::{ turbo::{
tasks_fs::{DiskFileSystem, FileContent, FileSystem, FileSystemPath}, tasks_fs::{DiskFileSystem, FileContent, FileSystem, FileSystemPath},
...@@ -77,9 +77,9 @@ pub struct NapiDraftModeOptions { ...@@ -77,9 +77,9 @@ pub struct NapiDraftModeOptions {
impl From<NapiDraftModeOptions> for DraftModeOptions { impl From<NapiDraftModeOptions> for DraftModeOptions {
fn from(val: NapiDraftModeOptions) -> Self { fn from(val: NapiDraftModeOptions) -> Self {
DraftModeOptions { DraftModeOptions {
preview_mode_id: val.preview_mode_id, preview_mode_id: val.preview_mode_id.into(),
preview_mode_encryption_key: val.preview_mode_encryption_key, preview_mode_encryption_key: val.preview_mode_encryption_key.into(),
preview_mode_signing_key: val.preview_mode_signing_key, preview_mode_signing_key: val.preview_mode_signing_key.into(),
} }
} }
} }
...@@ -186,20 +186,20 @@ pub struct NapiTurboEngineOptions { ...@@ -186,20 +186,20 @@ pub struct NapiTurboEngineOptions {
impl From<NapiProjectOptions> for ProjectOptions { impl From<NapiProjectOptions> for ProjectOptions {
fn from(val: NapiProjectOptions) -> Self { fn from(val: NapiProjectOptions) -> Self {
ProjectOptions { ProjectOptions {
root_path: val.root_path, root_path: val.root_path.into(),
project_path: val.project_path, project_path: val.project_path.into(),
watch: val.watch, watch: val.watch,
next_config: val.next_config, next_config: val.next_config.into(),
js_config: val.js_config, js_config: val.js_config.into(),
env: val env: val
.env .env
.into_iter() .into_iter()
.map(|var| (var.name, var.value)) .map(|var| (var.name.into(), var.value.into()))
.collect(), .collect(),
define_env: val.define_env.into(), define_env: val.define_env.into(),
dev: val.dev, dev: val.dev,
encryption_key: val.encryption_key, encryption_key: val.encryption_key.into(),
build_id: val.build_id, build_id: val.build_id.into(),
preview_props: val.preview_props.into(), preview_props: val.preview_props.into(),
} }
} }
...@@ -208,18 +208,20 @@ impl From<NapiProjectOptions> for ProjectOptions { ...@@ -208,18 +208,20 @@ impl From<NapiProjectOptions> for ProjectOptions {
impl From<NapiPartialProjectOptions> for PartialProjectOptions { impl From<NapiPartialProjectOptions> for PartialProjectOptions {
fn from(val: NapiPartialProjectOptions) -> Self { fn from(val: NapiPartialProjectOptions) -> Self {
PartialProjectOptions { PartialProjectOptions {
root_path: val.root_path, root_path: val.root_path.map(From::from),
project_path: val.project_path, project_path: val.project_path.map(From::from),
watch: val.watch, watch: val.watch,
next_config: val.next_config, next_config: val.next_config.map(From::from),
js_config: val.js_config, js_config: val.js_config.map(From::from),
env: val env: val.env.map(|env| {
.env env.into_iter()
.map(|env| env.into_iter().map(|var| (var.name, var.value)).collect()), .map(|var| (var.name.into(), var.value.into()))
.collect()
}),
define_env: val.define_env.map(|env| env.into()), define_env: val.define_env.map(|env| env.into()),
dev: val.dev, dev: val.dev,
encryption_key: val.encryption_key, encryption_key: val.encryption_key.map(From::from),
build_id: val.build_id, build_id: val.build_id.map(From::from),
preview_props: val.preview_props.map(|props| props.into()), preview_props: val.preview_props.map(|props| props.into()),
} }
} }
...@@ -231,17 +233,17 @@ impl From<NapiDefineEnv> for DefineEnv { ...@@ -231,17 +233,17 @@ impl From<NapiDefineEnv> for DefineEnv {
client: val client: val
.client .client
.into_iter() .into_iter()
.map(|var| (var.name, var.value)) .map(|var| (var.name.into(), var.value.into()))
.collect(), .collect(),
edge: val edge: val
.edge .edge
.into_iter() .into_iter()
.map(|var| (var.name, var.value)) .map(|var| (var.name.into(), var.value.into()))
.collect(), .collect(),
nodejs: val nodejs: val
.nodejs .nodejs
.into_iter() .into_iter()
.map(|var| (var.name, var.value)) .map(|var| (var.name.into(), var.value.into()))
.collect(), .collect(),
} }
} }
...@@ -357,10 +359,8 @@ pub async fn project_new( ...@@ -357,10 +359,8 @@ pub async fn project_new(
/// - https://github.com/oven-sh/bun/blob/06a9aa80c38b08b3148bfeabe560/src/install/install.zig#L3038 /// - https://github.com/oven-sh/bun/blob/06a9aa80c38b08b3148bfeabe560/src/install/install.zig#L3038
#[tracing::instrument] #[tracing::instrument]
async fn benchmark_file_io(directory: Vc<FileSystemPath>) -> Result<Vc<Completion>> { async fn benchmark_file_io(directory: Vc<FileSystemPath>) -> Result<Vc<Completion>> {
let temp_path = directory.join(format!( let temp_path =
"tmp_file_io_benchmark_{:x}", directory.join(format!("tmp_file_io_benchmark_{:x}", rand::random::<u128>()).into());
rand::random::<u128>()
));
// try to get the real file path on disk so that we can use it with tokio // try to get the real file path on disk so that we can use it with tokio
let fs = Vc::try_resolve_downcast_type::<DiskFileSystem>(directory.fs()) let fs = Vc::try_resolve_downcast_type::<DiskFileSystem>(directory.fs())
...@@ -624,7 +624,11 @@ pub fn project_entrypoints_subscribe( ...@@ -624,7 +624,11 @@ pub fn project_entrypoints_subscribe(
.routes .routes
.iter() .iter()
.map(|(pathname, route)| { .map(|(pathname, route)| {
NapiRoute::from_route(pathname.clone(), route.clone(), &turbo_tasks) NapiRoute::from_route(
pathname.clone().into(),
route.clone(),
&turbo_tasks,
)
}) })
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
middleware: entrypoints middleware: entrypoints
...@@ -670,7 +674,7 @@ struct HmrUpdateWithIssues { ...@@ -670,7 +674,7 @@ struct HmrUpdateWithIssues {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn hmr_update( async fn hmr_update(
project: Vc<Project>, project: Vc<Project>,
identifier: String, identifier: RcStr,
state: Vc<VersionState>, state: Vc<VersionState>,
) -> Result<Vc<HmrUpdateWithIssues>> { ) -> Result<Vc<HmrUpdateWithIssues>> {
let update_operation = project.hmr_update(identifier, state); let update_operation = project.hmr_update(identifier, state);
...@@ -701,7 +705,7 @@ pub fn project_hmr_events( ...@@ -701,7 +705,7 @@ pub fn project_hmr_events(
let outer_identifier = identifier.clone(); let outer_identifier = identifier.clone();
let session = session.clone(); let session = session.clone();
move || { move || {
let identifier = outer_identifier.clone(); let identifier: RcStr = outer_identifier.clone().into();
let session = session.clone(); let session = session.clone();
async move { async move {
let project = project.project().resolve().await?; let project = project.project().resolve().await?;
...@@ -773,7 +777,7 @@ struct HmrIdentifiers { ...@@ -773,7 +777,7 @@ struct HmrIdentifiers {
#[turbo_tasks::value(serialization = "none")] #[turbo_tasks::value(serialization = "none")]
struct HmrIdentifiersWithIssues { struct HmrIdentifiersWithIssues {
identifiers: ReadRef<Vec<String>>, identifiers: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>, issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>, diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
} }
...@@ -967,7 +971,9 @@ pub async fn project_trace_source( ...@@ -967,7 +971,9 @@ pub async fn project_trace_source(
( (
path, path,
match module { match module {
Some(module) => Some(urlencoding::decode(&module.1)?.into_owned()), Some(module) => {
Some(urlencoding::decode(&module.1)?.into_owned().into())
}
None => None, None => None,
}, },
) )
...@@ -992,13 +998,13 @@ pub async fn project_trace_source( ...@@ -992,13 +998,13 @@ pub async fn project_trace_source(
.container .container
.project() .project()
.node_root() .node_root()
.join(chunk_base.to_owned()); .join(chunk_base.into());
let client_path = project let client_path = project
.container .container
.project() .project()
.client_relative_path() .client_relative_path()
.join(chunk_base.to_owned()); .join(chunk_base.into());
let mut map_result = project let mut map_result = project
.container .container
...@@ -1053,7 +1059,7 @@ pub async fn project_trace_source( ...@@ -1053,7 +1059,7 @@ pub async fn project_trace_source(
Ok(Some(StackFrame { Ok(Some(StackFrame {
file: source_file.to_string(), file: source_file.to_string(),
method_name: name, method_name: name.as_ref().map(ToString::to_string),
line, line,
column, column,
is_server: frame.is_server, is_server: frame.is_server,
...@@ -1079,7 +1085,7 @@ pub async fn project_get_source_for_asset( ...@@ -1079,7 +1085,7 @@ pub async fn project_get_source_for_asset(
.project_path() .project_path()
.fs() .fs()
.root() .root()
.join(file_path.to_string()) .join(file_path.clone().into())
.read() .read()
.await?; .await?;
......
...@@ -120,12 +120,12 @@ impl From<&PlainIssue> for NapiIssue { ...@@ -120,12 +120,12 @@ impl From<&PlainIssue> for NapiIssue {
.as_ref() .as_ref()
.map(|styled| serde_json::to_value(StyledStringSerialize::from(styled)).unwrap()), .map(|styled| serde_json::to_value(StyledStringSerialize::from(styled)).unwrap()),
stage: issue.stage.to_string(), stage: issue.stage.to_string(),
file_path: issue.file_path.clone(), file_path: issue.file_path.to_string(),
detail: issue detail: issue
.detail .detail
.as_ref() .as_ref()
.map(|styled| serde_json::to_value(StyledStringSerialize::from(styled)).unwrap()), .map(|styled| serde_json::to_value(StyledStringSerialize::from(styled)).unwrap()),
documentation_link: issue.documentation_link.clone(), documentation_link: issue.documentation_link.to_string(),
severity: issue.severity.as_str().to_string(), severity: issue.severity.as_str().to_string(),
source: issue.source.as_deref().map(|source| source.into()), source: issue.source.as_deref().map(|source| source.into()),
title: serde_json::to_value(StyledStringSerialize::from(&issue.title)).unwrap(), title: serde_json::to_value(StyledStringSerialize::from(&issue.title)).unwrap(),
...@@ -255,9 +255,13 @@ pub struct NapiDiagnostic { ...@@ -255,9 +255,13 @@ pub struct NapiDiagnostic {
impl NapiDiagnostic { impl NapiDiagnostic {
pub fn from(diagnostic: &PlainDiagnostic) -> Self { pub fn from(diagnostic: &PlainDiagnostic) -> Self {
Self { Self {
category: diagnostic.category.clone(), category: diagnostic.category.to_string(),
name: diagnostic.name.clone(), name: diagnostic.name.to_string(),
payload: diagnostic.payload.clone(), payload: diagnostic
.payload
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
} }
} }
} }
......
...@@ -190,10 +190,21 @@ impl FromNapiValue for NapiRouteHas { ...@@ -190,10 +190,21 @@ impl FromNapiValue for NapiRouteHas {
impl From<NapiRouteHas> for RouteHas { impl From<NapiRouteHas> for RouteHas {
fn from(val: NapiRouteHas) -> Self { fn from(val: NapiRouteHas) -> Self {
match val { match val {
NapiRouteHas::Header { key, value } => RouteHas::Header { key, value }, NapiRouteHas::Header { key, value } => RouteHas::Header {
NapiRouteHas::Query { key, value } => RouteHas::Query { key, value }, key: key.into(),
NapiRouteHas::Cookie { key, value } => RouteHas::Cookie { key, value }, value: value.map(From::from),
NapiRouteHas::Host { value } => RouteHas::Host { value }, },
NapiRouteHas::Query { key, value } => RouteHas::Query {
key: key.into(),
value: value.map(From::from),
},
NapiRouteHas::Cookie { key, value } => RouteHas::Cookie {
key: key.into(),
value: value.map(From::from),
},
NapiRouteHas::Host { value } => RouteHas::Host {
value: value.into(),
},
} }
} }
} }
......
...@@ -40,5 +40,5 @@ pub async fn run_turbo_tracing( ...@@ -40,5 +40,5 @@ pub async fn run_turbo_tracing(
}), }),
) )
.await?; .await?;
Ok(files) Ok(files.into_iter().map(|f| f.to_string()).collect())
} }
...@@ -6,7 +6,7 @@ use indexmap::IndexMap; ...@@ -6,7 +6,7 @@ use indexmap::IndexMap;
use tracing::Level; use tracing::Level;
use turbo_tasks::{ use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic, VisitControlFlow}, graph::{GraphTraversal, NonDeterministic, VisitControlFlow},
ReadRef, TryJoinIterExt, Value, ValueToString, Vc, RcStr, ReadRef, TryJoinIterExt, Value, ValueToString, Vc,
}; };
use turbopack_binding::{ use turbopack_binding::{
swc::core::ecma::{ swc::core::ecma::{
...@@ -39,7 +39,7 @@ where ...@@ -39,7 +39,7 @@ where
F: FnMut(Vc<Box<dyn ChunkableModule>>) -> Fu, F: FnMut(Vc<Box<dyn ChunkableModule>>) -> Fu,
Fu: Future<Output = Result<Vc<OutputAssets>>> + Send, Fu: Future<Output = Result<Vc<OutputAssets>>> + Send,
{ {
let mut chunks_hash: HashMap<String, Vc<OutputAssets>> = HashMap::new(); let mut chunks_hash: HashMap<RcStr, Vc<OutputAssets>> = HashMap::new();
let mut dynamic_import_chunks = IndexMap::new(); let mut dynamic_import_chunks = IndexMap::new();
// Iterate over the collected import mappings, and create a chunk for each // Iterate over the collected import mappings, and create a chunk for each
...@@ -62,7 +62,7 @@ where ...@@ -62,7 +62,7 @@ where
// chunks in case if there are same modules being imported in differnt // chunks in case if there are same modules being imported in differnt
// origins. // origins.
let chunk_group = build_chunk(module).await?; let chunk_group = build_chunk(module).await?;
chunks_hash.insert(imported_raw_str.to_string(), chunk_group); chunks_hash.insert(imported_raw_str.clone(), chunk_group);
chunk_group chunk_group
}; };
...@@ -178,22 +178,19 @@ pub(crate) async fn collect_next_dynamic_imports( ...@@ -178,22 +178,19 @@ pub(crate) async fn collect_next_dynamic_imports(
struct NextDynamicVisit; struct NextDynamicVisit;
impl turbo_tasks::graph::Visit<(Vc<Box<dyn Module>>, ReadRef<String>)> for NextDynamicVisit { impl turbo_tasks::graph::Visit<(Vc<Box<dyn Module>>, ReadRef<RcStr>)> for NextDynamicVisit {
type Edge = (Vc<Box<dyn Module>>, ReadRef<String>); type Edge = (Vc<Box<dyn Module>>, ReadRef<RcStr>);
type EdgesIntoIter = Vec<Self::Edge>; type EdgesIntoIter = Vec<Self::Edge>;
type EdgesFuture = impl Future<Output = Result<Self::EdgesIntoIter>>; type EdgesFuture = impl Future<Output = Result<Self::EdgesIntoIter>>;
fn visit( fn visit(
&mut self, &mut self,
edge: Self::Edge, edge: Self::Edge,
) -> VisitControlFlow<(Vc<Box<dyn Module>>, ReadRef<String>)> { ) -> VisitControlFlow<(Vc<Box<dyn Module>>, ReadRef<RcStr>)> {
VisitControlFlow::Continue(edge) VisitControlFlow::Continue(edge)
} }
fn edges( fn edges(&mut self, &(parent, _): &(Vc<Box<dyn Module>>, ReadRef<RcStr>)) -> Self::EdgesFuture {
&mut self,
&(parent, _): &(Vc<Box<dyn Module>>, ReadRef<String>),
) -> Self::EdgesFuture {
async move { async move {
primary_referenced_modules(parent) primary_referenced_modules(parent)
.await? .await?
...@@ -204,7 +201,7 @@ impl turbo_tasks::graph::Visit<(Vc<Box<dyn Module>>, ReadRef<String>)> for NextD ...@@ -204,7 +201,7 @@ impl turbo_tasks::graph::Visit<(Vc<Box<dyn Module>>, ReadRef<String>)> for NextD
} }
} }
fn span(&mut self, (_, name): &(Vc<Box<dyn Module>>, ReadRef<String>)) -> tracing::Span { fn span(&mut self, (_, name): &(Vc<Box<dyn Module>>, ReadRef<RcStr>)) -> tracing::Span {
tracing::span!(Level::INFO, "next/dynamic visit", name = display(name)) tracing::span!(Level::INFO, "next/dynamic visit", name = display(name))
} }
} }
...@@ -244,7 +241,7 @@ async fn build_dynamic_imports_map_for_module( ...@@ -244,7 +241,7 @@ async fn build_dynamic_imports_map_for_module(
client_asset_context, client_asset_context,
server_module.ident().path(), server_module.ident().path(),
)), )),
Request::parse(Value::new(Pattern::Constant(import.to_string()))), Request::parse(Value::new(Pattern::Constant(import.clone()))),
Value::new(EcmaScriptModulesReferenceSubType::DynamicImport), Value::new(EcmaScriptModulesReferenceSubType::DynamicImport),
IssueSeverity::Error.cell(), IssueSeverity::Error.cell(),
None, None,
...@@ -264,7 +261,7 @@ async fn build_dynamic_imports_map_for_module( ...@@ -264,7 +261,7 @@ async fn build_dynamic_imports_map_for_module(
/// import wrapped with dynamic() via CollectImportSourceVisitor. /// import wrapped with dynamic() via CollectImportSourceVisitor.
struct DynamicImportVisitor { struct DynamicImportVisitor {
dynamic_ident: Option<Ident>, dynamic_ident: Option<Ident>,
pub import_sources: Vec<String>, pub import_sources: Vec<RcStr>,
} }
impl DynamicImportVisitor { impl DynamicImportVisitor {
...@@ -309,7 +306,7 @@ impl Visit for DynamicImportVisitor { ...@@ -309,7 +306,7 @@ impl Visit for DynamicImportVisitor {
/// A visitor to collect import source string from import('path/to/module') /// A visitor to collect import source string from import('path/to/module')
struct CollectImportSourceVisitor { struct CollectImportSourceVisitor {
import_source: Option<String>, import_source: Option<RcStr>,
} }
impl CollectImportSourceVisitor { impl CollectImportSourceVisitor {
...@@ -329,7 +326,7 @@ impl Visit for CollectImportSourceVisitor { ...@@ -329,7 +326,7 @@ impl Visit for CollectImportSourceVisitor {
if let Callee::Import(_import) = call_expr.callee { if let Callee::Import(_import) = call_expr.callee {
if let Some(arg) = call_expr.args.first() { if let Some(arg) = call_expr.args.first() {
if let Expr::Lit(Lit::Str(str_)) = &*arg.expr { if let Expr::Lit(Lit::Str(str_)) = &*arg.expr {
self.import_source = Some(str_.value.to_string()); self.import_source = Some(str_.value.as_str().into());
} }
} }
} }
...@@ -339,8 +336,8 @@ impl Visit for CollectImportSourceVisitor { ...@@ -339,8 +336,8 @@ impl Visit for CollectImportSourceVisitor {
} }
} }
pub type DynamicImportedModules = Vec<(String, Vc<Box<dyn Module>>)>; pub type DynamicImportedModules = Vec<(RcStr, Vc<Box<dyn Module>>)>;
pub type DynamicImportedOutputAssets = Vec<(String, Vc<OutputAssets>)>; pub type DynamicImportedOutputAssets = Vec<(RcStr, Vc<OutputAssets>)>;
/// A struct contains mapping for the dynamic imports to construct chunk per /// A struct contains mapping for the dynamic imports to construct chunk per
/// each individual module (Origin Module, Vec<(ImportSourceString, Module)>) /// each individual module (Origin Module, Vec<(ImportSourceString, Module)>)
......
use indexmap::IndexMap; use indexmap::IndexMap;
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use crate::{ use crate::{
project::{Instrumentation, Middleware}, project::{Instrumentation, Middleware},
...@@ -8,7 +8,7 @@ use crate::{ ...@@ -8,7 +8,7 @@ use crate::{
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct Entrypoints { pub struct Entrypoints {
pub routes: IndexMap<String, Route>, pub routes: IndexMap<RcStr, Route>,
pub middleware: Option<Middleware>, pub middleware: Option<Middleware>,
pub instrumentation: Option<Instrumentation>, pub instrumentation: Option<Instrumentation>,
pub pages_document_endpoint: Vc<Box<dyn Endpoint>>, pub pages_document_endpoint: Vc<Box<dyn Endpoint>>,
......
use anyhow::Result; use anyhow::Result;
use next_core::{all_assets_from_entries, next_manifests::NextFontManifest}; use next_core::{all_assets_from_entries, next_manifests::NextFontManifest};
use turbo_tasks::{ValueToString, Vc}; use turbo_tasks::{RcStr, ValueToString, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::{File, FileSystemPath}, turbo::tasks_fs::{File, FileSystemPath},
turbopack::core::{ turbopack::core::{
...@@ -34,13 +34,9 @@ pub(crate) async fn create_font_manifest( ...@@ -34,13 +34,9 @@ pub(crate) async fn create_font_manifest(
.collect(); .collect();
let path = if app_dir { let path = if app_dir {
node_root.join(format!( node_root.join(format!("server/app{manifest_path_prefix}/next-font-manifest.json",).into())
"server/app{manifest_path_prefix}/next-font-manifest.json",
))
} else { } else {
node_root.join(format!( node_root.join(format!("server/pages{manifest_path_prefix}/next-font-manifest.json").into())
"server/pages{manifest_path_prefix}/next-font-manifest.json"
))
}; };
let has_fonts = !font_paths.is_empty(); let has_fonts = !font_paths.is_empty();
...@@ -49,13 +45,14 @@ pub(crate) async fn create_font_manifest( ...@@ -49,13 +45,14 @@ pub(crate) async fn create_font_manifest(
let font_paths = font_paths let font_paths = font_paths
.into_iter() .into_iter()
.filter(|path| path.contains(".p.")) .filter(|path| path.contains(".p."))
.map(RcStr::from)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let next_font_manifest = if !has_fonts { let next_font_manifest = if !has_fonts {
Default::default() Default::default()
} else if app_dir { } else if app_dir {
let dir_str = dir.to_string().await?; let dir_str = dir.to_string().await?;
let page_path = format!("{}{}", dir_str, original_name); let page_path = format!("{}{}", dir_str, original_name).into();
NextFontManifest { NextFontManifest {
app: [(page_path, font_paths)].into_iter().collect(), app: [(page_path, font_paths)].into_iter().collect(),
...@@ -64,7 +61,7 @@ pub(crate) async fn create_font_manifest( ...@@ -64,7 +61,7 @@ pub(crate) async fn create_font_manifest(
} }
} else { } else {
NextFontManifest { NextFontManifest {
pages: [(pathname.to_string(), font_paths)].into_iter().collect(), pages: [(pathname.into(), font_paths)].into_iter().collect(),
pages_using_size_adjust: using_size_adjust, pages_using_size_adjust: using_size_adjust,
..Default::default() ..Default::default()
} }
......
...@@ -73,7 +73,7 @@ impl InstrumentationEndpoint { ...@@ -73,7 +73,7 @@ impl InstrumentationEndpoint {
self.context, self.context,
self.project.project_path(), self.project.project_path(),
userland_module, userland_module,
"instrumentation".to_string(), "instrumentation".into(),
); );
let mut evaluatable_assets = get_server_runtime_entries( let mut evaluatable_assets = get_server_runtime_entries(
...@@ -126,7 +126,7 @@ impl InstrumentationEndpoint { ...@@ -126,7 +126,7 @@ impl InstrumentationEndpoint {
.entry_chunk_group( .entry_chunk_group(
self.project self.project
.node_root() .node_root()
.join("server/instrumentation.js".to_string()), .join("server/instrumentation.js".into()),
module, module,
get_server_runtime_entries( get_server_runtime_entries(
Value::new(ServerContextType::Instrumentation), Value::new(ServerContextType::Instrumentation),
...@@ -161,7 +161,7 @@ impl InstrumentationEndpoint { ...@@ -161,7 +161,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), wasm: wasm_paths_to_bindings(wasm_paths_from_root),
name: "instrumentation".to_string(), name: "instrumentation".into(),
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
...@@ -169,7 +169,7 @@ impl InstrumentationEndpoint { ...@@ -169,7 +169,7 @@ impl InstrumentationEndpoint {
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new( let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
node_root.join("server/instrumentation/middleware-manifest.json".to_string()), node_root.join("server/instrumentation/middleware-manifest.json".into()),
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,
......
...@@ -2,7 +2,7 @@ use std::collections::HashMap; ...@@ -2,7 +2,7 @@ use std::collections::HashMap;
use anyhow::Result; use anyhow::Result;
use next_core::next_manifests::LoadableManifest; use next_core::next_manifests::LoadableManifest;
use turbo_tasks::{TryFlatJoinIterExt, Vc}; use turbo_tasks::{RcStr, TryFlatJoinIterExt, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::{File, FileContent, FileSystemPath}, turbo::tasks_fs::{File, FileContent, FileSystemPath},
turbopack::core::{ turbopack::core::{
...@@ -24,7 +24,7 @@ pub async fn create_react_loadable_manifest( ...@@ -24,7 +24,7 @@ pub async fn create_react_loadable_manifest(
let dynamic_import_entries = &*dynamic_import_entries.await?; let dynamic_import_entries = &*dynamic_import_entries.await?;
let mut output = vec![]; let mut output = vec![];
let mut loadable_manifest: HashMap<String, LoadableManifest> = Default::default(); let mut loadable_manifest: HashMap<RcStr, LoadableManifest> = Default::default();
for (origin, dynamic_imports) in dynamic_import_entries.into_iter() { for (origin, dynamic_imports) in dynamic_import_entries.into_iter() {
let origin_path = &*origin.ident().path().await?; let origin_path = &*origin.ident().path().await?;
...@@ -33,7 +33,7 @@ pub async fn create_react_loadable_manifest( ...@@ -33,7 +33,7 @@ pub async fn create_react_loadable_manifest(
let chunk_output = chunk_output.await?; let chunk_output = chunk_output.await?;
output.extend(chunk_output.iter().copied()); output.extend(chunk_output.iter().copied());
let id = format!("{} -> {}", origin_path, import); let id: RcStr = format!("{} -> {}", origin_path, import).into();
let client_relative_path_value = client_relative_path.await?; let client_relative_path_value = client_relative_path.await?;
let files = chunk_output let files = chunk_output
...@@ -43,7 +43,7 @@ pub async fn create_react_loadable_manifest( ...@@ -43,7 +43,7 @@ pub async fn create_react_loadable_manifest(
async move { async move {
Ok(client_relative_path_value Ok(client_relative_path_value
.get_path_to(&*file.ident().path().await?) .get_path_to(&*file.ident().path().await?)
.map(|path| path.to_string())) .map(|path| path.into()))
} }
}) })
.try_flat_join() .try_flat_join()
......
...@@ -75,7 +75,7 @@ impl MiddlewareEndpoint { ...@@ -75,7 +75,7 @@ impl MiddlewareEndpoint {
self.context, self.context,
self.project.project_path(), self.project.project_path(),
module, module,
"middleware".to_string(), "middleware".into(),
); );
let mut evaluatable_assets = get_server_runtime_entries( let mut evaluatable_assets = get_server_runtime_entries(
...@@ -140,7 +140,7 @@ impl MiddlewareEndpoint { ...@@ -140,7 +140,7 @@ impl MiddlewareEndpoint {
.iter() .iter()
.map(|matcher| match matcher { .map(|matcher| match matcher {
MiddlewareMatcherKind::Str(matchers) => MiddlewareMatcher { MiddlewareMatcherKind::Str(matchers) => MiddlewareMatcher {
original_source: matchers.to_string(), original_source: matchers.as_str().into(),
..Default::default() ..Default::default()
}, },
MiddlewareMatcherKind::Matcher(matcher) => matcher.clone(), MiddlewareMatcherKind::Matcher(matcher) => matcher.clone(),
...@@ -148,8 +148,8 @@ impl MiddlewareEndpoint { ...@@ -148,8 +148,8 @@ impl MiddlewareEndpoint {
.collect() .collect()
} else { } else {
vec![MiddlewareMatcher { vec![MiddlewareMatcher {
regexp: Some("^/.*$".to_string()), regexp: Some("^/.*$".into()),
original_source: "/:path*".to_string(), original_source: "/:path*".into(),
..Default::default() ..Default::default()
}] }]
}; };
...@@ -157,21 +157,21 @@ impl MiddlewareEndpoint { ...@@ -157,21 +157,21 @@ impl MiddlewareEndpoint {
let edge_function_definition = EdgeFunctionDefinition { let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root, files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root), wasm: wasm_paths_to_bindings(wasm_paths_from_root),
name: "middleware".to_string(), name: "middleware".into(),
page: "/".to_string(), page: "/".into(),
regions: None, regions: None,
matchers, matchers,
env: this.project.edge_env().await?.clone_value(), env: this.project.edge_env().await?.clone_value(),
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
middleware: [("/".to_string(), edge_function_definition)] middleware: [("/".into(), edge_function_definition)]
.into_iter() .into_iter()
.collect(), .collect(),
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new( let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
node_root.join("server/middleware/middleware-manifest.json".to_string()), node_root.join("server/middleware/middleware-manifest.json".into()),
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,
......
use anyhow::Result; use anyhow::Result;
use next_core::{all_assets_from_entries, next_manifests::AssetBinding}; use next_core::{all_assets_from_entries, next_manifests::AssetBinding};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TryFlatJoinIterExt, Vc}; use turbo_tasks::{trace::TraceRawVcs, RcStr, TryFlatJoinIterExt, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::FileSystemPath, turbo::tasks_fs::FileSystemPath,
turbopack::core::{ turbopack::core::{
...@@ -62,7 +62,7 @@ pub async fn all_server_paths( ...@@ -62,7 +62,7 @@ pub async fn all_server_paths(
pub async fn all_paths_in_root( pub async fn all_paths_in_root(
assets: Vc<OutputAssets>, assets: Vc<OutputAssets>,
root: Vc<FileSystemPath>, root: Vc<FileSystemPath>,
) -> Result<Vc<Vec<String>>> { ) -> Result<Vc<Vec<RcStr>>> {
let all_assets = &*all_assets_from_entries(assets).await?; let all_assets = &*all_assets_from_entries(assets).await?;
let root = &*root.await?; let root = &*root.await?;
...@@ -75,7 +75,7 @@ pub(crate) async fn get_paths_from_root( ...@@ -75,7 +75,7 @@ pub(crate) async fn get_paths_from_root(
root: &FileSystemPath, root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>], output_assets: &[Vc<Box<dyn OutputAsset>>],
filter: impl FnOnce(&str) -> bool + Copy, filter: impl FnOnce(&str) -> bool + Copy,
) -> Result<Vec<String>> { ) -> Result<Vec<RcStr>> {
output_assets output_assets
.iter() .iter()
.map({ .map({
...@@ -86,7 +86,7 @@ pub(crate) async fn get_paths_from_root( ...@@ -86,7 +86,7 @@ pub(crate) async fn get_paths_from_root(
}; };
Ok(if filter(relative) { Ok(if filter(relative) {
Some(relative.to_string()) Some(relative.into())
} else { } else {
None None
}) })
...@@ -99,21 +99,21 @@ pub(crate) async fn get_paths_from_root( ...@@ -99,21 +99,21 @@ pub(crate) async fn get_paths_from_root(
pub(crate) async fn get_js_paths_from_root( pub(crate) async fn get_js_paths_from_root(
root: &FileSystemPath, root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>], output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> { ) -> Result<Vec<RcStr>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".js")).await get_paths_from_root(root, output_assets, |path| path.ends_with(".js")).await
} }
pub(crate) async fn get_wasm_paths_from_root( pub(crate) async fn get_wasm_paths_from_root(
root: &FileSystemPath, root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>], output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> { ) -> Result<Vec<RcStr>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".wasm")).await get_paths_from_root(root, output_assets, |path| path.ends_with(".wasm")).await
} }
pub(crate) async fn get_font_paths_from_root( pub(crate) async fn get_font_paths_from_root(
root: &FileSystemPath, root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>], output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> { ) -> Result<Vec<RcStr>> {
get_paths_from_root(root, output_assets, |path| { get_paths_from_root(root, output_assets, |path| {
path.ends_with(".woff") path.ends_with(".woff")
|| path.ends_with(".woff2") || path.ends_with(".woff2")
...@@ -142,7 +142,7 @@ fn get_file_stem(path: &str) -> &str { ...@@ -142,7 +142,7 @@ fn get_file_stem(path: &str) -> &str {
} }
} }
pub(crate) fn wasm_paths_to_bindings(paths: Vec<String>) -> Vec<AssetBinding> { pub(crate) fn wasm_paths_to_bindings(paths: Vec<RcStr>) -> Vec<AssetBinding> {
paths paths
.into_iter() .into_iter()
.map(|path| { .map(|path| {
...@@ -155,7 +155,7 @@ pub(crate) fn wasm_paths_to_bindings(paths: Vec<String>) -> Vec<AssetBinding> { ...@@ -155,7 +155,7 @@ pub(crate) fn wasm_paths_to_bindings(paths: Vec<String>) -> Vec<AssetBinding> {
); );
AssetBinding { AssetBinding {
name: format!("wasm_{}", escaped), name: format!("wasm_{}", escaped).into(),
file_path: path, file_path: path,
} }
}) })
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, Completion, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, Completion, RcStr, Vc};
use crate::paths::ServerPath; use crate::paths::ServerPath;
...@@ -84,15 +84,15 @@ pub enum WrittenEndpoint { ...@@ -84,15 +84,15 @@ pub enum WrittenEndpoint {
/// Relative to the root_path /// Relative to the root_path
server_entry_path: String, server_entry_path: String,
server_paths: Vec<ServerPath>, server_paths: Vec<ServerPath>,
client_paths: Vec<String>, client_paths: Vec<RcStr>,
}, },
Edge { Edge {
server_paths: Vec<ServerPath>, server_paths: Vec<ServerPath>,
client_paths: Vec<String>, client_paths: Vec<RcStr>,
}, },
} }
/// The routes as map from pathname to route. (pathname includes the leading /// The routes as map from pathname to route. (pathname includes the leading
/// slash) /// slash)
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct Routes(IndexMap<String, Route>); pub struct Routes(IndexMap<RcStr, Route>);
...@@ -9,7 +9,7 @@ use next_core::{ ...@@ -9,7 +9,7 @@ use next_core::{
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic}, graph::{GraphTraversal, NonDeterministic},
TryFlatJoinIterExt, Value, ValueToString, Vc, RcStr, TryFlatJoinIterExt, Value, ValueToString, Vc,
}; };
use turbopack_binding::{ use turbopack_binding::{
swc::core::{common::comments::Comments, ecma::ast::Program}, swc::core::{common::comments::Comments, ecma::ast::Program},
...@@ -54,7 +54,7 @@ pub(crate) async fn create_server_actions_manifest( ...@@ -54,7 +54,7 @@ pub(crate) async fn create_server_actions_manifest(
) -> Result<(Vc<Box<dyn EvaluatableAsset>>, Vc<Box<dyn OutputAsset>>)> { ) -> Result<(Vc<Box<dyn EvaluatableAsset>>, Vc<Box<dyn OutputAsset>>)> {
let actions = get_actions(rsc_entry, server_reference_modules, asset_context); let actions = get_actions(rsc_entry, server_reference_modules, asset_context);
let loader = let loader =
build_server_actions_loader(project_path, page_name.to_string(), actions, asset_context); build_server_actions_loader(project_path, page_name.into(), actions, asset_context);
let evaluable = Vc::try_resolve_sidecast::<Box<dyn EvaluatableAsset>>(loader) let evaluable = Vc::try_resolve_sidecast::<Box<dyn EvaluatableAsset>>(loader)
.await? .await?
.context("loader module must be evaluatable")?; .context("loader module must be evaluatable")?;
...@@ -76,7 +76,7 @@ pub(crate) async fn create_server_actions_manifest( ...@@ -76,7 +76,7 @@ pub(crate) async fn create_server_actions_manifest(
#[turbo_tasks::function] #[turbo_tasks::function]
async fn build_server_actions_loader( async fn build_server_actions_loader(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
page_name: String, page_name: RcStr,
actions: Vc<AllActions>, actions: Vc<AllActions>,
asset_context: Vc<Box<dyn AssetContext>>, asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> { ) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
...@@ -92,7 +92,7 @@ async fn build_server_actions_loader( ...@@ -92,7 +92,7 @@ async fn build_server_actions_loader(
let index = import_map.len(); let index = import_map.len();
let module_name = import_map let module_name = import_map
.entry(*module) .entry(*module)
.or_insert_with(|| format!("ACTIONS_MODULE{index}")); .or_insert_with(|| format!("ACTIONS_MODULE{index}").into());
writeln!( writeln!(
contents, contents,
" '{hash_id}': (...args) => Promise.resolve(require('{module_name}')).then(mod => \ " '{hash_id}': (...args) => Promise.resolve(require('{module_name}')).then(mod => \
...@@ -101,7 +101,8 @@ async fn build_server_actions_loader( ...@@ -101,7 +101,8 @@ async fn build_server_actions_loader(
} }
write!(contents, "}});")?; write!(contents, "}});")?;
let output_path = project_path.join(format!(".next-internal/server/app{page_name}/actions.js")); let output_path =
project_path.join(format!(".next-internal/server/app{page_name}/actions.js").into());
let file = File::from(contents.build()); let file = File::from(contents.build());
let source = VirtualSource::new(output_path, AssetContent::file(file.into())); let source = VirtualSource::new(output_path, AssetContent::file(file.into()));
let import_map = import_map.into_iter().map(|(k, v)| (v, k)).collect(); let import_map = import_map.into_iter().map(|(k, v)| (v, k)).collect();
...@@ -128,12 +129,11 @@ async fn build_manifest( ...@@ -128,12 +129,11 @@ async fn build_manifest(
page_name: &str, page_name: &str,
runtime: NextRuntime, runtime: NextRuntime,
actions: Vc<AllActions>, actions: Vc<AllActions>,
loader_id: Vc<String>, loader_id: Vc<RcStr>,
) -> Result<Vc<Box<dyn OutputAsset>>> { ) -> Result<Vc<Box<dyn OutputAsset>>> {
let manifest_path_prefix = page_name; let manifest_path_prefix = page_name;
let manifest_path = node_root.join(format!( let manifest_path = node_root
"server/app{manifest_path_prefix}/server-reference-manifest.json", .join(format!("server/app{manifest_path_prefix}/server-reference-manifest.json",).into());
));
let mut manifest = ServerReferenceManifest { let mut manifest = ServerReferenceManifest {
..Default::default() ..Default::default()
}; };
...@@ -163,8 +163,8 @@ async fn build_manifest( ...@@ -163,8 +163,8 @@ async fn build_manifest(
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn action_modifier() -> Vc<String> { fn action_modifier() -> Vc<RcStr> {
Vc::cell("action".to_string()) Vc::cell("action".into())
} }
/// Traverses the entire module graph starting from [Module], looking for magic /// Traverses the entire module graph starting from [Module], looking for magic
......
...@@ -4,7 +4,7 @@ use anyhow::{bail, Result}; ...@@ -4,7 +4,7 @@ use anyhow::{bail, Result};
use next_core::emit_client_assets; use next_core::emit_client_assets;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, Completion, State, TryFlatJoinIterExt, debug::ValueDebugFormat, trace::TraceRawVcs, Completion, RcStr, State, TryFlatJoinIterExt,
TryJoinIterExt, ValueDefault, ValueToString, Vc, TryJoinIterExt, ValueDefault, ValueToString, Vc,
}; };
use turbopack_binding::{ use turbopack_binding::{
...@@ -124,7 +124,7 @@ impl VersionedContentMap { ...@@ -124,7 +124,7 @@ impl VersionedContentMap {
pub async fn get_source_map( pub async fn get_source_map(
self: Vc<Self>, self: Vc<Self>,
path: Vc<FileSystemPath>, path: Vc<FileSystemPath>,
section: Option<String>, section: Option<RcStr>,
) -> Result<Vc<OptionSourceMap>> { ) -> Result<Vc<OptionSourceMap>> {
if let Some(generate_source_map) = if let Some(generate_source_map) =
Vc::try_resolve_sidecast::<Box<dyn GenerateSourceMap>>(self.get_asset(path)).await? Vc::try_resolve_sidecast::<Box<dyn GenerateSourceMap>>(self.get_asset(path)).await?
...@@ -169,7 +169,7 @@ impl VersionedContentMap { ...@@ -169,7 +169,7 @@ impl VersionedContentMap {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn keys_in_path(&self, root: Vc<FileSystemPath>) -> Result<Vc<Vec<String>>> { pub async fn keys_in_path(&self, root: Vc<FileSystemPath>) -> Result<Vc<Vec<RcStr>>> {
let keys = { let keys = {
let map = self.map_path_to_op.get(); let map = self.map_path_to_op.get();
map.keys().copied().collect::<Vec<_>>() map.keys().copied().collect::<Vec<_>>()
...@@ -177,7 +177,7 @@ impl VersionedContentMap { ...@@ -177,7 +177,7 @@ impl VersionedContentMap {
let root = &root.await?; let root = &root.await?;
let keys = keys let keys = keys
.into_iter() .into_iter()
.map(|path| async move { Ok(root.get_path_to(&*path.await?).map(|p| p.to_string())) }) .map(|path| async move { Ok(root.get_path_to(&*path.await?).map(RcStr::from)) })
.try_flat_join() .try_flat_join()
.await?; .await?;
Ok(Vc::cell(keys)) Ok(Vc::cell(keys))
......
...@@ -3,7 +3,7 @@ use std::ops::Deref; ...@@ -3,7 +3,7 @@ use std::ops::Deref;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use turbo_tasks::{trace::TraceRawVcs, TryJoinIterExt, ValueDefault, Vc}; use turbo_tasks::{trace::TraceRawVcs, RcStr, TryJoinIterExt, ValueDefault, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_binding::{ use turbopack_binding::{
swc::core::{ swc::core::{
...@@ -71,7 +71,7 @@ pub struct NextSegmentConfig { ...@@ -71,7 +71,7 @@ pub struct NextSegmentConfig {
pub revalidate: Option<NextRevalidate>, pub revalidate: Option<NextRevalidate>,
pub fetch_cache: Option<NextSegmentFetchCache>, pub fetch_cache: Option<NextSegmentFetchCache>,
pub runtime: Option<NextRuntime>, pub runtime: Option<NextRuntime>,
pub preferred_region: Option<Vec<String>>, pub preferred_region: Option<Vec<RcStr>>,
pub experimental_ppr: Option<bool>, pub experimental_ppr: Option<bool>,
} }
...@@ -178,7 +178,7 @@ impl Issue for NextSegmentConfigParsingIssue { ...@@ -178,7 +178,7 @@ impl Issue for NextSegmentConfigParsingIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> { fn title(&self) -> Vc<StyledString> {
StyledString::Text("Unable to parse config export in source file".to_string()).cell() StyledString::Text("Unable to parse config export in source file".into()).cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -197,7 +197,7 @@ impl Issue for NextSegmentConfigParsingIssue { ...@@ -197,7 +197,7 @@ impl Issue for NextSegmentConfigParsingIssue {
StyledString::Text( StyledString::Text(
"The exported configuration object in a source file need to have a very specific \ "The exported configuration object in a source file need to have a very specific \
format from which some properties can be statically parsed at compiled-time." format from which some properties can be statically parsed at compiled-time."
.to_string(), .into(),
) )
.cell(), .cell(),
)) ))
...@@ -209,10 +209,10 @@ impl Issue for NextSegmentConfigParsingIssue { ...@@ -209,10 +209,10 @@ impl Issue for NextSegmentConfigParsingIssue {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn documentation_link(&self) -> Vc<String> { fn documentation_link(&self) -> Vc<RcStr> {
Vc::cell( Vc::cell(
"https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config" "https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config"
.to_string(), .into(),
) )
} }
...@@ -312,7 +312,7 @@ fn parse_config_value( ...@@ -312,7 +312,7 @@ fn parse_config_value(
let (explainer, hints) = value.explain(2, 0); let (explainer, hints) = value.explain(2, 0);
NextSegmentConfigParsingIssue { NextSegmentConfigParsingIssue {
ident: source.ident(), ident: source.ident(),
detail: StyledString::Text(format!("{detail} Got {explainer}.{hints}")).cell(), detail: StyledString::Text(format!("{detail} Got {explainer}.{hints}").into()).cell(),
source: issue_source(source, span), source: issue_source(source, span),
} }
.cell() .cell()
...@@ -402,14 +402,14 @@ fn parse_config_value( ...@@ -402,14 +402,14 @@ fn parse_config_value(
let preferred_region = match value { let preferred_region = match value {
// Single value is turned into a single-element Vec. // Single value is turned into a single-element Vec.
JsValue::Constant(ConstantValue::Str(str)) => vec![str.to_string()], JsValue::Constant(ConstantValue::Str(str)) => vec![str.to_string().into()],
// Array of strings is turned into a Vec. If one of the values in not a String it // Array of strings is turned into a Vec. If one of the values in not a String it
// will error. // will error.
JsValue::Array { items, .. } => { JsValue::Array { items, .. } => {
let mut regions = Vec::new(); let mut regions = Vec::new();
for item in items { for item in items {
if let JsValue::Constant(ConstantValue::Str(str)) = item { if let JsValue::Constant(ConstantValue::Str(str)) = item {
regions.push(str.to_string()); regions.push(str.to_string().into());
} else { } else {
invalid_config( invalid_config(
"Values of the `preferredRegion` array need to static strings", "Values of the `preferredRegion` array need to static strings",
......
...@@ -80,7 +80,7 @@ pub async fn bootstrap( ...@@ -80,7 +80,7 @@ pub async fn bootstrap(
let config_asset = context let config_asset = context
.process( .process(
Vc::upcast(VirtualSource::new( Vc::upcast(VirtualSource::new(
asset.ident().path().join("bootstrap-config.ts".to_string()), asset.ident().path().join("bootstrap-config.ts".into()),
AssetContent::file( AssetContent::file(
File::from( File::from(
config config
...@@ -97,8 +97,8 @@ pub async fn bootstrap( ...@@ -97,8 +97,8 @@ pub async fn bootstrap(
.module(); .module();
let mut inner_assets = inner_assets.await?.clone_value(); let mut inner_assets = inner_assets.await?.clone_value();
inner_assets.insert("ENTRY".to_string(), asset); inner_assets.insert("ENTRY".into(), asset);
inner_assets.insert("BOOTSTRAP_CONFIG".to_string(), config_asset); inner_assets.insert("BOOTSTRAP_CONFIG".into(), config_asset);
let asset = context let asset = context
.process( .process(
......
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::{FileContent, FileSystem, FileSystemPath}, turbo::tasks_fs::{FileContent, FileSystem, FileSystemPath},
turbopack::core::{file_source::FileSource, source::Source}, turbopack::core::{file_source::FileSource, source::Source},
...@@ -13,16 +13,16 @@ pub(crate) fn next_js_fs() -> Vc<Box<dyn FileSystem>> { ...@@ -13,16 +13,16 @@ pub(crate) fn next_js_fs() -> Vc<Box<dyn FileSystem>> {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) fn next_js_file(path: String) -> Vc<FileContent> { pub(crate) fn next_js_file(path: RcStr) -> Vc<FileContent> {
next_js_fs().root().join(path).read() next_js_fs().root().join(path).read()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) fn next_js_file_path(path: String) -> Vc<FileSystemPath> { pub(crate) fn next_js_file_path(path: RcStr) -> Vc<FileSystemPath> {
next_js_fs().root().join(path) next_js_fs().root().join(path)
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) fn next_asset(path: String) -> Vc<Box<dyn Source>> { pub(crate) fn next_asset(path: RcStr) -> Vc<Box<dyn Source>> {
Vc::upcast(FileSource::new(next_js_file_path(path))) Vc::upcast(FileSource::new(next_js_file_path(path)))
} }
use anyhow::Result; use anyhow::Result;
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn instrumentation_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec<String>>> { pub async fn instrumentation_files(page_extensions: Vc<Vec<RcStr>>) -> Result<Vc<Vec<RcStr>>> {
let extensions = page_extensions.await?; let extensions = page_extensions.await?;
let files = ["instrumentation.", "src/instrumentation."] let files = ["instrumentation.", "src/instrumentation."]
.into_iter() .into_iter()
...@@ -10,6 +10,7 @@ pub async fn instrumentation_files(page_extensions: Vc<Vec<String>>) -> Result<V ...@@ -10,6 +10,7 @@ pub async fn instrumentation_files(page_extensions: Vc<Vec<String>>) -> Result<V
extensions extensions
.iter() .iter()
.map(move |ext| String::from(f) + ext.as_str()) .map(move |ext| String::from(f) + ext.as_str())
.map(RcStr::from)
}) })
.collect(); .collect();
Ok(Vc::cell(files)) Ok(Vc::cell(files))
......
...@@ -7,7 +7,7 @@ use anyhow::Result; ...@@ -7,7 +7,7 @@ use anyhow::Result;
use async_recursion::async_recursion; use async_recursion::async_recursion;
use indexmap::IndexMap; use indexmap::IndexMap;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{Value, ValueToString, Vc}; use turbo_tasks::{RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{ core::{
...@@ -33,15 +33,15 @@ use crate::{ ...@@ -33,15 +33,15 @@ use crate::{
}; };
pub struct LoaderTreeBuilder { pub struct LoaderTreeBuilder {
inner_assets: IndexMap<String, Vc<Box<dyn Module>>>, inner_assets: IndexMap<RcStr, Vc<Box<dyn Module>>>,
counter: usize, counter: usize,
imports: Vec<String>, imports: Vec<RcStr>,
loader_tree_code: String, loader_tree_code: String,
context: Vc<ModuleAssetContext>, context: Vc<ModuleAssetContext>,
server_component_transition: Vc<Box<dyn Transition>>, server_component_transition: Vc<Box<dyn Transition>>,
pages: Vec<Vc<FileSystemPath>>, pages: Vec<Vc<FileSystemPath>>,
/// next.config.js' basePath option to construct og metadata. /// next.config.js' basePath option to construct og metadata.
base_path: Option<String>, base_path: Option<RcStr>,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
...@@ -73,7 +73,7 @@ impl LoaderTreeBuilder { ...@@ -73,7 +73,7 @@ impl LoaderTreeBuilder {
fn new( fn new(
context: Vc<ModuleAssetContext>, context: Vc<ModuleAssetContext>,
server_component_transition: Vc<Box<dyn Transition>>, server_component_transition: Vc<Box<dyn Transition>>,
base_path: Option<String>, base_path: Option<RcStr>,
) -> Self { ) -> Self {
LoaderTreeBuilder { LoaderTreeBuilder {
inner_assets: IndexMap::new(), inner_assets: IndexMap::new(),
...@@ -123,15 +123,19 @@ impl LoaderTreeBuilder { ...@@ -123,15 +123,19 @@ impl LoaderTreeBuilder {
path = StringifyJs(&module.ident().path().to_string().await?) path = StringifyJs(&module.ident().path().to_string().await?)
)?; )?;
self.imports.push(formatdoc!( self.imports.push(
r#" formatdoc!(
r#"
import {} from "COMPONENT_{}"; import {} from "COMPONENT_{}";
"#, "#,
identifier, identifier,
i i
)); )
.into(),
);
self.inner_assets.insert(format!("COMPONENT_{i}"), module); self.inner_assets
.insert(format!("COMPONENT_{i}").into(), module);
} }
Ok(()) Ok(())
} }
...@@ -240,12 +244,12 @@ impl LoaderTreeBuilder { ...@@ -240,12 +244,12 @@ impl LoaderTreeBuilder {
let inner_module_id = format!("METADATA_{i}"); let inner_module_id = format!("METADATA_{i}");
self.imports self.imports
.push(format!("import {identifier} from \"{inner_module_id}\";")); .push(format!("import {identifier} from \"{inner_module_id}\";").into());
let source = dynamic_image_metadata_source( let source = dynamic_image_metadata_source(
Vc::upcast(self.context), Vc::upcast(self.context),
*path, *path,
name.to_string(), name.into(),
app_page.clone(), app_page.clone(),
); );
...@@ -258,7 +262,7 @@ impl LoaderTreeBuilder { ...@@ -258,7 +262,7 @@ impl LoaderTreeBuilder {
)), )),
) )
.module(); .module();
self.inner_assets.insert(inner_module_id, module); self.inner_assets.insert(inner_module_id.into(), module);
let s = " "; let s = " ";
writeln!(self.loader_tree_code, "{s}{identifier},")?; writeln!(self.loader_tree_code, "{s}{identifier},")?;
...@@ -279,18 +283,18 @@ impl LoaderTreeBuilder { ...@@ -279,18 +283,18 @@ impl LoaderTreeBuilder {
let identifier = magic_identifier::mangle(&format!("{name} #{i}")); let identifier = magic_identifier::mangle(&format!("{name} #{i}"));
let inner_module_id = format!("METADATA_{i}"); let inner_module_id = format!("METADATA_{i}");
let helper_import = "import { fillMetadataSegment } from \ let helper_import: RcStr = "import { fillMetadataSegment } from \
\"next/dist/lib/metadata/get-metadata-route\"" \"next/dist/lib/metadata/get-metadata-route\""
.to_string(); .into();
if !self.imports.contains(&helper_import) { if !self.imports.contains(&helper_import) {
self.imports.push(helper_import); self.imports.push(helper_import);
} }
self.imports self.imports
.push(format!("import {identifier} from \"{inner_module_id}\";")); .push(format!("import {identifier} from \"{inner_module_id}\";").into());
self.inner_assets.insert( self.inner_assets.insert(
inner_module_id, inner_module_id.into(),
Vc::upcast(StructuredImageModuleType::create_module( Vc::upcast(StructuredImageModuleType::create_module(
Vc::upcast(FileSource::new(path)), Vc::upcast(FileSource::new(path)),
BlurPlaceholderMode::None, BlurPlaceholderMode::None,
...@@ -332,7 +336,7 @@ impl LoaderTreeBuilder { ...@@ -332,7 +336,7 @@ impl LoaderTreeBuilder {
let identifier = magic_identifier::mangle(&format!("{name} alt text #{i}")); let identifier = magic_identifier::mangle(&format!("{name} alt text #{i}"));
let inner_module_id = format!("METADATA_ALT_{i}"); let inner_module_id = format!("METADATA_ALT_{i}");
self.imports self.imports
.push(format!("import {identifier} from \"{inner_module_id}\";")); .push(format!("import {identifier} from \"{inner_module_id}\";").into());
let module = self let module = self
.context .context
.process( .process(
...@@ -342,7 +346,7 @@ impl LoaderTreeBuilder { ...@@ -342,7 +346,7 @@ impl LoaderTreeBuilder {
Value::new(ReferenceType::Internal(InnerAssets::empty())), Value::new(ReferenceType::Internal(InnerAssets::empty())),
) )
.module(); .module();
self.inner_assets.insert(inner_module_id, module); self.inner_assets.insert(inner_module_id.into(), module);
writeln!(self.loader_tree_code, "{s} alt: {identifier},")?; writeln!(self.loader_tree_code, "{s} alt: {identifier},")?;
} }
...@@ -425,7 +429,7 @@ impl LoaderTreeBuilder { ...@@ -425,7 +429,7 @@ impl LoaderTreeBuilder {
self.walk_tree(loader_tree, true).await?; self.walk_tree(loader_tree, true).await?;
Ok(LoaderTreeModule { Ok(LoaderTreeModule {
imports: self.imports, imports: self.imports,
loader_tree_code: self.loader_tree_code, loader_tree_code: self.loader_tree_code.into(),
inner_assets: self.inner_assets, inner_assets: self.inner_assets,
pages: self.pages, pages: self.pages,
}) })
...@@ -433,9 +437,9 @@ impl LoaderTreeBuilder { ...@@ -433,9 +437,9 @@ impl LoaderTreeBuilder {
} }
pub struct LoaderTreeModule { pub struct LoaderTreeModule {
pub imports: Vec<String>, pub imports: Vec<RcStr>,
pub loader_tree_code: String, pub loader_tree_code: RcStr,
pub inner_assets: IndexMap<String, Vc<Box<dyn Module>>>, pub inner_assets: IndexMap<RcStr, Vc<Box<dyn Module>>>,
pub pages: Vec<Vc<FileSystemPath>>, pub pages: Vec<Vc<FileSystemPath>>,
} }
...@@ -444,7 +448,7 @@ impl LoaderTreeModule { ...@@ -444,7 +448,7 @@ impl LoaderTreeModule {
loader_tree: Vc<LoaderTree>, loader_tree: Vc<LoaderTree>,
context: Vc<ModuleAssetContext>, context: Vc<ModuleAssetContext>,
server_component_transition: Vc<Box<dyn Transition>>, server_component_transition: Vc<Box<dyn Transition>>,
base_path: Option<String>, base_path: Option<RcStr>,
) -> Result<Self> { ) -> Result<Self> {
LoaderTreeBuilder::new(context, server_component_transition, base_path) LoaderTreeBuilder::new(context, server_component_transition, base_path)
.build(loader_tree) .build(loader_tree)
......
use anyhow::Result; use anyhow::Result;
use indexmap::indexmap; use indexmap::indexmap;
use turbo_tasks::{Value, Vc}; use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_binding::turbopack::core::{ use turbopack_binding::turbopack::core::{
context::AssetContext, module::Module, reference_type::ReferenceType, context::AssetContext, module::Module, reference_type::ReferenceType,
...@@ -9,7 +9,7 @@ use turbopack_binding::turbopack::core::{ ...@@ -9,7 +9,7 @@ use turbopack_binding::turbopack::core::{
use crate::util::load_next_js_template; use crate::util::load_next_js_template;
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn middleware_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec<String>>> { pub async fn middleware_files(page_extensions: Vc<Vec<RcStr>>) -> Result<Vc<Vec<RcStr>>> {
let extensions = page_extensions.await?; let extensions = page_extensions.await?;
let files = ["middleware.", "src/middleware."] let files = ["middleware.", "src/middleware."]
.into_iter() .into_iter()
...@@ -17,6 +17,7 @@ pub async fn middleware_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec ...@@ -17,6 +17,7 @@ pub async fn middleware_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec
extensions extensions
.iter() .iter()
.map(move |ext| String::from(f) + ext.as_str()) .map(move |ext| String::from(f) + ext.as_str())
.map(RcStr::from)
}) })
.collect(); .collect();
Ok(Vc::cell(files)) Ok(Vc::cell(files))
...@@ -35,8 +36,8 @@ pub async fn get_middleware_module( ...@@ -35,8 +36,8 @@ pub async fn get_middleware_module(
"middleware.js", "middleware.js",
project_root, project_root,
indexmap! { indexmap! {
"VAR_USERLAND" => INNER.to_string(), "VAR_USERLAND" => INNER.into(),
"VAR_DEFINITION_PAGE" => "/middleware".to_string(), "VAR_DEFINITION_PAGE" => "/middleware".into(),
}, },
indexmap! {}, indexmap! {},
indexmap! {}, indexmap! {},
...@@ -44,7 +45,7 @@ pub async fn get_middleware_module( ...@@ -44,7 +45,7 @@ pub async fn get_middleware_module(
.await?; .await?;
let inner_assets = indexmap! { let inner_assets = indexmap! {
INNER.to_string() => userland_module INNER.into() => userland_module
}; };
let module = context let module = context
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use indexmap::IndexMap;
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks::{RcStr, TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc};
use turbopack_binding::turbopack::core::{ use turbopack_binding::turbopack::core::{
chunk::{availability_info::AvailabilityInfo, ChunkingContext, ChunkingContextExt}, chunk::{availability_info::AvailabilityInfo, ChunkingContext, ChunkingContextExt},
module::Module, module::Module,
...@@ -18,13 +18,13 @@ use crate::{ ...@@ -18,13 +18,13 @@ use crate::{
}; };
#[turbo_tasks::function] #[turbo_tasks::function]
fn client_modules_modifier() -> Vc<String> { fn client_modules_modifier() -> Vc<RcStr> {
Vc::cell("client modules".to_string()) Vc::cell("client modules".into())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn client_modules_ssr_modifier() -> Vc<String> { fn client_modules_ssr_modifier() -> Vc<RcStr> {
Vc::cell("client modules ssr".to_string()) Vc::cell("client modules ssr".into())
} }
#[turbo_tasks::value] #[turbo_tasks::value]
......
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::ecmascript::chunk::EcmascriptChunkPlaceable; use turbopack_binding::turbopack::ecmascript::chunk::EcmascriptChunkPlaceable;
use crate::app_segment_config::NextSegmentConfig; use crate::app_segment_config::NextSegmentConfig;
...@@ -7,10 +7,10 @@ use crate::app_segment_config::NextSegmentConfig; ...@@ -7,10 +7,10 @@ use crate::app_segment_config::NextSegmentConfig;
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct AppEntry { pub struct AppEntry {
/// The pathname of the route or page. /// The pathname of the route or page.
pub pathname: String, pub pathname: RcStr,
/// The original Next.js name of the route or page. This is used instead of /// The original Next.js name of the route or page. This is used instead of
/// the pathname to refer to this entry. /// the pathname to refer to this entry.
pub original_name: String, pub original_name: RcStr,
/// The RSC module asset for the route or page. /// The RSC module asset for the route or page.
pub rsc_entry: Vc<Box<dyn EcmascriptChunkPlaceable>>, pub rsc_entry: Vc<Box<dyn EcmascriptChunkPlaceable>>,
/// The source code config for this entry. /// The source code config for this entry.
......
...@@ -2,7 +2,7 @@ use std::io::Write; ...@@ -2,7 +2,7 @@ use std::io::Write;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::indexmap; use indexmap::indexmap;
use turbo_tasks::{TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueToString, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::{rope::RopeBuilder, File, FileSystemPath}, turbo::tasks_fs::{rope::RopeBuilder, File, FileSystemPath},
turbopack::{ turbopack::{
...@@ -71,25 +71,25 @@ pub async fn get_app_page_entry( ...@@ -71,25 +71,25 @@ pub async fn get_app_page_entry(
let pages = pages.iter().map(|page| page.to_string()).try_join().await?; let pages = pages.iter().map(|page| page.to_string()).try_join().await?;
let original_name = page.to_string(); let original_name: RcStr = page.to_string().into();
let pathname = AppPath::from(page.clone()).to_string(); let pathname: RcStr = AppPath::from(page.clone()).to_string().into();
// Load the file from the next.js codebase. // Load the file from the next.js codebase.
let source = load_next_js_template( let source = load_next_js_template(
"app-page.js", "app-page.js",
project_root, project_root,
indexmap! { indexmap! {
"VAR_DEFINITION_PAGE" => page.to_string(), "VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(), "VAR_DEFINITION_PATHNAME" => pathname.clone(),
"VAR_ORIGINAL_PATHNAME" => original_name.clone(), "VAR_ORIGINAL_PATHNAME" => original_name.clone(),
// TODO(alexkirsz) Support custom global error. // TODO(alexkirsz) Support custom global error.
"VAR_MODULE_GLOBAL_ERROR" => "next/dist/client/components/error-boundary".to_string(), "VAR_MODULE_GLOBAL_ERROR" => "next/dist/client/components/error-boundary".into(),
}, },
indexmap! { indexmap! {
"tree" => loader_tree_code, "tree" => loader_tree_code,
"pages" => StringifyJs(&pages).to_string(), "pages" => StringifyJs(&pages).to_string().into(),
"__next_app_require__" => "__turbopack_require__".to_string(), "__next_app_require__" => "__turbopack_require__".into(),
"__next_app_load_chunk__" => " __turbopack_load__".to_string(), "__next_app_load_chunk__" => " __turbopack_load__".into(),
}, },
indexmap! {}, indexmap! {},
) )
...@@ -103,7 +103,9 @@ pub async fn get_app_page_entry( ...@@ -103,7 +103,9 @@ pub async fn get_app_page_entry(
let file = File::from(result.build()); let file = File::from(result.build());
let source = VirtualSource::new_with_ident( let source = VirtualSource::new_with_ident(
source.ident().with_query(Vc::cell(query.to_string())), source
.ident()
.with_query(Vc::cell(query.to_string().into())),
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
...@@ -171,15 +173,15 @@ async fn wrap_edge_page( ...@@ -171,15 +173,15 @@ async fn wrap_edge_page(
"edge-ssr-app.js", "edge-ssr-app.js",
project_root, project_root,
indexmap! { indexmap! {
"VAR_USERLAND" => INNER.to_string(), "VAR_USERLAND" => INNER.into(),
"VAR_PAGE" => page.to_string(), "VAR_PAGE" => page.to_string().into(),
}, },
indexmap! { indexmap! {
"sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string(), "sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string().into(),
"nextConfig" => serde_json::to_string(next_config)?, "nextConfig" => serde_json::to_string(next_config)?.into(),
"isServerComponent" => serde_json::Value::Bool(is_server_component).to_string(), "isServerComponent" => serde_json::Value::Bool(is_server_component).to_string().into(),
"dev" => serde_json::Value::Bool(dev).to_string(), "dev" => serde_json::Value::Bool(dev).to_string().into(),
"serverActions" => serde_json::to_string(&server_actions)? "serverActions" => serde_json::to_string(&server_actions)?.into(),
}, },
indexmap! { indexmap! {
"incrementalCacheHandler" => None, "incrementalCacheHandler" => None,
...@@ -188,7 +190,7 @@ async fn wrap_edge_page( ...@@ -188,7 +190,7 @@ async fn wrap_edge_page(
.await?; .await?;
let inner_assets = indexmap! { let inner_assets = indexmap! {
INNER.to_string() => entry INNER.into() => entry
}; };
let wrapped = context let wrapped = context
...@@ -202,6 +204,6 @@ async fn wrap_edge_page( ...@@ -202,6 +204,6 @@ async fn wrap_edge_page(
context, context,
project_root, project_root,
wrapped, wrapped,
AppPath::from(page).to_string(), AppPath::from(page).to_string().into(),
)) ))
} }
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::indexmap; use indexmap::indexmap;
use turbo_tasks::{Value, ValueToString, Vc}; use turbo_tasks::{RcStr, Value, ValueToString, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::FileSystemPath, turbo::tasks_fs::FileSystemPath,
turbopack::{ turbopack::{
...@@ -57,14 +57,14 @@ pub async fn get_app_route_entry( ...@@ -57,14 +57,14 @@ pub async fn get_app_route_entry(
nodejs_context nodejs_context
}; };
let original_name = page.to_string(); let original_name: RcStr = page.to_string().into();
let pathname = AppPath::from(page.clone()).to_string(); let pathname: RcStr = AppPath::from(page.clone()).to_string().into();
let path = source.ident().path(); let path = source.ident().path();
const INNER: &str = "INNER_APP_ROUTE"; const INNER: &str = "INNER_APP_ROUTE";
let output_type = next_config let output_type: RcStr = next_config
.await? .await?
.output .output
.as_ref() .as_ref()
...@@ -72,21 +72,22 @@ pub async fn get_app_route_entry( ...@@ -72,21 +72,22 @@ pub async fn get_app_route_entry(
OutputType::Standalone => "\"standalone\"".to_string(), OutputType::Standalone => "\"standalone\"".to_string(),
OutputType::Export => "\"export\"".to_string(), OutputType::Export => "\"export\"".to_string(),
}) })
.unwrap_or_else(|| "\"\"".to_string()); .map(RcStr::from)
.unwrap_or_else(|| "\"\"".into());
// Load the file from the next.js codebase. // Load the file from the next.js codebase.
let virtual_source = load_next_js_template( let virtual_source = load_next_js_template(
"app-route.js", "app-route.js",
project_root, project_root,
indexmap! { indexmap! {
"VAR_DEFINITION_PAGE" => page.to_string(), "VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(), "VAR_DEFINITION_PATHNAME" => pathname.clone(),
"VAR_DEFINITION_FILENAME" => path.file_stem().await?.as_ref().unwrap().clone(), "VAR_DEFINITION_FILENAME" => path.file_stem().await?.as_ref().unwrap().as_str().into(),
// TODO(alexkirsz) Is this necessary? // TODO(alexkirsz) Is this necessary?
"VAR_DEFINITION_BUNDLE_PATH" => "".to_string(), "VAR_DEFINITION_BUNDLE_PATH" => "".into(),
"VAR_ORIGINAL_PATHNAME" => original_name.clone(), "VAR_ORIGINAL_PATHNAME" => original_name.clone(),
"VAR_RESOLVED_PAGE_PATH" => path.to_string().await?.clone_value(), "VAR_RESOLVED_PAGE_PATH" => path.to_string().await?.clone_value(),
"VAR_USERLAND" => INNER.to_string(), "VAR_USERLAND" => INNER.into(),
}, },
indexmap! { indexmap! {
"nextConfigOutput" => output_type "nextConfigOutput" => output_type
...@@ -103,7 +104,7 @@ pub async fn get_app_route_entry( ...@@ -103,7 +104,7 @@ pub async fn get_app_route_entry(
.module(); .module();
let inner_assets = indexmap! { let inner_assets = indexmap! {
INNER.to_string() => userland_module INNER.into() => userland_module
}; };
let mut rsc_entry = context let mut rsc_entry = context
...@@ -142,7 +143,7 @@ async fn wrap_edge_route( ...@@ -142,7 +143,7 @@ async fn wrap_edge_route(
context: Vc<Box<dyn AssetContext>>, context: Vc<Box<dyn AssetContext>>,
project_root: Vc<FileSystemPath>, project_root: Vc<FileSystemPath>,
entry: Vc<Box<dyn Module>>, entry: Vc<Box<dyn Module>>,
pathname: String, pathname: RcStr,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_ROUTE_ENTRY"; const INNER: &str = "INNER_ROUTE_ENTRY";
...@@ -150,7 +151,7 @@ async fn wrap_edge_route( ...@@ -150,7 +151,7 @@ async fn wrap_edge_route(
"edge-app-route.js", "edge-app-route.js",
project_root, project_root,
indexmap! { indexmap! {
"VAR_USERLAND" => INNER.to_string(), "VAR_USERLAND" => INNER.into(),
}, },
indexmap! {}, indexmap! {},
indexmap! {}, indexmap! {},
...@@ -158,7 +159,7 @@ async fn wrap_edge_route( ...@@ -158,7 +159,7 @@ async fn wrap_edge_route(
.await?; .await?;
let inner_assets = indexmap! { let inner_assets = indexmap! {
INNER.to_string() => entry INNER.into() => entry
}; };
let wrapped = context let wrapped = context
......
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{RcStr, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::glob::Glob; use turbo_tasks_fs::glob::Glob;
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{ core::{
...@@ -159,8 +159,8 @@ impl IncludedModuleReference { ...@@ -159,8 +159,8 @@ impl IncludedModuleReference {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ValueToString for IncludedModuleReference { impl ValueToString for IncludedModuleReference {
#[turbo_tasks::function] #[turbo_tasks::function]
fn to_string(&self) -> Vc<String> { fn to_string(&self) -> Vc<RcStr> {
Vc::cell("module".to_string()) Vc::cell("module".into())
} }
} }
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{ValueToString, Vc}; use turbo_tasks::{RcStr, ValueToString, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath}; use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_hash::hash_xxh3_hash64, turbo::tasks_hash::hash_xxh3_hash64,
...@@ -46,7 +46,7 @@ async fn hash_file_content(path: Vc<FileSystemPath>) -> Result<u64> { ...@@ -46,7 +46,7 @@ async fn hash_file_content(path: Vc<FileSystemPath>) -> Result<u64> {
pub async fn dynamic_image_metadata_source( pub async fn dynamic_image_metadata_source(
asset_context: Vc<Box<dyn AssetContext>>, asset_context: Vc<Box<dyn AssetContext>>,
path: Vc<FileSystemPath>, path: Vc<FileSystemPath>,
ty: String, ty: RcStr,
page: AppPage, page: AppPage,
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem().await?; let stem = path.file_stem().await?;
...@@ -126,7 +126,7 @@ pub async fn dynamic_image_metadata_source( ...@@ -126,7 +126,7 @@ pub async fn dynamic_image_metadata_source(
let file = File::from(code); let file = File::from(code);
let source = VirtualSource::new( let source = VirtualSource::new(
path.parent().join(format!("{stem}--metadata.js")), path.parent().join(format!("{stem}--metadata.js").into()),
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
...@@ -134,7 +134,7 @@ pub async fn dynamic_image_metadata_source( ...@@ -134,7 +134,7 @@ pub async fn dynamic_image_metadata_source(
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn collect_direct_exports(module: Vc<Box<dyn Module>>) -> Result<Vc<Vec<String>>> { async fn collect_direct_exports(module: Vc<Box<dyn Module>>) -> Result<Vc<Vec<RcStr>>> {
let Some(ecmascript_asset) = let Some(ecmascript_asset) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module).await? Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module).await?
else { else {
......
...@@ -2,7 +2,7 @@ use std::{collections::HashMap, ops::Deref}; ...@@ -2,7 +2,7 @@ use std::{collections::HashMap, ops::Deref};
use anyhow::Result; use anyhow::Result;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use crate::next_app::{AppPage, PageSegment, PageType}; use crate::next_app::{AppPage, PageSegment, PageType};
...@@ -50,7 +50,7 @@ fn match_numbered_metadata(stem: &str) -> Option<(&str, &str)> { ...@@ -50,7 +50,7 @@ fn match_numbered_metadata(stem: &str) -> Option<(&str, &str)> {
fn match_metadata_file<'a>( fn match_metadata_file<'a>(
filename: &'a str, filename: &'a str,
page_extensions: &[String], page_extensions: &[RcStr],
metadata: &HashMap<&str, &[&str]>, metadata: &HashMap<&str, &[&str]>,
) -> Option<MetadataFileMatch<'a>> { ) -> Option<MetadataFileMatch<'a>> {
let (stem, ext) = filename.split_once('.')?; let (stem, ext) = filename.split_once('.')?;
...@@ -115,7 +115,7 @@ pub(crate) async fn get_content_type(path: Vc<FileSystemPath>) -> Result<String> ...@@ -115,7 +115,7 @@ pub(crate) async fn get_content_type(path: Vc<FileSystemPath>) -> Result<String>
pub fn match_local_metadata_file<'a>( pub fn match_local_metadata_file<'a>(
basename: &'a str, basename: &'a str,
page_extensions: &[String], page_extensions: &[RcStr],
) -> Option<MetadataFileMatch<'a>> { ) -> Option<MetadataFileMatch<'a>> {
match_metadata_file(basename, page_extensions, STATIC_LOCAL_METADATA.deref()) match_metadata_file(basename, page_extensions, STATIC_LOCAL_METADATA.deref())
} }
...@@ -127,7 +127,7 @@ pub struct GlobalMetadataFileMatch<'a> { ...@@ -127,7 +127,7 @@ pub struct GlobalMetadataFileMatch<'a> {
pub fn match_global_metadata_file<'a>( pub fn match_global_metadata_file<'a>(
basename: &'a str, basename: &'a str,
page_extensions: &[String], page_extensions: &[RcStr],
) -> Option<GlobalMetadataFileMatch<'a>> { ) -> Option<GlobalMetadataFileMatch<'a>> {
match_metadata_file(basename, page_extensions, STATIC_GLOBAL_METADATA.deref()).map(|m| { match_metadata_file(basename, page_extensions, STATIC_GLOBAL_METADATA.deref()).map(|m| {
GlobalMetadataFileMatch { GlobalMetadataFileMatch {
...@@ -183,7 +183,7 @@ fn file_stem(path: &str) -> &str { ...@@ -183,7 +183,7 @@ fn file_stem(path: &str) -> &str {
/// /favicon, /manifest, use to match dynamic API routes like app/robots.ts. /// /favicon, /manifest, use to match dynamic API routes like app/robots.ts.
pub fn is_metadata_route_file( pub fn is_metadata_route_file(
app_dir_relative_path: &str, app_dir_relative_path: &str,
page_extensions: &[String], page_extensions: &[RcStr],
with_extension: bool, with_extension: bool,
) -> bool { ) -> bool {
let (dir, filename) = split_directory(app_dir_relative_path); let (dir, filename) = split_directory(app_dir_relative_path);
...@@ -326,17 +326,20 @@ pub fn normalize_metadata_route(mut page: AppPage) -> Result<AppPage> { ...@@ -326,17 +326,20 @@ pub fn normalize_metadata_route(mut page: AppPage) -> Result<AppPage> {
page.0.pop(); page.0.pop();
page.push(PageSegment::Static(format!( page.push(PageSegment::Static(
"{}{}{}", format!(
base_name, "{}{}{}",
suffix base_name,
.map(|suffix| format!("-{suffix}")) suffix
.unwrap_or_default(), .map(|suffix| format!("-{suffix}"))
ext.map(|ext| format!(".{ext}")).unwrap_or_default(), .unwrap_or_default(),
)))?; ext.map(|ext| format!(".{ext}")).unwrap_or_default(),
)
.into(),
))?;
if !is_static_route { if !is_static_route {
page.push(PageSegment::OptionalCatchAll("__metadata_id__".to_string()))?; page.push(PageSegment::OptionalCatchAll("__metadata_id__".into()))?;
} }
page.push(PageSegment::PageType(PageType::Route))?; page.push(PageSegment::PageType(PageType::Route))?;
......
...@@ -145,7 +145,7 @@ async fn static_route_source( ...@@ -145,7 +145,7 @@ async fn static_route_source(
let file = File::from(code); let file = File::from(code);
let source = VirtualSource::new( let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")), path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
...@@ -197,7 +197,7 @@ async fn dynamic_text_route_source(path: Vc<FileSystemPath>) -> Result<Vc<Box<dy ...@@ -197,7 +197,7 @@ async fn dynamic_text_route_source(path: Vc<FileSystemPath>) -> Result<Vc<Box<dy
let file = File::from(code); let file = File::from(code);
let source = VirtualSource::new( let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")), path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
...@@ -218,8 +218,7 @@ async fn dynamic_site_map_route_source( ...@@ -218,8 +218,7 @@ async fn dynamic_site_map_route_source(
let mut static_generation_code = ""; let mut static_generation_code = "";
if mode.is_production() && page.contains(&PageSegment::Dynamic("[__metadata_id__]".to_string())) if mode.is_production() && page.contains(&PageSegment::Dynamic("[__metadata_id__]".into())) {
{
static_generation_code = indoc! { static_generation_code = indoc! {
r#" r#"
export async function generateStaticParams() { export async function generateStaticParams() {
...@@ -297,7 +296,7 @@ async fn dynamic_site_map_route_source( ...@@ -297,7 +296,7 @@ async fn dynamic_site_map_route_source(
let file = File::from(code); let file = File::from(code);
let source = VirtualSource::new( let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")), path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
...@@ -355,7 +354,7 @@ async fn dynamic_image_route_source(path: Vc<FileSystemPath>) -> Result<Vc<Box<d ...@@ -355,7 +354,7 @@ async fn dynamic_image_route_source(path: Vc<FileSystemPath>) -> Result<Vc<Box<d
let file = File::from(code); let file = File::from(code);
let source = VirtualSource::new( let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")), path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
......
...@@ -14,7 +14,7 @@ use std::{ ...@@ -14,7 +14,7 @@ use std::{
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TaskInput}; use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput};
pub use crate::next_app::{ pub use crate::next_app::{
app_client_references_chunks::{get_app_client_references_chunks, ClientReferencesChunks}, app_client_references_chunks::{get_app_client_references_chunks, ClientReferencesChunks},
...@@ -40,17 +40,17 @@ pub use crate::next_app::{ ...@@ -40,17 +40,17 @@ pub use crate::next_app::{
)] )]
pub enum PageSegment { pub enum PageSegment {
/// e.g. `/dashboard` /// e.g. `/dashboard`
Static(String), Static(RcStr),
/// e.g. `/[id]` /// e.g. `/[id]`
Dynamic(String), Dynamic(RcStr),
/// e.g. `/[...slug]` /// e.g. `/[...slug]`
CatchAll(String), CatchAll(RcStr),
/// e.g. `/[[...slug]]` /// e.g. `/[[...slug]]`
OptionalCatchAll(String), OptionalCatchAll(RcStr),
/// e.g. `/(shop)` /// e.g. `/(shop)`
Group(String), Group(RcStr),
/// e.g. `/@auth` /// e.g. `/@auth`
Parallel(String), Parallel(RcStr),
/// The final page type appended. (e.g. `/dashboard/page`, /// The final page type appended. (e.g. `/dashboard/page`,
/// `/api/hello/route`) /// `/api/hello/route`)
PageType(PageType), PageType(PageType),
...@@ -67,32 +67,32 @@ impl PageSegment { ...@@ -67,32 +67,32 @@ impl PageSegment {
} }
if let Some(s) = segment.strip_prefix('(').and_then(|s| s.strip_suffix(')')) { if let Some(s) = segment.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
return Ok(PageSegment::Group(s.to_string())); return Ok(PageSegment::Group(s.into()));
} }
if let Some(s) = segment.strip_prefix('@') { if let Some(s) = segment.strip_prefix('@') {
return Ok(PageSegment::Parallel(s.to_string())); return Ok(PageSegment::Parallel(s.into()));
} }
if let Some(s) = segment if let Some(s) = segment
.strip_prefix("[[...") .strip_prefix("[[...")
.and_then(|s| s.strip_suffix("]]")) .and_then(|s| s.strip_suffix("]]"))
{ {
return Ok(PageSegment::OptionalCatchAll(s.to_string())); return Ok(PageSegment::OptionalCatchAll(s.into()));
} }
if let Some(s) = segment if let Some(s) = segment
.strip_prefix("[...") .strip_prefix("[...")
.and_then(|s| s.strip_suffix(']')) .and_then(|s| s.strip_suffix(']'))
{ {
return Ok(PageSegment::CatchAll(s.to_string())); return Ok(PageSegment::CatchAll(s.into()));
} }
if let Some(s) = segment.strip_prefix('[').and_then(|s| s.strip_suffix(']')) { if let Some(s) = segment.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
return Ok(PageSegment::Dynamic(s.to_string())); return Ok(PageSegment::Dynamic(s.into()));
} }
Ok(PageSegment::Static(segment.to_string())) Ok(PageSegment::Static(segment.into()))
} }
} }
...@@ -308,13 +308,13 @@ impl PartialOrd for AppPage { ...@@ -308,13 +308,13 @@ impl PartialOrd for AppPage {
)] )]
pub enum PathSegment { pub enum PathSegment {
/// e.g. `/dashboard` /// e.g. `/dashboard`
Static(String), Static(RcStr),
/// e.g. `/[id]` /// e.g. `/[id]`
Dynamic(String), Dynamic(RcStr),
/// e.g. `/[...slug]` /// e.g. `/[...slug]`
CatchAll(String), CatchAll(RcStr),
/// e.g. `/[[...slug]]` /// e.g. `/[[...slug]]`
OptionalCatchAll(String), OptionalCatchAll(RcStr),
} }
impl Display for PathSegment { impl Display for PathSegment {
......
use anyhow::Result; use anyhow::Result;
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::FileSystemPath, turbo::tasks_fs::FileSystemPath,
turbopack::core::resolve::{options::ImportMapping, ExternalType}, turbopack::core::resolve::{options::ImportMapping, ExternalType},
...@@ -13,22 +13,19 @@ pub async fn get_postcss_package_mapping( ...@@ -13,22 +13,19 @@ pub async fn get_postcss_package_mapping(
) -> Result<Vc<ImportMapping>> { ) -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![ Ok(ImportMapping::Alternatives(vec![
// Prefer the local installed version over the next.js version // Prefer the local installed version over the next.js version
ImportMapping::PrimaryAlternative("postcss".to_string(), Some(project_path)).cell(), ImportMapping::PrimaryAlternative("postcss".into(), Some(project_path)).cell(),
ImportMapping::PrimaryAlternative( ImportMapping::PrimaryAlternative("postcss".into(), Some(get_next_package(project_path)))
"postcss".to_string(), .cell(),
Some(get_next_package(project_path)),
)
.cell(),
]) ])
.cell()) .cell())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_external_next_compiled_package_mapping( pub async fn get_external_next_compiled_package_mapping(
package_name: Vc<String>, package_name: Vc<RcStr>,
) -> Result<Vc<ImportMapping>> { ) -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![ImportMapping::External( Ok(ImportMapping::Alternatives(vec![ImportMapping::External(
Some(format!("next/dist/compiled/{}", &*package_name.await?)), Some(format!("next/dist/compiled/{}", &*package_name.await?).into()),
ExternalType::CommonJs, ExternalType::CommonJs,
) )
.into()]) .into()])
......
...@@ -2,7 +2,7 @@ use std::iter::once; ...@@ -2,7 +2,7 @@ use std::iter::once;
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use indexmap::IndexMap;
use turbo_tasks::{Value, Vc}; use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::FileSystem; use turbo_tasks_fs::FileSystem;
use turbopack_binding::{ use turbopack_binding::{
turbo::{tasks_env::EnvMap, tasks_fs::FileSystemPath}, turbo::{tasks_env::EnvMap, tasks_fs::FileSystemPath},
...@@ -66,17 +66,17 @@ use crate::{ ...@@ -66,17 +66,17 @@ use crate::{
util::foreign_code_context_condition, util::foreign_code_context_condition,
}; };
fn defines(define_env: &IndexMap<String, String>) -> CompileTimeDefines { fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines {
let mut defines = IndexMap::new(); let mut defines = IndexMap::new();
for (k, v) in define_env { for (k, v) in define_env {
defines defines
.entry(k.split('.').map(|s| s.to_string()).collect::<Vec<String>>()) .entry(k.split('.').map(|s| s.into()).collect::<Vec<RcStr>>())
.or_insert_with(|| { .or_insert_with(|| {
let val = serde_json::from_str(v); let val = serde_json::from_str(v);
match val { match val {
Ok(serde_json::Value::Bool(v)) => CompileTimeDefineValue::Bool(v), Ok(serde_json::Value::Bool(v)) => CompileTimeDefineValue::Bool(v),
Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v), Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v.into()),
_ => CompileTimeDefineValue::JSON(v.clone()), _ => CompileTimeDefineValue::JSON(v.clone()),
} }
}); });
...@@ -95,14 +95,14 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer ...@@ -95,14 +95,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".to_string(), request: "node:buffer".into(),
lookup_path: None, lookup_path: None,
export: Some("Buffer".to_string()), export: Some("Buffer".into()),
}, },
process = FreeVarReference::EcmaScriptModule { process = FreeVarReference::EcmaScriptModule {
request: "node:process".to_string(), request: "node:process".into(),
lookup_path: None, lookup_path: None,
export: Some("default".to_string()), export: Some("default".into()),
} }
) )
.cell()) .cell())
...@@ -110,7 +110,7 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer ...@@ -110,7 +110,7 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn get_client_compile_time_info( pub fn get_client_compile_time_info(
browserslist_query: String, browserslist_query: RcStr,
define_env: Vc<EnvMap>, define_env: Vc<EnvMap>,
) -> Vc<CompileTimeInfo> { ) -> Vc<CompileTimeInfo> {
CompileTimeInfo::builder(Environment::new(Value::new(ExecutionEnvironment::Browser( CompileTimeInfo::builder(Environment::new(Value::new(ExecutionEnvironment::Browser(
...@@ -149,7 +149,7 @@ pub async fn get_client_resolve_options_context( ...@@ -149,7 +149,7 @@ pub async fn get_client_resolve_options_context(
let next_client_fallback_import_map = get_next_client_fallback_import_map(ty); let next_client_fallback_import_map = get_next_client_fallback_import_map(ty);
let next_client_resolved_map = let next_client_resolved_map =
get_next_client_resolved_map(project_path, project_path, *mode.await?); get_next_client_resolved_map(project_path, project_path, *mode.await?);
let custom_conditions = vec![mode.await?.condition().to_string()]; let custom_conditions = vec![mode.await?.condition().into()];
let module_options_context = ResolveOptionsContext { let module_options_context = ResolveOptionsContext {
enable_node_modules: Some(project_path.root().resolve().await?), enable_node_modules: Some(project_path.root().resolve().await?),
custom_conditions, custom_conditions,
...@@ -218,7 +218,7 @@ pub async fn get_client_module_options_context( ...@@ -218,7 +218,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".to_string(), mode.await?.condition().to_string()]; let conditions = vec!["browser".into(), 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,
...@@ -226,7 +226,7 @@ pub async fn get_client_module_options_context( ...@@ -226,7 +226,7 @@ pub async fn get_client_module_options_context(
conditions conditions
.iter() .iter()
.cloned() .cloned()
.chain(once("foreign".to_string())) .chain(once("foreign".into()))
.collect(), .collect(),
) )
.await?; .await?;
...@@ -326,7 +326,7 @@ pub async fn get_client_module_options_context( ...@@ -326,7 +326,7 @@ pub async fn get_client_module_options_context(
pub async fn get_client_chunking_context( pub async fn get_client_chunking_context(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
client_root: Vc<FileSystemPath>, client_root: Vc<FileSystemPath>,
asset_prefix: Vc<Option<String>>, asset_prefix: Vc<Option<RcStr>>,
environment: Vc<Environment>, environment: Vc<Environment>,
mode: Vc<NextMode>, mode: Vc<NextMode>,
) -> Result<Vc<Box<dyn ChunkingContext>>> { ) -> Result<Vc<Box<dyn ChunkingContext>>> {
...@@ -335,7 +335,7 @@ pub async fn get_client_chunking_context( ...@@ -335,7 +335,7 @@ pub async fn get_client_chunking_context(
project_path, project_path,
client_root, client_root,
client_root, client_root,
client_root.join("static/chunks".to_string()), client_root.join("static/chunks".into()),
get_client_assets_path(client_root), get_client_assets_path(client_root),
environment, environment,
next_mode.runtime_type(), next_mode.runtime_type(),
...@@ -353,7 +353,7 @@ pub async fn get_client_chunking_context( ...@@ -353,7 +353,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".to_string()) client_root.join("static/media".into())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -379,7 +379,7 @@ pub async fn get_client_runtime_entries( ...@@ -379,7 +379,7 @@ pub async fn get_client_runtime_entries(
// functions to be available. // functions to be available.
if let Some(request) = enable_react_refresh { if let Some(request) = enable_react_refresh {
runtime_entries runtime_entries
.push(RuntimeEntry::Request(request, project_root.join("_".to_string())).cell()) .push(RuntimeEntry::Request(request, project_root.join("_".into())).cell())
}; };
} }
...@@ -387,9 +387,9 @@ pub async fn get_client_runtime_entries( ...@@ -387,9 +387,9 @@ pub async fn get_client_runtime_entries(
runtime_entries.push( runtime_entries.push(
RuntimeEntry::Request( RuntimeEntry::Request(
Request::parse(Value::new(Pattern::Constant( Request::parse(Value::new(Pattern::Constant(
"next/dist/client/app-next-turbopack.js".to_string(), "next/dist/client/app-next-turbopack.js".into(),
))), ))),
project_root.join("_".to_string()), project_root.join("_".into()),
) )
.cell(), .cell(),
); );
......
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{ core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -31,8 +31,8 @@ impl CssClientReferenceModule { ...@@ -31,8 +31,8 @@ impl CssClientReferenceModule {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn css_client_reference_modifier() -> Vc<String> { fn css_client_reference_modifier() -> Vc<RcStr> {
Vc::cell("css client reference".to_string()) Vc::cell("css client reference".into())
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
#![allow(rustdoc::private_intra_doc_links)] #![allow(rustdoc::private_intra_doc_links)]
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{ core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -46,8 +46,8 @@ impl EcmascriptClientReferenceModule { ...@@ -46,8 +46,8 @@ impl EcmascriptClientReferenceModule {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn ecmascript_client_reference_modifier() -> Vc<String> { fn ecmascript_client_reference_modifier() -> Vc<RcStr> {
Vc::cell("ecmascript client reference".to_string()) Vc::cell("ecmascript client reference".into())
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
...@@ -2,7 +2,7 @@ use std::{io::Write, iter::once}; ...@@ -2,7 +2,7 @@ use std::{io::Write, iter::once};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indoc::writedoc; use indoc::writedoc;
use turbo_tasks::{Value, ValueToString, Vc}; use turbo_tasks::{RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::File; use turbo_tasks_fs::File;
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{ core::{
...@@ -143,7 +143,7 @@ impl EcmascriptClientReferenceProxyModule { ...@@ -143,7 +143,7 @@ impl EcmascriptClientReferenceProxyModule {
AssetContent::file(File::from(code.source_code().clone()).into()); AssetContent::file(File::from(code.source_code().clone()).into());
let proxy_source = VirtualSource::new( let proxy_source = VirtualSource::new(
self.server_module_ident.path().join("proxy.js".to_string()), self.server_module_ident.path().join("proxy.js".into()),
proxy_module_content, proxy_module_content,
); );
...@@ -253,13 +253,13 @@ struct ProxyModuleChunkItem { ...@@ -253,13 +253,13 @@ struct ProxyModuleChunkItem {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn client_proxy_modifier() -> Vc<String> { fn client_proxy_modifier() -> Vc<RcStr> {
Vc::cell("client proxy".to_string()) Vc::cell("client proxy".into())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn client_reference_description() -> Vc<String> { fn client_reference_description() -> Vc<RcStr> {
Vc::cell("client references".to_string()) Vc::cell("client references".into())
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use turbo_tasks::{Value, Vc}; use turbo_tasks::{RcStr, Value, Vc};
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{ core::{
context::ProcessResult, context::ProcessResult,
...@@ -40,7 +40,7 @@ impl NextEcmascriptClientReferenceTransition { ...@@ -40,7 +40,7 @@ impl NextEcmascriptClientReferenceTransition {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Transition for NextEcmascriptClientReferenceTransition { impl Transition for NextEcmascriptClientReferenceTransition {
#[turbo_tasks::function] #[turbo_tasks::function]
fn process_layer(self: Vc<Self>, layer: Vc<String>) -> Vc<String> { fn process_layer(self: Vc<Self>, layer: Vc<RcStr>) -> Vc<RcStr> {
layer layer
} }
...@@ -58,10 +58,12 @@ impl Transition for NextEcmascriptClientReferenceTransition { ...@@ -58,10 +58,12 @@ impl Transition for NextEcmascriptClientReferenceTransition {
let ident = source.ident().await?; let ident = source.ident().await?;
let ident_path = ident.path.await?; let ident_path = ident.path.await?;
let client_source = if ident_path.path.contains("next/dist/esm/") { let client_source = if ident_path.path.contains("next/dist/esm/") {
let path = ident let path = ident.path.root().join(
.path ident_path
.root() .path
.join(ident_path.path.replace("next/dist/esm/", "next/dist/")); .replace("next/dist/esm/", "next/dist/")
.into(),
);
Vc::upcast(FileSource::new_with_query(path, ident.query)) Vc::upcast(FileSource::new_with_query(path, ident.query))
} else { } else {
source source
......
...@@ -8,7 +8,7 @@ use turbo_tasks::{ ...@@ -8,7 +8,7 @@ use turbo_tasks::{
debug::ValueDebugFormat, debug::ValueDebugFormat,
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow}, graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
trace::TraceRawVcs, trace::TraceRawVcs,
ReadRef, TryJoinIterExt, ValueToString, Vc, RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc,
}; };
use turbopack_binding::turbopack::core::{ use turbopack_binding::turbopack::core::{
module::{Module, Modules}, module::{Module, Modules},
...@@ -170,9 +170,9 @@ struct VisitClientReferenceNode { ...@@ -170,9 +170,9 @@ struct VisitClientReferenceNode {
Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Debug, ValueDebugFormat, TraceRawVcs, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Debug, ValueDebugFormat, TraceRawVcs,
)] )]
enum VisitClientReferenceNodeType { enum VisitClientReferenceNodeType {
ClientReference(ClientReference, ReadRef<String>), ClientReference(ClientReference, ReadRef<RcStr>),
ServerComponentEntry(Vc<NextServerComponentModule>, ReadRef<String>), ServerComponentEntry(Vc<NextServerComponentModule>, ReadRef<RcStr>),
Internal(Vc<Box<dyn Module>>, ReadRef<String>), Internal(Vc<Box<dyn Module>>, ReadRef<RcStr>),
} }
impl Visit<VisitClientReferenceNode> for VisitClientReference { impl Visit<VisitClientReferenceNode> for VisitClientReference {
...@@ -269,13 +269,13 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference { ...@@ -269,13 +269,13 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference {
fn span(&mut self, node: &VisitClientReferenceNode) -> tracing::Span { fn span(&mut self, node: &VisitClientReferenceNode) -> tracing::Span {
match &node.ty { match &node.ty {
VisitClientReferenceNodeType::ClientReference(_, name) => { VisitClientReferenceNodeType::ClientReference(_, name) => {
tracing::info_span!("client reference", name = **name) tracing::info_span!("client reference", name = name.to_string())
} }
VisitClientReferenceNodeType::Internal(_, name) => { VisitClientReferenceNodeType::Internal(_, name) => {
tracing::info_span!("module", name = **name) tracing::info_span!("module", name = name.to_string())
} }
VisitClientReferenceNodeType::ServerComponentEntry(_, name) => { VisitClientReferenceNodeType::ServerComponentEntry(_, name) => {
tracing::info_span!("layout segment", name = **name) tracing::info_span!("layout segment", name = name.to_string())
} }
} }
} }
......
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::core::{ use turbopack_binding::turbopack::core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
chunk::{ChunkableModule, ChunkingContext, ChunkingContextExt}, chunk::{ChunkableModule, ChunkingContext, ChunkingContextExt},
...@@ -46,8 +46,8 @@ impl NextDynamicEntryModule { ...@@ -46,8 +46,8 @@ impl NextDynamicEntryModule {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn dynamic_modifier() -> Vc<String> { fn dynamic_modifier() -> Vc<RcStr> {
Vc::cell("dynamic".to_string()) Vc::cell("dynamic".into())
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{Value, Vc}; use turbo_tasks::{RcStr, Value, Vc};
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{context::ProcessResult, reference_type::ReferenceType, source::Source}, core::{context::ProcessResult, reference_type::ReferenceType, source::Source},
turbopack::{transition::Transition, ModuleAssetContext}, turbopack::{transition::Transition, ModuleAssetContext},
...@@ -26,7 +26,7 @@ impl NextDynamicTransition { ...@@ -26,7 +26,7 @@ impl NextDynamicTransition {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Transition for NextDynamicTransition { impl Transition for NextDynamicTransition {
#[turbo_tasks::function] #[turbo_tasks::function]
fn process_layer(self: Vc<Self>, layer: Vc<String>) -> Vc<String> { fn process_layer(self: Vc<Self>, layer: Vc<RcStr>) -> Vc<RcStr> {
layer layer
} }
......
...@@ -4,7 +4,7 @@ use anyhow::Result; ...@@ -4,7 +4,7 @@ use anyhow::Result;
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow}, graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
ReadRef, TryJoinIterExt, ValueToString, Vc, RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc,
}; };
use turbopack_binding::turbopack::core::{ use turbopack_binding::turbopack::core::{
module::{Module, Modules}, module::{Module, Modules},
...@@ -66,8 +66,8 @@ struct VisitDynamic; ...@@ -66,8 +66,8 @@ struct VisitDynamic;
#[derive(Clone, Eq, PartialEq, Hash)] #[derive(Clone, Eq, PartialEq, Hash)]
enum VisitDynamicNode { enum VisitDynamicNode {
Dynamic(Vc<NextDynamicEntryModule>, ReadRef<String>), Dynamic(Vc<NextDynamicEntryModule>, ReadRef<RcStr>),
Internal(Vc<Box<dyn Module>>, ReadRef<String>), Internal(Vc<Box<dyn Module>>, ReadRef<RcStr>),
} }
impl Visit<VisitDynamicNode> for VisitDynamic { impl Visit<VisitDynamicNode> for VisitDynamic {
...@@ -117,10 +117,10 @@ impl Visit<VisitDynamicNode> for VisitDynamic { ...@@ -117,10 +117,10 @@ impl Visit<VisitDynamicNode> for VisitDynamic {
fn span(&mut self, node: &VisitDynamicNode) -> tracing::Span { fn span(&mut self, node: &VisitDynamicNode) -> tracing::Span {
match node { match node {
VisitDynamicNode::Dynamic(_, name) => { VisitDynamicNode::Dynamic(_, name) => {
tracing::info_span!("dynamic module", name = **name) tracing::info_span!("dynamic module", name = name.to_string())
} }
VisitDynamicNode::Internal(_, name) => { VisitDynamicNode::Internal(_, name) => {
tracing::info_span!("module", name = **name) tracing::info_span!("module", name = name.to_string())
} }
} }
} }
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use indexmap::IndexMap;
use turbo_tasks::{Value, Vc}; use turbo_tasks::{RcStr, Value, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::{tasks_env::EnvMap, tasks_fs::FileSystemPath}, turbo::{tasks_env::EnvMap, tasks_fs::FileSystemPath},
turbopack::{ turbopack::{
...@@ -33,17 +33,17 @@ use crate::{ ...@@ -33,17 +33,17 @@ use crate::{
util::{foreign_code_context_condition, NextRuntime}, util::{foreign_code_context_condition, NextRuntime},
}; };
fn defines(define_env: &IndexMap<String, String>) -> CompileTimeDefines { fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines {
let mut defines = IndexMap::new(); let mut defines = IndexMap::new();
for (k, v) in define_env { for (k, v) in define_env {
defines defines
.entry(k.split('.').map(|s| s.to_string()).collect::<Vec<String>>()) .entry(k.split('.').map(|s| s.into()).collect::<Vec<RcStr>>())
.or_insert_with(|| { .or_insert_with(|| {
let val = serde_json::from_str(v); let val = serde_json::from_str(v);
match val { match val {
Ok(serde_json::Value::Bool(v)) => CompileTimeDefineValue::Bool(v), Ok(serde_json::Value::Bool(v)) => CompileTimeDefineValue::Bool(v),
Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v), Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v.into()),
_ => CompileTimeDefineValue::JSON(v.clone()), _ => CompileTimeDefineValue::JSON(v.clone()),
} }
}); });
...@@ -67,9 +67,9 @@ async fn next_edge_free_vars( ...@@ -67,9 +67,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".to_string(), request: "buffer".into(),
lookup_path: Some(project_path), lookup_path: Some(project_path),
export: Some("Buffer".to_string()), export: Some("Buffer".into()),
}, },
) )
.cell()) .cell())
...@@ -141,16 +141,17 @@ pub async fn get_edge_resolve_options_context( ...@@ -141,16 +141,17 @@ pub async fn get_edge_resolve_options_context(
after_resolve_plugins.extend_from_slice(&base_plugins); after_resolve_plugins.extend_from_slice(&base_plugins);
// https://github.com/vercel/next.js/blob/bf52c254973d99fed9d71507a2e818af80b8ade7/packages/next/src/build/webpack-config.ts#L96-L102 // https://github.com/vercel/next.js/blob/bf52c254973d99fed9d71507a2e818af80b8ade7/packages/next/src/build/webpack-config.ts#L96-L102
let mut custom_conditions = vec![mode.await?.condition().to_string()]; let mut custom_conditions = vec![mode.await?.condition().into()];
custom_conditions.extend( custom_conditions.extend(
NextRuntime::Edge NextRuntime::Edge
.conditions() .conditions()
.iter() .iter()
.map(ToString::to_string), .map(ToString::to_string)
.map(RcStr::from),
); );
if ty.supports_react_server() { if ty.supports_react_server() {
custom_conditions.push("react-server".to_string()); custom_conditions.push("react-server".into());
}; };
let resolve_options_context = ResolveOptionsContext { let resolve_options_context = ResolveOptionsContext {
...@@ -186,18 +187,18 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -186,18 +187,18 @@ pub async fn get_edge_chunking_context_with_client_assets(
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
node_root: Vc<FileSystemPath>, node_root: Vc<FileSystemPath>,
client_root: Vc<FileSystemPath>, client_root: Vc<FileSystemPath>,
asset_prefix: Vc<Option<String>>, asset_prefix: Vc<Option<RcStr>>,
environment: Vc<Environment>, environment: Vc<Environment>,
) -> Result<Vc<Box<dyn ChunkingContext>>> { ) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".to_string()); let output_root = node_root.join("server/edge".into());
let next_mode = mode.await?; let next_mode = mode.await?;
Ok(Vc::upcast( Ok(Vc::upcast(
BrowserChunkingContext::builder( BrowserChunkingContext::builder(
project_path, project_path,
output_root, output_root,
client_root, client_root,
output_root.join("chunks/ssr".to_string()), output_root.join("chunks/ssr".into()),
client_root.join("static/media".to_string()), client_root.join("static/media".into()),
environment, environment,
next_mode.runtime_type(), next_mode.runtime_type(),
) )
...@@ -214,15 +215,15 @@ pub async fn get_edge_chunking_context( ...@@ -214,15 +215,15 @@ pub async fn get_edge_chunking_context(
node_root: Vc<FileSystemPath>, node_root: Vc<FileSystemPath>,
environment: Vc<Environment>, environment: Vc<Environment>,
) -> Result<Vc<Box<dyn ChunkingContext>>> { ) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".to_string()); let output_root = node_root.join("server/edge".into());
let next_mode = mode.await?; let next_mode = mode.await?;
Ok(Vc::upcast( Ok(Vc::upcast(
BrowserChunkingContext::builder( BrowserChunkingContext::builder(
project_path, project_path,
output_root, output_root,
output_root, output_root,
output_root.join("chunks".to_string()), output_root.join("chunks".into()),
output_root.join("assets".to_string()), output_root.join("assets".into()),
environment, environment,
next_mode.runtime_type(), next_mode.runtime_type(),
) )
...@@ -230,7 +231,7 @@ pub async fn get_edge_chunking_context( ...@@ -230,7 +231,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(Vc::cell(Some("blob:server/edge/".to_string()))) .asset_base_path(Vc::cell(Some("blob:server/edge/".into())))
.minify_type(next_mode.minify_type()) .minify_type(next_mode.minify_type())
.build(), .build(),
)) ))
......
use anyhow::Result; use anyhow::Result;
use indexmap::indexmap; use indexmap::indexmap;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{Value, Vc}; use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_binding::turbopack::{ use turbopack_binding::turbopack::{
core::{ core::{
...@@ -16,7 +16,7 @@ pub async fn wrap_edge_entry( ...@@ -16,7 +16,7 @@ pub async fn wrap_edge_entry(
context: Vc<Box<dyn AssetContext>>, context: Vc<Box<dyn AssetContext>>,
project_root: Vc<FileSystemPath>, project_root: Vc<FileSystemPath>,
entry: Vc<Box<dyn Module>>, entry: Vc<Box<dyn Module>>,
pathname: String, pathname: RcStr,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
// The wrapped module could be an async module, we handle that with the proxy // The wrapped module could be an async module, we handle that with the proxy
// here. The comma expression makes sure we don't call the function with the // here. The comma expression makes sure we don't call the function with the
...@@ -32,12 +32,12 @@ pub async fn wrap_edge_entry( ...@@ -32,12 +32,12 @@ pub async fn wrap_edge_entry(
// TODO(alexkirsz) Figure out how to name this virtual asset. // TODO(alexkirsz) Figure out how to name this virtual asset.
let virtual_source = VirtualSource::new( let virtual_source = VirtualSource::new(
project_root.join("edge-wrapper.js".to_string()), project_root.join("edge-wrapper.js".into()),
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
let inner_assets = indexmap! { let inner_assets = indexmap! {
"MODULE".to_string() => entry "MODULE".into() => entry
}; };
let module = context let module = context
......
use anyhow::Result; use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbo_tasks_fs::File; use turbo_tasks_fs::File;
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::FileSystemPath, turbo::tasks_fs::FileSystemPath,
...@@ -46,7 +46,7 @@ impl NextEdgeUnsupportedModuleReplacer { ...@@ -46,7 +46,7 @@ impl NextEdgeUnsupportedModuleReplacer {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextEdgeUnsupportedModuleReplacer { impl ImportMappingReplacement for NextEdgeUnsupportedModuleReplacer {
#[turbo_tasks::function] #[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> { fn replace(&self, _capture: RcStr) -> Vc<ImportMapping> {
ImportMapping::Ignore.into() ImportMapping::Ignore.into()
} }
......
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_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbo::tasks::trace::TraceRawVcs; use turbopack_binding::turbo::tasks::trace::TraceRawVcs;
pub(crate) struct DefaultFallbackFont { pub(crate) struct DefaultFallbackFont {
pub name: String, pub name: RcStr,
pub capsize_key: String, pub capsize_key: RcStr,
pub az_avg_width: f64, pub az_avg_width: f64,
pub units_per_em: u32, pub units_per_em: u32,
} }
...@@ -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".to_owned(), name: "Arial".into(),
capsize_key: "arial".to_owned(), capsize_key: "arial".into(),
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".to_owned(), name: "Times New Roman".into(),
capsize_key: "timesNewRoman".to_owned(), capsize_key: "timesNewRoman".into(),
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: Vc<String>, pub scoped_font_family: Vc<RcStr>,
/// The name of font locally, used in `src: local("{}")` /// The name of font locally, used in `src: local("{}")`
pub local_font_family: Vc<String>, pub local_font_family: Vc<RcStr>,
pub adjustment: Option<FontAdjustment>, pub adjustment: Option<FontAdjustment>,
} }
...@@ -48,7 +48,7 @@ pub(crate) enum FontFallback { ...@@ -48,7 +48,7 @@ pub(crate) enum FontFallback {
/// return this and omit fallback information instead. /// return this and omit fallback information instead.
Error, Error,
/// A list of manually provided font names to use a fallback, as-is. /// A list of manually provided font names to use a fallback, as-is.
Manual(Vec<String>), Manual(Vec<RcStr>),
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
...@@ -4,7 +4,7 @@ use anyhow::{Context, Result}; ...@@ -4,7 +4,7 @@ use anyhow::{Context, Result};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, Vc}; use turbo_tasks::{trace::TraceRawVcs, RcStr, Vc};
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::FileSystemPath, turbo::tasks_fs::FileSystemPath,
turbopack::core::issue::{IssueExt, IssueSeverity, StyledString}, turbopack::core::issue::{IssueExt, IssueSeverity, StyledString},
...@@ -27,7 +27,7 @@ use crate::{ ...@@ -27,7 +27,7 @@ use crate::{
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub(super) struct FontMetricsMapEntry { pub(super) struct FontMetricsMapEntry {
category: String, category: RcStr,
ascent: i32, ascent: i32,
descent: i32, descent: i32,
line_gap: u32, line_gap: u32,
...@@ -36,11 +36,11 @@ pub(super) struct FontMetricsMapEntry { ...@@ -36,11 +36,11 @@ pub(super) struct FontMetricsMapEntry {
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
pub(super) struct FontMetricsMap(pub HashMap<String, FontMetricsMapEntry>); pub(super) struct FontMetricsMap(pub HashMap<RcStr, FontMetricsMapEntry>);
#[derive(Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)] #[derive(Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
struct Fallback { struct Fallback {
pub font_family: String, pub font_family: RcStr,
pub adjustment: Option<FontAdjustment>, pub adjustment: Option<FontAdjustment>,
} }
...@@ -53,11 +53,9 @@ pub(super) async fn get_font_fallback( ...@@ -53,11 +53,9 @@ pub(super) async fn get_font_fallback(
Ok(match &options.fallback { Ok(match &options.fallback {
Some(fallback) => FontFallback::Manual(fallback.clone()).cell(), Some(fallback) => FontFallback::Manual(fallback.clone()).cell(),
None => { None => {
let metrics_json = load_next_js_templateon( let metrics_json =
context, load_next_js_templateon(context, "dist/server/capsize-font-metrics.json".into())
"dist/server/capsize-font-metrics.json".to_string(), .await?;
)
.await?;
let fallback = lookup_fallback( let fallback = lookup_fallback(
&options.font_family, &options.font_family,
metrics_json, metrics_json,
...@@ -77,13 +75,16 @@ pub(super) async fn get_font_fallback( ...@@ -77,13 +75,16 @@ pub(super) async fn get_font_fallback(
Err(_) => { Err(_) => {
NextFontIssue { NextFontIssue {
path: context, path: context,
title: StyledString::Text(format!( title: StyledString::Text(
"Failed to find font override values for font `{}`", format!(
&options.font_family, "Failed to find font override values for font `{}`",
)) &options.font_family,
)
.into(),
)
.cell(), .cell(),
description: StyledString::Text( description: StyledString::Text(
"Skipping generating a fallback font.".to_owned(), "Skipping generating a fallback font.".into(),
) )
.cell(), .cell(),
severity: IssueSeverity::Warning.cell(), severity: IssueSeverity::Warning.cell(),
...@@ -100,7 +101,7 @@ pub(super) async fn get_font_fallback( ...@@ -100,7 +101,7 @@ pub(super) async fn get_font_fallback(
static FALLBACK_FONT_NAME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?:^\w|[A-Z]|\b\w)").unwrap()); static FALLBACK_FONT_NAME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?:^\w|[A-Z]|\b\w)").unwrap());
// From https://github.com/vercel/next.js/blob/1628260b88ce3052ac307a1607b6e8470188ab83/packages/next/src/server/font-utils.ts#L101 // From https://github.com/vercel/next.js/blob/1628260b88ce3052ac307a1607b6e8470188ab83/packages/next/src/server/font-utils.ts#L101
fn format_fallback_font_name(font_family: &str) -> String { fn format_fallback_font_name(font_family: &str) -> RcStr {
let mut fallback_name = FALLBACK_FONT_NAME let mut fallback_name = FALLBACK_FONT_NAME
.replace(font_family, |caps: &regex::Captures| { .replace(font_family, |caps: &regex::Captures| {
caps.iter() caps.iter()
...@@ -118,7 +119,7 @@ fn format_fallback_font_name(font_family: &str) -> String { ...@@ -118,7 +119,7 @@ fn format_fallback_font_name(font_family: &str) -> String {
}) })
.to_string(); .to_string();
fallback_name.retain(|c| !c.is_whitespace()); fallback_name.retain(|c| !c.is_whitespace());
fallback_name fallback_name.into()
} }
fn lookup_fallback( fn lookup_fallback(
...@@ -208,7 +209,7 @@ mod tests { ...@@ -208,7 +209,7 @@ mod tests {
assert_eq!( assert_eq!(
lookup_fallback("Inter", font_metrics, true)?, lookup_fallback("Inter", font_metrics, true)?,
Fallback { Fallback {
font_family: "Arial".to_owned(), font_family: "Arial".into(),
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,
...@@ -254,7 +255,7 @@ mod tests { ...@@ -254,7 +255,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".to_owned(), font_family: "Times New Roman".into(),
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,
......
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use indexmap::{indexset, IndexMap, IndexSet}; use indexmap::{indexset, IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::Vc; use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbo::tasks::{trace::TraceRawVcs, Value}; use turbopack_binding::turbo::tasks::{trace::TraceRawVcs, Value};
use super::request::{NextFontRequest, OneOrManyStrings}; use super::request::{NextFontRequest, OneOrManyStrings};
const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"]; const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"];
pub(super) type FontData = IndexMap<String, FontDataEntry>; pub(super) type FontData = IndexMap<RcStr, FontDataEntry>;
#[turbo_tasks::value(serialization = "auto_for_input")] #[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Clone, Debug, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, PartialOrd, Ord, Hash)]
pub(super) struct NextFontGoogleOptions { pub(super) struct NextFontGoogleOptions {
/// Name of the requested font from Google. Contains literal spaces. /// Name of the requested font from Google. Contains literal spaces.
pub font_family: String, pub font_family: RcStr,
pub weights: FontWeights, pub weights: FontWeights,
pub styles: Vec<String>, pub styles: Vec<RcStr>,
pub display: String, pub display: RcStr,
pub preload: bool, pub preload: bool,
pub selected_variable_axes: Option<Vec<String>>, pub selected_variable_axes: Option<Vec<RcStr>>,
pub fallback: Option<Vec<String>>, pub fallback: Option<Vec<RcStr>>,
pub adjust_font_fallback: bool, pub adjust_font_fallback: bool,
/// An optional name for a css custom property (css variable) that applies /// An optional name for a css custom property (css variable) that applies
/// the font family when used. /// the font family when used.
pub variable: Option<String>, pub variable: Option<RcStr>,
pub subsets: Option<Vec<String>>, pub subsets: Option<Vec<RcStr>>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -36,8 +36,8 @@ impl NextFontGoogleOptions { ...@@ -36,8 +36,8 @@ impl NextFontGoogleOptions {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn font_family(self: Vc<Self>) -> Result<Vc<String>> { pub async fn font_family(self: Vc<Self>) -> Result<Vc<RcStr>> {
Ok(Vc::cell((*self.await?.font_family).to_owned())) Ok(Vc::cell((*self.await?.font_family).into()))
} }
} }
...@@ -51,15 +51,15 @@ pub(super) enum FontWeights { ...@@ -51,15 +51,15 @@ pub(super) enum FontWeights {
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, TraceRawVcs)] #[derive(Debug, PartialEq, Eq, Deserialize, Serialize, TraceRawVcs)]
pub(super) struct FontDataEntry { pub(super) struct FontDataEntry {
pub weights: Vec<String>, pub weights: Vec<RcStr>,
pub styles: Vec<String>, pub styles: Vec<RcStr>,
pub axes: Option<Vec<Axis>>, pub axes: Option<Vec<Axis>>,
} }
#[derive(Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)] #[derive(Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub(super) struct Axis { pub(super) struct Axis {
pub tag: String, pub tag: RcStr,
pub min: f64, pub min: f64,
pub max: f64, pub max: f64,
} }
...@@ -71,7 +71,7 @@ impl Eq for Axis {} ...@@ -71,7 +71,7 @@ impl Eq for Axis {}
// https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22 // https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22
pub(super) fn options_from_request( pub(super) fn options_from_request(
request: &NextFontRequest, request: &NextFontRequest,
data: &IndexMap<String, FontDataEntry>, data: &IndexMap<RcStr, FontDataEntry>,
) -> Result<NextFontGoogleOptions> { ) -> Result<NextFontGoogleOptions> {
if request.arguments.len() > 1 { if request.arguments.len() > 1 {
return Err(anyhow!( return Err(anyhow!(
...@@ -82,10 +82,10 @@ pub(super) fn options_from_request( ...@@ -82,10 +82,10 @@ pub(super) fn options_from_request(
let argument = request.arguments.last().cloned().unwrap_or_default(); let argument = request.arguments.last().cloned().unwrap_or_default();
// `import` comes from the imported symbol in JS, which separates with _ // `import` comes from the imported symbol in JS, which separates with _
let font_family = request.import.replace('_', " "); let font_family: RcStr = request.import.replace('_', " ").into();
let font_data = data.get(&font_family).context("Unknown font")?; let font_data = data.get(&font_family).context("Unknown font")?;
let requested_weights: IndexSet<String> = argument let requested_weights: IndexSet<RcStr> = argument
.weight .weight
.map(|w| match w { .map(|w| match w {
OneOrManyStrings::One(one) => indexset! {one}, OneOrManyStrings::One(one) => indexset! {one},
...@@ -102,7 +102,7 @@ pub(super) fn options_from_request( ...@@ -102,7 +102,7 @@ pub(super) fn options_from_request(
.unwrap_or_default(); .unwrap_or_default();
let weights = if requested_weights.is_empty() { let weights = if requested_weights.is_empty() {
if !font_data.weights.contains(&"variable".to_owned()) { if !font_data.weights.contains(&"variable".into()) {
return Err(anyhow!( return Err(anyhow!(
"Missing weight for {}. Available weights: {}", "Missing weight for {}. Available weights: {}",
font_family, font_family,
...@@ -145,7 +145,7 @@ pub(super) fn options_from_request( ...@@ -145,7 +145,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".to_owned()); styles.push("normal".into());
} }
} }
...@@ -160,9 +160,9 @@ pub(super) fn options_from_request( ...@@ -160,9 +160,9 @@ pub(super) fn options_from_request(
} }
} }
let display = argument.display.unwrap_or_else(|| "swap".to_owned()); let display = argument.display.unwrap_or_else(|| "swap".into());
if !ALLOWED_DISPLAY_VALUES.contains(&display.as_ref()) { if !ALLOWED_DISPLAY_VALUES.contains(&display.as_str()) {
return Err(anyhow!( return Err(anyhow!(
"Invalid display value {} for font {}.\nAvailable display values: {}", "Invalid display value {} for font {}.\nAvailable display values: {}",
display, display,
...@@ -195,6 +195,7 @@ pub(super) fn options_from_request( ...@@ -195,6 +195,7 @@ pub(super) fn options_from_request(
mod tests { mod tests {
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use indexmap::IndexMap;
use turbo_tasks::RcStr;
use turbopack_binding::turbo::tasks_fs::json::parse_json_with_source_context; use turbopack_binding::turbo::tasks_fs::json::parse_json_with_source_context;
use super::{options_from_request, FontDataEntry, NextFontGoogleOptions}; use super::{options_from_request, FontDataEntry, NextFontGoogleOptions};
...@@ -202,7 +203,7 @@ mod tests { ...@@ -202,7 +203,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unknown_font() -> Result<()> { fn test_errors_on_unknown_font() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -235,7 +236,7 @@ mod tests { ...@@ -235,7 +236,7 @@ mod tests {
#[test] #[test]
fn test_default_values_when_no_arguments() -> Result<()> { fn test_default_values_when_no_arguments() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -260,10 +261,10 @@ mod tests { ...@@ -260,10 +261,10 @@ mod tests {
assert_eq!( assert_eq!(
options_from_request(&request, &data)?, options_from_request(&request, &data)?,
NextFontGoogleOptions { NextFontGoogleOptions {
font_family: "ABeeZee".to_owned(), font_family: "ABeeZee".into(),
weights: FontWeights::Variable, weights: FontWeights::Variable,
styles: vec!["normal".to_owned()], styles: vec!["normal".into()],
display: "swap".to_owned(), display: "swap".into(),
preload: true, preload: true,
selected_variable_axes: None, selected_variable_axes: None,
fallback: None, fallback: None,
...@@ -278,7 +279,7 @@ mod tests { ...@@ -278,7 +279,7 @@ mod tests {
#[test] #[test]
fn test_errors_when_no_weights_chosen_no_variable() -> Result<()> { fn test_errors_when_no_weights_chosen_no_variable() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -314,7 +315,7 @@ mod tests { ...@@ -314,7 +315,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unnecessary_weights() -> Result<()> { fn test_errors_on_unnecessary_weights() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -353,7 +354,7 @@ mod tests { ...@@ -353,7 +354,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unvavailable_weights() -> Result<()> { fn test_errors_on_unvavailable_weights() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -391,7 +392,7 @@ mod tests { ...@@ -391,7 +392,7 @@ mod tests {
#[test] #[test]
fn test_defaults_to_only_style_when_one_available() -> Result<()> { fn test_defaults_to_only_style_when_one_available() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -416,14 +417,14 @@ mod tests { ...@@ -416,14 +417,14 @@ mod tests {
)?; )?;
let options = options_from_request(&request, &data)?; let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec!["italic".to_owned()]); assert_eq!(options.styles, vec![RcStr::from("italic")]);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_defaults_to_normal_style_when_multiple() -> Result<()> { fn test_defaults_to_normal_style_when_multiple() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -448,14 +449,14 @@ mod tests { ...@@ -448,14 +449,14 @@ mod tests {
)?; )?;
let options = options_from_request(&request, &data)?; let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec!["normal".to_owned()]); assert_eq!(options.styles, vec![RcStr::from("normal")]);
Ok(()) Ok(())
} }
#[test] #[test]
fn test_errors_on_unknown_styles() -> Result<()> { fn test_errors_on_unknown_styles() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -495,7 +496,7 @@ mod tests { ...@@ -495,7 +496,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unknown_display() -> Result<()> { fn test_errors_on_unknown_display() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -536,7 +537,7 @@ mod tests { ...@@ -536,7 +537,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_axes_without_variable() -> Result<()> { fn test_errors_on_axes_without_variable() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context( let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
......
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