Unverified Commit 2dade5df authored by Alex Kirszenberg's avatar Alex Kirszenberg Committed by GitHub

Refactor pages structure (#49802)

parent e5ad96ed
......@@ -7,4 +7,4 @@ export {
__N_SSG,
// @ts-expect-error
__N_SSP,
} from '@vercel/turbopack-next/internal/_error'
} from '@vercel/turbopack-next/pages/_error'
export * from '@vercel/turbopack-next/pages/_app'
export { default } from '@vercel/turbopack-next/pages/_app'
export * from '@vercel/turbopack-next/pages/_document'
export { default } from '@vercel/turbopack-next/pages/_document'
export * from '@vercel/turbopack-next/pages/_error'
export { default } from '@vercel/turbopack-next/pages/_error'
......@@ -26,6 +26,7 @@
"@vercel/turbopack-next/*": ["src/*"],
"@vercel/turbopack-next/pages/_app": ["node_modules/next/app"],
"@vercel/turbopack-next/pages/_document": ["node_modules/next/document"],
"@vercel/turbopack-next/pages/_error": ["node_modules/next/error"],
"@vercel/turbopack-next/internal/_error": ["node_modules/next/error"],
"next/*": ["node_modules/next/*"]
},
......
......@@ -79,7 +79,7 @@ pub async fn get_next_client_import_map(
);
insert_alias_to_alternatives(
&mut import_map,
format!("{VIRTUAL_PACKAGE_NAME}/internal/_error"),
format!("{VIRTUAL_PACKAGE_NAME}/pages/_error"),
vec![
request_to_import_mapping(pages_dir, "./_error"),
request_to_import_mapping(pages_dir, "next/error"),
......@@ -375,7 +375,7 @@ pub async fn insert_next_server_special_aliases(
);
insert_alias_to_alternatives(
import_map,
format!("{VIRTUAL_PACKAGE_NAME}/internal/_error"),
format!("{VIRTUAL_PACKAGE_NAME}/pages/_error"),
vec![
request_to_import_mapping(pages_dir, "./_error"),
external_request_to_import_mapping("next/error"),
......
......@@ -76,9 +76,10 @@ use crate::{
},
page_loader::create_page_loader,
pages_structure::{
OptionPagesStructureVc, PagesStructure, PagesStructureItem, PagesStructureVc,
OptionPagesStructureVc, PagesDirectoryStructure, PagesDirectoryStructureVc, PagesStructure,
PagesStructureItem, PagesStructureVc,
},
util::{parse_config_from_source, pathname_for_path, render_data, NextRuntime},
util::{parse_config_from_source, pathname_for_path, render_data, NextRuntime, PathType},
};
/// Create a content source serving the `pages` or `src/pages` directory as
......@@ -86,10 +87,10 @@ use crate::{
#[turbo_tasks::function]
pub async fn create_page_source(
pages_structure: OptionPagesStructureVc,
project_path: FileSystemPathVc,
project_root: FileSystemPathVc,
execution_context: ExecutionContextVc,
output_path: FileSystemPathVc,
server_root: FileSystemPathVc,
node_root: FileSystemPathVc,
client_root: FileSystemPathVc,
env: ProcessEnvVc,
browserslist_query: &str,
next_config: NextConfigVc,
......@@ -97,11 +98,11 @@ pub async fn create_page_source(
) -> Result<ContentSourceVc> {
let (pages_dir, pages_structure) = if let Some(pages_structure) = *pages_structure.await? {
(
pages_structure.directory().resolve().await?,
pages_structure.project_path().resolve().await?,
Some(pages_structure),
)
} else {
(project_path.join("pages"), None)
(project_root.join("pages"), None)
};
let client_ty = Value::new(ClientContextType::Pages { pages_dir });
......@@ -110,24 +111,24 @@ pub async fn create_page_source(
let client_compile_time_info = get_client_compile_time_info(browserslist_query);
let client_module_options_context = get_client_module_options_context(
project_path,
project_root,
execution_context,
client_compile_time_info.environment(),
client_ty,
next_config,
);
let client_resolve_options_context =
get_client_resolve_options_context(project_path, client_ty, next_config, execution_context);
get_client_resolve_options_context(project_root, client_ty, next_config, execution_context);
let client_chunking_context = get_client_chunking_context(
project_path,
server_root,
project_root,
client_root,
client_compile_time_info.environment(),
client_ty,
);
let client_runtime_entries =
get_client_runtime_entries(project_path, env, client_ty, next_config, execution_context);
get_client_runtime_entries(project_root, env, client_ty, next_config, execution_context);
let next_client_transition = NextClientTransition {
is_app: false,
......@@ -141,17 +142,17 @@ pub async fn create_page_source(
.into();
let edge_compile_time_info = get_edge_compile_time_info(
project_path,
project_root,
server_addr,
Value::new(EnvironmentIntention::Api),
);
let edge_chunking_context = DevChunkingContextVc::builder(
project_path,
output_path.join("edge"),
output_path.join("edge/chunks"),
project_root,
node_root.join("edge"),
node_root.join("edge/chunks"),
get_client_assets_path(
server_root,
client_root,
Value::new(ClientContextType::Pages { pages_dir }),
),
edge_compile_time_info.environment(),
......@@ -159,15 +160,15 @@ pub async fn create_page_source(
.reference_chunk_source_maps(false)
.build();
let edge_resolve_options_context =
get_edge_resolve_options_context(project_path, server_ty, next_config, execution_context);
get_edge_resolve_options_context(project_root, server_ty, next_config, execution_context);
let next_edge_transition = NextEdgeTransition {
edge_compile_time_info,
edge_chunking_context,
edge_module_options_context: None,
edge_resolve_options_context,
output_path,
base_path: project_path,
output_path: node_root,
base_path: project_root,
bootstrap_asset: next_asset("entry/edge-bootstrap.ts"),
entry_name: "edge".to_string(),
}
......@@ -176,13 +177,13 @@ pub async fn create_page_source(
let server_compile_time_info = get_server_compile_time_info(server_ty, env, server_addr);
let server_resolve_options_context =
get_server_resolve_options_context(project_path, server_ty, next_config, execution_context);
get_server_resolve_options_context(project_root, server_ty, next_config, execution_context);
let server_module_options_context =
get_server_module_options_context(project_path, execution_context, server_ty, next_config);
get_server_module_options_context(project_root, execution_context, server_ty, next_config);
let server_data_module_options_context = get_server_module_options_context(
project_path,
project_root,
execution_context,
server_data_ty,
next_config,
......@@ -195,10 +196,10 @@ pub async fn create_page_source(
(
"next-client-chunks".to_string(),
NextClientChunksTransitionVc::new(
project_path,
project_root,
execution_context,
client_ty,
server_root,
client_root,
client_compile_time_info,
next_config,
)
......@@ -236,14 +237,14 @@ pub async fn create_page_source(
let server_runtime_entries =
AssetsVc::cell(vec![
ProcessEnvAssetVc::new(project_path, injected_env).into()
ProcessEnvAssetVc::new(project_root, injected_env).into()
]);
let fallback_runtime_entries = AssetsVc::cell(vec![]);
let fallback_page = get_fallback_page(
project_path,
project_root,
execution_context,
server_root,
client_root,
env,
client_compile_time_info,
next_config,
......@@ -257,7 +258,7 @@ pub async fn create_page_source(
// Match _next/404 first to ensure rewrites work properly.
sources.push(
create_not_found_page_source(
project_path,
project_root,
env,
server_context,
client_context,
......@@ -265,8 +266,8 @@ pub async fn create_page_source(
page_extensions,
fallback_runtime_entries,
fallback_page,
server_root,
output_path.join("force_not_found"),
client_root,
node_root.join("force_not_found"),
SpecificityVc::exact(),
NextExactMatcherVc::new(StringVc::cell("_next/404".to_string())).into(),
render_data,
......@@ -275,9 +276,9 @@ pub async fn create_page_source(
);
if let Some(pages_structure) = pages_structure {
sources.push(create_page_source_for_directory(
sources.push(create_page_source_for_root_directory(
pages_structure,
project_path,
project_root,
env,
server_context,
server_data_context,
......@@ -285,21 +286,21 @@ pub async fn create_page_source(
pages_dir,
server_runtime_entries,
fallback_page,
server_root,
output_path,
client_root,
node_root,
render_data,
));
}
sources.push(
AssetGraphContentSourceVc::new_eager(server_root, fallback_page.as_asset())
AssetGraphContentSourceVc::new_eager(client_root, fallback_page.as_asset())
.as_content_source()
.issue_context(pages_dir, "Next.js pages directory fallback"),
);
sources.push(
create_not_found_page_source(
project_path,
project_root,
env,
server_context,
client_context,
......@@ -307,8 +308,8 @@ pub async fn create_page_source(
page_extensions,
fallback_runtime_entries,
fallback_page,
server_root,
output_path.join("fallback_not_found"),
client_root,
node_root.join("fallback_not_found"),
SpecificityVc::not_found(),
NextFallbackMatcherVc::new().into(),
render_data,
......@@ -333,19 +334,19 @@ async fn create_page_source_for_file(
page_asset: AssetVc,
runtime_entries: AssetsVc,
fallback_page: DevHtmlAssetVc,
server_root: FileSystemPathVc,
server_path: FileSystemPathVc,
client_root: FileSystemPathVc,
client_path: FileSystemPathVc,
is_api_path: bool,
intermediate_output_path: FileSystemPathVc,
output_root: FileSystemPathVc,
node_path: FileSystemPathVc,
node_root: FileSystemPathVc,
render_data: JsonValueVc,
) -> Result<ContentSourceVc> {
let server_chunking_context = DevChunkingContextVc::builder(
project_path,
intermediate_output_path,
intermediate_output_path.join("chunks"),
node_path,
node_path.join("chunks"),
get_client_assets_path(
server_root,
client_root,
Value::new(ClientContextType::Pages { pages_dir }),
),
server_context.compile_time_info().environment(),
......@@ -353,14 +354,14 @@ async fn create_page_source_for_file(
.reference_chunk_source_maps(false)
.build();
let data_intermediate_output_path = intermediate_output_path.join("data");
let data_node_path = node_path.join("data");
let server_data_chunking_context = DevChunkingContextVc::builder(
project_path,
data_intermediate_output_path,
data_intermediate_output_path.join("chunks"),
data_node_path,
data_node_path.join("chunks"),
get_client_assets_path(
server_root,
client_root,
Value::new(ClientContextType::Pages { pages_dir }),
),
server_context.compile_time_info().environment(),
......@@ -370,12 +371,12 @@ async fn create_page_source_for_file(
let client_chunking_context = get_client_chunking_context(
project_path,
server_root,
client_root,
client_context.compile_time_info().environment(),
Value::new(ClientContextType::Pages { pages_dir }),
);
let pathname = pathname_for_path(server_root, server_path, true, false);
let pathname = pathname_for_path(client_root, client_path, PathType::Page);
let route_matcher = NextParamsMatcherVc::new(pathname);
Ok(if is_api_path {
......@@ -383,7 +384,7 @@ async fn create_page_source_for_file(
project_path,
env,
specificity,
server_root,
client_root,
route_matcher.into(),
pathname,
SsrEntry {
......@@ -392,8 +393,8 @@ async fn create_page_source_for_file(
entry_asset: page_asset,
ty: SsrType::AutoApi,
chunking_context: server_chunking_context,
intermediate_output_path,
output_root,
node_path,
node_root,
project_path,
}
.cell()
......@@ -401,7 +402,7 @@ async fn create_page_source_for_file(
render_data,
)
} else {
let data_pathname = pathname_for_path(server_root, server_path, true, true);
let data_pathname = pathname_for_path(client_root, client_path, PathType::Data);
let data_route_matcher =
NextPrefixSuffixParamsMatcherVc::new(data_pathname, "_next/data/development/", ".json");
......@@ -411,8 +412,8 @@ async fn create_page_source_for_file(
entry_asset: page_asset,
ty: SsrType::Html,
chunking_context: server_chunking_context,
intermediate_output_path,
output_root,
node_path,
node_root,
project_path,
}
.cell()
......@@ -424,8 +425,8 @@ async fn create_page_source_for_file(
entry_asset: page_asset,
ty: SsrType::Data,
chunking_context: server_data_chunking_context,
intermediate_output_path: data_intermediate_output_path,
output_root,
node_path: data_node_path,
node_root,
project_path,
}
.cell()
......@@ -436,7 +437,7 @@ async fn create_page_source_for_file(
project_path,
env,
specificity,
server_root,
client_root,
route_matcher.into(),
pathname,
ssr_entry,
......@@ -447,7 +448,7 @@ async fn create_page_source_for_file(
project_path,
env,
specificity,
server_root,
client_root,
data_route_matcher.into(),
pathname,
ssr_data_entry,
......@@ -455,7 +456,7 @@ async fn create_page_source_for_file(
render_data,
),
create_page_loader(
server_root,
client_root,
client_context,
client_chunking_context,
page_asset,
......@@ -491,18 +492,18 @@ async fn create_not_found_page_source(
page_extensions: StringsVc,
runtime_entries: AssetsVc,
fallback_page: DevHtmlAssetVc,
server_root: FileSystemPathVc,
intermediate_output_path: FileSystemPathVc,
client_root: FileSystemPathVc,
node_path: FileSystemPathVc,
specificity: SpecificityVc,
route_matcher: RouteMatcherVc,
render_data: JsonValueVc,
) -> Result<ContentSourceVc> {
let server_chunking_context = DevChunkingContextVc::builder(
project_path,
intermediate_output_path,
intermediate_output_path.join("chunks"),
node_path,
node_path.join("chunks"),
get_client_assets_path(
server_root,
client_root,
Value::new(ClientContextType::Pages { pages_dir }),
),
server_context.compile_time_info().environment(),
......@@ -512,7 +513,7 @@ async fn create_not_found_page_source(
let client_chunking_context = get_client_chunking_context(
project_path,
server_root,
client_root,
client_context.compile_time_info().environment(),
Value::new(ClientContextType::Pages { pages_dir }),
);
......@@ -542,15 +543,15 @@ async fn create_not_found_page_source(
entry_asset,
ty: SsrType::Html,
chunking_context: server_chunking_context,
intermediate_output_path,
output_root: intermediate_output_path,
node_path,
node_root: node_path,
project_path,
}
.cell()
.into();
let page_loader = create_page_loader(
server_root,
client_root,
client_context,
client_chunking_context,
entry_asset,
......@@ -562,7 +563,7 @@ async fn create_not_found_page_source(
project_path,
env,
specificity,
server_root,
client_root,
route_matcher,
pathname,
ssr_entry,
......@@ -578,9 +579,9 @@ async fn create_not_found_page_source(
/// Calls itself recursively for sub directories or the
/// [create_page_source_for_file] method for files.
#[turbo_tasks::function]
async fn create_page_source_for_directory(
async fn create_page_source_for_root_directory(
pages_structure: PagesStructureVc,
project_path: FileSystemPathVc,
project_root: FileSystemPathVc,
env: ProcessEnvVc,
server_context: AssetContextVc,
server_data_context: AssetContextVc,
......@@ -588,11 +589,76 @@ async fn create_page_source_for_directory(
pages_dir: FileSystemPathVc,
runtime_entries: AssetsVc,
fallback_page: DevHtmlAssetVc,
server_root: FileSystemPathVc,
output_root: FileSystemPathVc,
client_root: FileSystemPathVc,
node_root: FileSystemPathVc,
render_data: JsonValueVc,
) -> Result<ContentSourceVc> {
let PagesStructure {
app: _,
document: _,
error: _,
ref api,
ref pages,
} = *pages_structure.await?;
let mut sources = vec![];
sources.push(create_page_source_for_directory(
*pages,
project_root,
env,
server_context,
server_data_context,
client_context,
pages_dir,
runtime_entries,
fallback_page,
client_root,
false,
node_root,
render_data,
));
if let Some(api) = api {
sources.push(create_page_source_for_directory(
*api,
project_root,
env,
server_context,
server_data_context,
client_context,
pages_dir,
runtime_entries,
fallback_page,
client_root,
true,
node_root,
render_data,
));
}
Ok(CombinedContentSource { sources }.cell().into())
}
/// Handles a directory in the pages directory (or the pages directory itself).
/// Calls itself recursively for sub directories or the
/// [create_page_source_for_file] method for files.
#[turbo_tasks::function]
async fn create_page_source_for_directory(
pages_structure: PagesDirectoryStructureVc,
project_root: FileSystemPathVc,
env: ProcessEnvVc,
server_context: AssetContextVc,
server_data_context: AssetContextVc,
client_context: AssetContextVc,
pages_dir: FileSystemPathVc,
runtime_entries: AssetsVc,
fallback_page: DevHtmlAssetVc,
client_root: FileSystemPathVc,
is_api_path: bool,
node_root: FileSystemPathVc,
render_data: JsonValueVc,
) -> Result<ContentSourceVc> {
let PagesDirectoryStructure {
ref items,
ref children,
..
......@@ -600,61 +666,44 @@ async fn create_page_source_for_directory(
let mut sources = vec![];
for item in items.iter() {
let source = match *item.await? {
PagesStructureItem::Page {
page,
specificity,
url,
} => create_page_source_for_file(
project_path,
env,
server_context,
server_data_context,
client_context,
pages_dir,
specificity,
SourceAssetVc::new(page).into(),
runtime_entries,
fallback_page,
server_root,
url,
false,
output_root,
output_root,
render_data,
)
.issue_context(page, "Next.js pages directory"),
PagesStructureItem::Api {
api,
specificity,
url,
} => create_page_source_for_file(
project_path,
env,
server_context,
server_data_context,
client_context,
pages_dir,
specificity,
SourceAssetVc::new(api).into(),
runtime_entries,
fallback_page,
server_root,
url,
true,
output_root,
output_root,
render_data,
)
.issue_context(api, "Next.js pages api directory"),
};
let PagesStructureItem {
project_path,
specificity,
next_router_path,
} = *item.await?;
let source = create_page_source_for_file(
project_root,
env,
server_context,
server_data_context,
client_context,
pages_dir,
specificity,
SourceAssetVc::new(project_path).into(),
runtime_entries,
fallback_page,
client_root,
next_router_path,
is_api_path,
node_root,
node_root,
render_data,
)
.issue_context(
project_path,
if is_api_path {
"Next.js page API file"
} else {
"Next.js page file"
},
);
sources.push(source);
}
for child in children.iter() {
sources.push(create_page_source_for_directory(
*child,
project_path,
project_root,
env,
server_context,
server_data_context,
......@@ -662,8 +711,9 @@ async fn create_page_source_for_directory(
pages_dir,
runtime_entries,
fallback_page,
server_root,
output_root,
client_root,
is_api_path,
node_root,
render_data,
))
}
......@@ -671,34 +721,34 @@ async fn create_page_source_for_directory(
Ok(CombinedContentSource { sources }.cell().into())
}
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord, TraceRawVcs,
)]
enum SsrType {
Api,
EdgeApi,
AutoApi,
Html,
Data,
}
/// The node.js renderer for SSR of pages.
#[turbo_tasks::value]
struct SsrEntry {
pub struct SsrEntry {
runtime_entries: AssetsVc,
context: AssetContextVc,
entry_asset: AssetVc,
ty: SsrType,
chunking_context: ChunkingContextVc,
intermediate_output_path: FileSystemPathVc,
output_root: FileSystemPathVc,
node_path: FileSystemPathVc,
node_root: FileSystemPathVc,
project_path: FileSystemPathVc,
}
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord, TraceRawVcs,
)]
pub enum SsrType {
Api,
EdgeApi,
AutoApi,
Html,
Data,
}
#[turbo_tasks::value_impl]
impl SsrEntryVc {
#[turbo_tasks::function]
async fn entry(self) -> Result<NodeRenderingEntryVc> {
pub async fn entry(self) -> Result<NodeRenderingEntryVc> {
let this = self.await?;
let entry_asset_page = this.context.process(
this.entry_asset,
......@@ -784,8 +834,8 @@ impl SsrEntryVc {
InnerAssetsVc::cell(inner_assets),
),
chunking_context: this.chunking_context,
intermediate_output_path: this.intermediate_output_path,
output_root: this.output_root,
intermediate_output_path: this.node_path,
output_root: this.node_root,
project_dir: this.project_path,
}
.cell())
......
use anyhow::Result;
use turbo_tasks::{
primitives::{BoolVc, StringsVc},
CompletionVc,
};
use turbo_tasks::{primitives::StringsVc, CompletionVc};
use turbopack_binding::{
turbo::tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemEntryType, FileSystemPathVc},
turbopack::dev_server::source::specificity::SpecificityVc,
};
use crate::next_config::NextConfigVc;
use crate::{embed_js::next_js_file_path, next_config::NextConfigVc};
/// A final route in the pages directory.
#[turbo_tasks::value]
pub enum PagesStructureItem {
Page {
url: FileSystemPathVc,
specificity: SpecificityVc,
page: FileSystemPathVc,
},
Api {
url: FileSystemPathVc,
specificity: SpecificityVc,
api: FileSystemPathVc,
},
pub struct PagesStructureItem {
pub project_path: FileSystemPathVc,
pub next_router_path: FileSystemPathVc,
pub specificity: SpecificityVc,
}
#[turbo_tasks::value_impl]
impl PagesStructureItemVc {
#[turbo_tasks::function]
async fn new(
url: FileSystemPathVc,
project_path: FileSystemPathVc,
next_router_path: FileSystemPathVc,
specificity: SpecificityVc,
file: FileSystemPathVc,
is_api: BoolVc,
) -> Result<Self> {
if *is_api.await? {
Ok(PagesStructureItem::Api {
url,
specificity,
api: file,
}
.cell())
} else {
Ok(PagesStructureItem::Page {
url,
specificity,
page: file,
}
.cell())
Ok(PagesStructureItem {
project_path,
next_router_path,
specificity,
}
.cell())
}
/// Returns a completion that changes when any route in the whole tree
/// changes.
#[turbo_tasks::function]
pub async fn routes_changed(self) -> Result<CompletionVc> {
match *self.await? {
PagesStructureItem::Page { url, .. } => url.await?,
PagesStructureItem::Api { url, .. } => url.await?,
};
let this = self.await?;
this.next_router_path.await?;
Ok(CompletionVc::new())
}
}
......@@ -67,29 +45,40 @@ impl PagesStructureItemVc {
/// folders.
#[turbo_tasks::value]
pub struct PagesStructure {
pub directory: FileSystemPathVc,
pub items: Vec<PagesStructureItemVc>,
pub children: Vec<PagesStructureVc>,
pub app: PagesStructureItemVc,
pub document: PagesStructureItemVc,
pub error: PagesStructureItemVc,
pub api: Option<PagesDirectoryStructureVc>,
pub pages: PagesDirectoryStructureVc,
}
#[turbo_tasks::value_impl]
impl PagesStructureVc {
/// Returns the directory of this structure.
/// Returns the path to the directory of this structure in the project file
/// system.
#[turbo_tasks::function]
pub async fn directory(self) -> Result<FileSystemPathVc> {
Ok(self.await?.directory)
pub async fn project_path(self) -> Result<FileSystemPathVc> {
Ok(self.await?.pages.project_path())
}
/// Returns a completion that changes when any route in the whole tree
/// changes.
#[turbo_tasks::function]
pub async fn routes_changed(self) -> Result<CompletionVc> {
for item in self.await?.items.iter() {
item.routes_changed().await?;
}
for child in self.await?.children.iter() {
child.routes_changed().await?;
let PagesStructure {
ref app,
ref document,
ref error,
ref api,
ref pages,
} = &*self.await?;
app.routes_changed().await?;
document.routes_changed().await?;
error.routes_changed().await?;
if let Some(api) = api {
api.routes_changed().await?;
}
pages.routes_changed().await?;
Ok(CompletionVc::new())
}
}
......@@ -108,47 +97,205 @@ impl OptionPagesStructureVc {
}
}
#[turbo_tasks::value]
pub struct PagesDirectoryStructure {
pub project_path: FileSystemPathVc,
pub next_router_path: FileSystemPathVc,
pub items: Vec<PagesStructureItemVc>,
pub children: Vec<PagesDirectoryStructureVc>,
}
#[turbo_tasks::value_impl]
impl PagesDirectoryStructureVc {
/// Returns the path to the directory of this structure in the project file
/// system.
#[turbo_tasks::function]
pub async fn project_path(self) -> Result<FileSystemPathVc> {
Ok(self.await?.project_path)
}
/// Returns a completion that changes when any route in the whole tree
/// changes.
#[turbo_tasks::function]
pub async fn routes_changed(self) -> Result<CompletionVc> {
for item in self.await?.items.iter() {
item.routes_changed().await?;
}
for child in self.await?.children.iter() {
child.routes_changed().await?;
}
Ok(CompletionVc::new())
}
}
/// Finds and returns the [PagesStructure] of the pages directory if existing.
#[turbo_tasks::function]
pub async fn find_pages_structure(
project_path: FileSystemPathVc,
server_root: FileSystemPathVc,
project_root: FileSystemPathVc,
next_router_root: FileSystemPathVc,
next_config: NextConfigVc,
) -> Result<OptionPagesStructureVc> {
let pages = project_path.join("pages");
let src_pages = project_path.join("src/pages");
let pages_dir = if *pages.get_type().await? == FileSystemEntryType::Directory {
pages
} else if *src_pages.get_type().await? == FileSystemEntryType::Directory {
src_pages
let pages_root = project_root.join("pages");
let pages_root = if *pages_root.get_type().await? == FileSystemEntryType::Directory {
pages_root
} else {
return Ok(OptionPagesStructureVc::cell(None));
let src_pages_root = project_root.join("src/pages");
if *src_pages_root.get_type().await? == FileSystemEntryType::Directory {
src_pages_root
} else {
return Ok(OptionPagesStructureVc::cell(None));
}
}
.resolve()
.await?;
Ok(OptionPagesStructureVc::cell(Some(get_pages_structure(
pages_dir,
server_root,
next_config.page_extensions(),
))))
Ok(OptionPagesStructureVc::cell(Some(
get_pages_structure_for_root_directory(
pages_root,
next_router_root,
next_config.page_extensions(),
),
)))
}
/// Parses a directory as pages directory and returns the [PagesStructure].
/// Handles the root pages directory.
#[turbo_tasks::function]
pub fn get_pages_structure(
pages_dir: FileSystemPathVc,
server_root: FileSystemPathVc,
async fn get_pages_structure_for_root_directory(
project_path: FileSystemPathVc,
next_router_path: FileSystemPathVc,
page_extensions: StringsVc,
) -> PagesStructureVc {
get_pages_structure_for_directory(
pages_dir,
SpecificityVc::exact(),
0,
server_root,
server_root.join("api"),
page_extensions,
)
) -> Result<PagesStructureVc> {
let page_extensions_raw = &*page_extensions.await?;
let mut children = vec![];
let mut items = vec![];
let mut app_item = None;
let mut document_item = None;
let mut error_item = None;
let mut api_directory = None;
let specificity = SpecificityVc::exact();
let dir_content = project_path.read_dir().await?;
if let DirectoryContent::Entries(entries) = &*dir_content {
for (name, entry) in entries.iter() {
match entry {
DirectoryEntry::File(file_project_path) => {
let Some(basename) = page_basename(name, page_extensions_raw) else {
continue;
};
match basename {
"_app" => {
let _ = app_item.insert(PagesStructureItemVc::new(
*file_project_path,
next_router_path.join("_app"),
specificity,
));
}
"_document" => {
let _ = document_item.insert(PagesStructureItemVc::new(
*file_project_path,
next_router_path.join("_document"),
specificity,
));
}
"_error" => {
let _ = error_item.insert(PagesStructureItemVc::new(
*file_project_path,
next_router_path.join("_error"),
specificity,
));
}
basename => {
let specificity = entry_specificity(specificity, name, 0);
let next_router_path =
next_router_path_for_basename(next_router_path, basename);
items.push((
basename,
PagesStructureItemVc::new(
*file_project_path,
next_router_path,
specificity,
),
));
}
}
}
DirectoryEntry::Directory(dir_project_path) => match name.as_ref() {
"api" => {
let _ = api_directory.insert(get_pages_structure_for_directory(
*dir_project_path,
next_router_path.join(name),
specificity,
1,
page_extensions,
));
}
_ => {
let specificity = entry_specificity(SpecificityVc::exact(), name, 0);
children.push((
name,
get_pages_structure_for_directory(
*dir_project_path,
next_router_path.join(name),
specificity,
1,
page_extensions,
),
));
}
},
_ => {}
}
}
}
// Ensure deterministic order since read_dir is not deterministic
items.sort_by_key(|(k, _)| *k);
children.sort_by_key(|(k, _)| *k);
let app_item = if let Some(app_item) = app_item {
app_item
} else {
PagesStructureItemVc::new(
next_js_file_path("entry/pages/_app.tsx"),
next_router_path.join("_app"),
specificity,
)
};
let document_item = if let Some(document_item) = document_item {
document_item
} else {
PagesStructureItemVc::new(
next_js_file_path("entry/pages/_document.tsx"),
next_router_path.join("_document"),
specificity,
)
};
let error_item = if let Some(error_item) = error_item {
error_item
} else {
PagesStructureItemVc::new(
next_js_file_path("entry/pages/_error.tsx"),
next_router_path.join("_error"),
specificity,
)
};
Ok(PagesStructure {
app: app_item,
document: document_item,
error: error_item,
api: api_directory,
pages: PagesDirectoryStructure {
project_path,
next_router_path,
items: items.into_iter().map(|(_, v)| v).collect(),
children: children.into_iter().map(|(_, v)| v).collect(),
}
.cell(),
}
.cell())
}
/// Handles a directory in the pages directory (or the pages directory itself).
......@@ -156,60 +303,46 @@ pub fn get_pages_structure(
/// [create_page_source_for_file] method for files.
#[turbo_tasks::function]
async fn get_pages_structure_for_directory(
input_dir: FileSystemPathVc,
project_path: FileSystemPathVc,
next_router_path: FileSystemPathVc,
specificity: SpecificityVc,
position: u32,
url: FileSystemPathVc,
server_api_path: FileSystemPathVc,
page_extensions: StringsVc,
) -> Result<PagesStructureVc> {
) -> Result<PagesDirectoryStructureVc> {
let page_extensions_raw = &*page_extensions.await?;
let mut children = vec![];
let mut items = vec![];
let dir_content = input_dir.read_dir().await?;
let dir_content = project_path.read_dir().await?;
if let DirectoryContent::Entries(entries) = &*dir_content {
for (name, entry) in entries.iter() {
let specificity = if name.starts_with("[[") || name.starts_with("[...") {
specificity.with_catch_all(position)
} else if name.starts_with('[') {
specificity.with_dynamic_segment(position)
} else {
specificity
};
let specificity = entry_specificity(specificity, name, position);
match entry {
DirectoryEntry::File(file) => {
if let Some((basename, extension)) = name.rsplit_once('.') {
if page_extensions_raw
.iter()
.any(|allowed| allowed == extension)
{
let url = if basename == "index" {
url.join("index.html")
} else {
url.join(basename).join("index.html")
};
items.push((
name,
PagesStructureItemVc::new(
url,
specificity,
*file,
url.is_inside(server_api_path),
),
))
}
}
DirectoryEntry::File(file_project_path) => {
let Some(basename) = page_basename(name, page_extensions_raw) else {
continue;
};
let next_router_path = match basename {
"index" => next_router_path,
_ => next_router_path.join(basename),
};
items.push((
basename,
PagesStructureItemVc::new(
*file_project_path,
next_router_path,
specificity,
),
));
}
DirectoryEntry::Directory(dir) => {
DirectoryEntry::Directory(dir_project_path) => {
children.push((
name,
get_pages_structure_for_directory(
*dir,
*dir_project_path,
next_router_path.join(name),
specificity,
position + 1,
url.join(name),
server_api_path,
page_extensions,
),
));
......@@ -225,10 +358,41 @@ async fn get_pages_structure_for_directory(
// Ensure deterministic order since read_dir is not deterministic
children.sort_by_key(|(k, _)| *k);
Ok(PagesStructure {
directory: input_dir,
Ok(PagesDirectoryStructure {
project_path,
next_router_path,
items: items.into_iter().map(|(_, v)| v).collect(),
children: children.into_iter().map(|(_, v)| v).collect(),
}
.cell())
}
fn entry_specificity(specificity: SpecificityVc, name: &str, position: u32) -> SpecificityVc {
if name.starts_with("[[") || name.starts_with("[...") {
specificity.with_catch_all(position)
} else if name.starts_with('[') {
specificity.with_dynamic_segment(position)
} else {
specificity
}
}
fn page_basename<'a>(name: &'a str, page_extensions: &'a [String]) -> Option<&'a str> {
if let Some((basename, extension)) = name.rsplit_once('.') {
if page_extensions.iter().any(|allowed| allowed == extension) {
return Some(basename);
}
}
None
}
fn next_router_path_for_basename(
next_router_path: FileSystemPathVc,
basename: &str,
) -> FileSystemPathVc {
if basename == "index" {
next_router_path
} else {
next_router_path.join(basename)
}
}
use anyhow::{anyhow, bail, Context, Result};
use anyhow::{bail, Context, Result};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use swc_core::ecma::ast::Program;
use turbo_tasks::{
primitives::{JsonValue, JsonValueVc, StringVc},
trace::TraceRawVcs,
Value, ValueToString,
TaskInput, Value, ValueToString,
};
use turbopack_binding::{
turbo::tasks_fs::{json::parse_json_rope_with_source_context, FileContent, FileSystemPathVc},
......@@ -30,13 +30,18 @@ use turbopack_binding::{
use crate::next_config::{NextConfigVc, OutputType};
#[derive(Debug, Clone, Copy, PartialEq, Eq, TaskInput)]
pub enum PathType {
Page,
Data,
}
/// Converts a filename within the server root into a next pathname.
#[turbo_tasks::function]
pub async fn pathname_for_path(
server_root: FileSystemPathVc,
server_path: FileSystemPathVc,
has_extension: bool,
data: bool,
path_ty: PathType,
) -> Result<StringVc> {
let server_path_value = &*server_path.await?;
let path = if let Some(path) = server_root.await?.get_path_to(server_path_value) {
......@@ -48,19 +53,12 @@ pub async fn pathname_for_path(
server_root.to_string().await?
)
};
let path = if has_extension {
path.rsplit_once('.')
.ok_or_else(|| anyhow!("path ({}) has no extension", path))?
.0
} else {
path
};
// `get_path_to` always strips the leading `/` from the path, so we need to add
// it back here.
let path = if path == "index" && !data {
"/".to_string()
} else {
format!("/{}", path.strip_suffix("/index").unwrap_or(path))
let path = match (path_ty, path) {
// "/" is special-cased to "/index" for data routes.
(PathType::Data, "") => "/index".to_string(),
// `get_path_to` always strips the leading `/` from the path, so we need to add
// it back here.
(_, path) => format!("/{}", path),
};
Ok(StringVc::cell(path))
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/error/ssr/input/pages/broken.tsx",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/externals/cjs-in-esm/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/externals/cjs-in-esm/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
],
),
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/image/basic/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/image/basic/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/image/basic/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
],
),
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/image/basic/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
],
),
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/image/remotepattern/input/pages/invalid.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/tailwind/basic/input/pages/index.jsx",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/tailwind/basic/input/pages/index.jsx",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/tailwind/basic/input/pages/index.jsx",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/tailwind/basic/input/pages/index.jsx",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/tailwind/basic/input/pages/index.jsx",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -28,7 +28,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/tailwind/basic/input/pages/index.jsx",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
],
),
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
],
),
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
PlainIssueProcessingPathItem {
context: Some(
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
],
),
......
......@@ -14,7 +14,7 @@ PlainIssue {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/temp/next/webpack-loaders/emitted-errors/input/pages/index.js",
),
description: "Next.js pages directory",
description: "Next.js page file",
},
],
),
......
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