Unverified Commit 38dafa16 authored by Alex Kirszenberg's avatar Alex Kirszenberg Committed by GitHub

Turbopack: App Router build POC (#52036)

This PR adds proof-of-concept support for the App Router to `next build
--experimental-turbo`.

It introduces a new way to generate Next.js manifests in Turbopack.
Currently, in dev, we pass proxy objects in lieu of manifests, and rely
on the entries to know which chunks they need loaded on the client.
However, this can't work for builds because it requires control over
Next.js rendering, which is not compatible with a Next->Turbo approach.
We would need to modify Next.js to support these "lazy" entries. So for
now, we add well-known assets (`NextDynamicAsset`,
`NextServerComponentAsset`, `NextClientReferenceAsset`, etc.) to the
graph, which will get picked up when walking it during asset processing.
This lets us collect all possible entries before chunking.

This two-step process (collecting all entries, then chunking them) is
also a good first step towards production chunking.

## Turbopack updates

* https://github.com/vercel/turbo/pull/5494 <!-- Tobias Koppers - add
reporting of console messages -->
* https://github.com/vercel/turbo/pull/5448 <!-- Alex Kirszenberg -
Misc. changes to support App Router build -->
parent 4a14671f
This diff is collapsed.
......@@ -42,11 +42,11 @@ swc_core = { version = "0.79.13" }
testing = { version = "0.33.20" }
# Turbo crates
turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-230711.2" }
turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-230712.2" }
# [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-230711.2" }
turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-230712.2" }
# [TODO]: need to refactor embed_directory! macro usage in next-core
turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-230711.2" }
turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-230712.2" }
# General Deps
......@@ -74,6 +74,7 @@ async-compression = { version = "0.3.13", default-features = false, features = [
"gzip",
"tokio",
] }
async-recursion = "1.0.2"
async-trait = "0.1.64"
atty = "0.2.14"
chrono = "0.4.23"
......
......@@ -39,6 +39,7 @@ profile = []
[dependencies]
anyhow = { workspace = true }
async-recursion = { workspace = true }
clap = { workspace = true, features = ["derive", "env"], optional = true }
console-subscriber = { workspace = true, optional = true }
dunce = { workspace = true }
......@@ -48,6 +49,10 @@ serde_json = { workspace = true }
tokio = { workspace = true, features = ["full"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
indoc = { workspace = true }
indexmap = { workspace = true }
mime_guess = "2.0.4"
base64 = "0.21.0"
turbopack-binding = { workspace = true, features = [
"__turbo_tasks",
......
#![feature(type_alias_impl_trait)]
use turbopack_binding::turbo::{
tasks::{run_once, TransientInstance, TurboTasks},
tasks_memory::MemoryBackend,
......@@ -5,6 +7,7 @@ use turbopack_binding::turbo::{
pub mod build_options;
pub mod manifests;
pub(crate) mod next_app;
pub(crate) mod next_build;
pub(crate) mod next_pages;
......
......@@ -110,23 +110,24 @@ pub enum ActionManifestWorkerEntry {
#[derive(Serialize, Default, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceManifest {
/// Mapping of module path and export name to client module ID and required
/// client chunks.
pub client_modules: ManifestNode,
pub ssr_module_mapping: HashMap<String, ManifestNode>,
/// Mapping of client module ID to corresponding SSR module ID and required
/// SSR chunks.
pub ssr_module_mapping: HashMap<ModuleId, ManifestNode>,
/// Same as `ssr_module_mapping`, but for Edge SSR.
#[serde(rename = "edgeSSRModuleMapping")]
pub edge_ssr_module_mapping: HashMap<String, ManifestNode>,
pub css_files: HashMap<String, Vec<String>>,
}
#[derive(Serialize, Default, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ClientCssReferenceManifest {
pub css_imports: HashMap<String, Vec<String>>,
pub css_modules: HashMap<String, Vec<String>>,
pub edge_ssr_module_mapping: HashMap<ModuleId, ManifestNode>,
/// Mapping of server component path to required CSS client chunks.
#[serde(rename = "entryCSSFiles")]
pub entry_css_files: HashMap<String, Vec<String>>,
}
#[derive(Serialize, Default, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ManifestNode {
/// Mapping of export name to manifest node entry.
#[serde(flatten)]
pub module_exports: HashMap<String, ManifestNodeEntry>,
}
......@@ -134,18 +135,22 @@ pub struct ManifestNode {
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ManifestNodeEntry {
/// Turbopack module ID.
pub id: ModuleId,
/// Export name.
pub name: String,
/// Chunks for the module. JS and CSS.
pub chunks: Vec<String>,
// TODO(WEB-434)
pub r#async: bool,
}
#[derive(Serialize, Debug)]
#[derive(Serialize, Debug, Eq, PartialEq, Hash)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum ModuleId {
String(String),
Number(f64),
Number(u64),
}
#[derive(Serialize, Default, Debug)]
......
use std::collections::HashSet;
use anyhow::Result;
use indexmap::IndexMap;
use next_core::{self, next_client_reference::ClientReferenceType};
use turbo_tasks::TryJoinIterExt;
use turbopack_binding::turbopack::{
build::BuildChunkingContextVc,
core::{
asset::{AssetVc, AssetsVc},
chunk::{ChunkableModule, ChunkingContext},
},
ecmascript::chunk::EcmascriptChunkingContextVc,
};
/// Computes all client references chunks, and adds them to the relevant
/// manifests.
///
/// This returns a map from client reference type to the chunks that reference
/// type needs to load.
pub async fn compute_app_client_references_chunks(
app_client_reference_types: &HashSet<ClientReferenceType>,
client_chunking_context: EcmascriptChunkingContextVc,
ssr_chunking_context: BuildChunkingContextVc,
all_chunks: &mut Vec<AssetVc>,
) -> Result<IndexMap<ClientReferenceType, ClientReferenceChunks>> {
let app_client_references_chunks: IndexMap<_, _> = app_client_reference_types
.iter()
.map(|client_reference_ty| async move {
Ok((
*client_reference_ty,
match client_reference_ty {
ClientReferenceType::EcmascriptClientReference(ecmascript_client_reference) => {
let ecmascript_client_reference_ref = ecmascript_client_reference.await?;
let client_entry_chunk = ecmascript_client_reference_ref
.client_module
.as_root_chunk(client_chunking_context.into());
let ssr_entry_chunk = ecmascript_client_reference_ref
.ssr_module
.as_root_chunk(ssr_chunking_context.into());
ClientReferenceChunks {
client_chunks: client_chunking_context.chunk_group(client_entry_chunk),
ssr_chunks: ssr_chunking_context.chunk_group(ssr_entry_chunk),
}
}
ClientReferenceType::CssClientReference(css_client_reference) => {
let css_client_reference_ref = css_client_reference.await?;
let client_entry_chunk = css_client_reference_ref
.client_module
.as_root_chunk(client_chunking_context.into());
ClientReferenceChunks {
client_chunks: client_chunking_context.chunk_group(client_entry_chunk),
ssr_chunks: AssetsVc::empty(),
}
}
},
))
})
.try_join()
.await?
.into_iter()
.collect();
for (app_client_reference_ty, app_client_reference_chunks) in &app_client_references_chunks {
match app_client_reference_ty {
ClientReferenceType::EcmascriptClientReference(_) => {
let client_chunks = &app_client_reference_chunks.client_chunks.await?;
let ssr_chunks = &app_client_reference_chunks.ssr_chunks.await?;
all_chunks.extend(client_chunks.iter().copied());
all_chunks.extend(ssr_chunks.iter().copied());
}
ClientReferenceType::CssClientReference(_) => {
let client_chunks = &app_client_reference_chunks.client_chunks.await?;
all_chunks.extend(client_chunks.iter().copied());
}
}
}
Ok(app_client_references_chunks)
}
/// Contains the chunks corresponding to a client reference.
pub struct ClientReferenceChunks {
/// Chunks to be loaded on the client.
pub client_chunks: AssetsVc,
/// Chunks to be loaded on the server for SSR.
pub ssr_chunks: AssetsVc,
}
use std::io::Write;
use anyhow::{bail, Result};
use indoc::writedoc;
use next_core::{
app_structure::LoaderTreeVc,
loader_tree::{LoaderTreeModule, ServerComponentTransition},
mode::NextMode,
next_server_component::NextServerComponentTransitionVc,
UnsupportedDynamicMetadataIssue,
};
use turbo_tasks::{TryJoinIterExt, Value, ValueToString};
use turbopack_binding::{
turbo::tasks_fs::{rope::RopeBuilder, File, FileSystemPathVc},
turbopack::{
core::{
context::AssetContext,
reference_type::{InnerAssetsVc, ReferenceType},
virtual_source::VirtualSourceVc,
},
ecmascript::{chunk::EcmascriptChunkPlaceableVc, utils::StringifyJs},
turbopack::ModuleAssetContextVc,
},
};
use super::app_entries::{AppEntry, AppEntryVc};
/// Computes the entry for a Next.js app page.
pub(super) async fn get_app_page_entry(
context: ModuleAssetContextVc,
loader_tree: LoaderTreeVc,
app_dir: FileSystemPathVc,
pathname: &str,
project_root: FileSystemPathVc,
) -> Result<AppEntryVc> {
let server_component_transition = NextServerComponentTransitionVc::new().into();
let loader_tree = LoaderTreeModule::build(
loader_tree,
context,
ServerComponentTransition::Transition(server_component_transition),
NextMode::Build,
)
.await?;
let LoaderTreeModule {
inner_assets,
imports,
loader_tree_code,
unsupported_metadata,
pages,
} = loader_tree;
if !unsupported_metadata.is_empty() {
UnsupportedDynamicMetadataIssue {
app_dir,
files: unsupported_metadata,
}
.cell()
.as_issue()
.emit();
}
let mut result = RopeBuilder::default();
for import in imports {
writeln!(result, "{import}")?;
}
let pages = pages.iter().map(|page| page.to_string()).try_join().await?;
// NOTE(alexkirsz) Keep in sync with
// next.js/packages/next/src/build/webpack/loaders/next-app-loader.ts
// TODO(alexkirsz) Support custom global error.
let original_name = get_original_page_name(pathname);
writedoc!(
result,
r#"
export const tree = {loader_tree_code}
export const pages = {pages}
export {{ default as GlobalError }} from 'next/dist/client/components/error-boundary'
export const originalPathname = {pathname}
export const __next_app__ = {{
require: __turbopack_require__,
loadChunk: __turbopack_load__,
}};
export * from 'next/dist/server/app-render/entry-base'
"#,
pages = StringifyJs(&pages),
pathname = StringifyJs(&original_name),
)?;
let file = File::from(result.build());
let source =
// TODO(alexkirsz) Figure out how to name this virtual asset.
VirtualSourceVc::new(project_root.join("todo.tsx"), file.into());
let rsc_entry = context.process(
source.into(),
Value::new(ReferenceType::Internal(InnerAssetsVc::cell(inner_assets))),
);
let Some(rsc_entry) = EcmascriptChunkPlaceableVc::resolve_from(rsc_entry).await? else {
bail!("expected an ECMAScript chunk placeable asset");
};
Ok(AppEntry {
pathname: pathname.to_string(),
original_name,
rsc_entry,
}
.cell())
}
// TODO(alexkirsz) This shouldn't be necessary. The loader tree should keep
// track of this instead.
fn get_original_page_name(pathname: &str) -> String {
match pathname {
"/" => "/page".to_string(),
"/_not-found" => "/_not-found".to_string(),
_ => format!("{}/page", pathname),
}
}
use std::io::Write;
use anyhow::{bail, Result};
use indexmap::indexmap;
use indoc::writedoc;
use serde::Serialize;
use turbo_tasks::{Value, ValueToString};
use turbopack_binding::{
turbo::tasks_fs::{rope::RopeBuilder, File, FileSystemPathVc},
turbopack::{
core::{
asset::Asset,
context::AssetContext,
reference_type::{EcmaScriptModulesReferenceSubType, InnerAssetsVc, ReferenceType},
source::SourceVc,
virtual_source::VirtualSourceVc,
},
ecmascript::{chunk::EcmascriptChunkPlaceableVc, utils::StringifyJs},
turbopack::ModuleAssetContextVc,
},
};
use super::app_entries::{AppEntry, AppEntryVc};
/// Computes the entry for a Next.js app route.
pub(super) async fn get_app_route_entry(
rsc_context: ModuleAssetContextVc,
source: SourceVc,
pathname: &str,
project_root: FileSystemPathVc,
) -> Result<AppEntryVc> {
let mut result = RopeBuilder::default();
let kind = "app-route";
let original_name = get_original_route_name(pathname);
let path = source.ident().path();
let options = AppRouteRouteModuleOptions {
definition: AppRouteRouteDefinition {
kind: RouteKind::AppRoute,
page: original_name.clone(),
pathname: pathname.to_string(),
filename: path.file_stem().await?.as_ref().unwrap().clone(),
// TODO(alexkirsz) Is this necessary?
bundle_path: "".to_string(),
},
resolved_page_path: path.to_string().await?.clone_value(),
// TODO(alexkirsz) Is this necessary?
next_config_output: "".to_string(),
};
// NOTE(alexkirsz) Keep in sync with
// next.js/packages/next/src/build/webpack/loaders/next-app-loader.ts
// TODO(alexkirsz) Support custom global error.
writedoc!(
result,
r#"
import 'next/dist/server/node-polyfill-headers'
import RouteModule from {route_module}
import * as userland from "ENTRY"
const options = {options}
const routeModule = new RouteModule({{
...options,
userland,
}})
// Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route.
const {{
requestAsyncStorage,
staticGenerationAsyncStorage,
serverHooks,
headerHooks,
staticGenerationBailout
}} = routeModule
const originalPathname = {original}
export {{
routeModule,
requestAsyncStorage,
staticGenerationAsyncStorage,
serverHooks,
headerHooks,
staticGenerationBailout,
originalPathname
}}
"#,
route_module = StringifyJs(&format!(
"next/dist/server/future/route-modules/{kind}/module"
)),
options = StringifyJs(&options),
original = StringifyJs(&original_name),
)?;
let file = File::from(result.build());
// TODO(alexkirsz) Figure out how to name this virtual asset.
let virtual_source = VirtualSourceVc::new(project_root.join("todo.tsx"), file.into());
let entry = rsc_context.process(
source,
Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
)),
);
let inner_assets = indexmap! {
"ENTRY".to_string() => entry.into()
};
let rsc_entry = rsc_context.process(
virtual_source.into(),
Value::new(ReferenceType::Internal(InnerAssetsVc::cell(inner_assets))),
);
let Some(rsc_entry) = EcmascriptChunkPlaceableVc::resolve_from(rsc_entry).await? else {
bail!("expected an ECMAScript chunk placeable asset");
};
Ok(AppEntry {
pathname: pathname.to_string(),
original_name,
rsc_entry,
}
.cell())
}
fn get_original_route_name(pathname: &str) -> String {
match pathname {
"/" => "/route".to_string(),
_ => format!("{}/route", pathname),
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct AppRouteRouteModuleOptions {
definition: AppRouteRouteDefinition,
resolved_page_path: String,
next_config_output: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct AppRouteRouteDefinition {
kind: RouteKind,
page: String,
pathname: String,
filename: String,
bundle_path: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum RouteKind {
AppRoute,
}
use std::io::Write;
use anyhow::{bail, Result};
use base64::{display::Base64Display, engine::general_purpose::STANDARD};
use indoc::writedoc;
use next_core::app_structure::MetadataItem;
use turbo_tasks::ValueToString;
use turbopack_binding::{
turbo::tasks_fs::{rope::RopeBuilder, File, FileContent, FileSystemPathVc},
turbopack::{
core::virtual_source::VirtualSourceVc, ecmascript::utils::StringifyJs,
turbopack::ModuleAssetContextVc,
},
};
use super::{app_entries::AppEntryVc, app_route_entry::get_app_route_entry};
/// Computes the entry for a Next.js favicon file.
pub(super) async fn get_app_route_favicon_entry(
rsc_context: ModuleAssetContextVc,
favicon: MetadataItem,
project_root: FileSystemPathVc,
) -> Result<AppEntryVc> {
let path = match favicon {
// TODO(alexkirsz) Is there a difference here?
MetadataItem::Static { path } => path,
MetadataItem::Dynamic { path } => path,
};
let mut code = RopeBuilder::default();
let content_type = mime_guess::from_ext(&path.extension().await?)
.first_or_octet_stream()
.to_string();
let original_file_content = path.read().await?;
let original_file_content_b64 = match &*original_file_content {
FileContent::Content(content) => {
let content = content.content().to_bytes()?;
Base64Display::new(&content, &STANDARD).to_string()
}
FileContent::NotFound => {
bail!("favicon file not found: {}", &path.to_string().await?);
}
};
// Specific to favicon
let cache_control = "public, max-age=0, must-revalidate";
// TODO(alexkirsz) Generalize this to any file.
writedoc! {
code,
r#"
import {{ NextResponse }} from 'next/server'
const contentType = {content_type}
const cacheControl = {cache_control}
const buffer = Buffer.from({original_file_content_b64}, 'base64')
export function GET() {{
return new NextResponse(buffer, {{
headers: {{
'Content-Type': contentType,
'Cache-Control': cacheControl,
}},
}})
}}
export const dynamic = 'force-static'
"#,
content_type = StringifyJs(&content_type),
cache_control = StringifyJs(&cache_control),
original_file_content_b64 = StringifyJs(&original_file_content_b64),
}?;
let file = File::from(code.build());
let source =
// TODO(alexkirsz) Figure out how to name this virtual source.
VirtualSourceVc::new(project_root.join("todo.tsx"), file.into());
get_app_route_entry(
rsc_context,
source.into(),
// TODO(alexkirsz) Get this from the metadata?
"/favicon.ico",
project_root,
)
.await
}
pub(crate) mod app_client_reference;
pub(crate) mod app_entries;
pub(crate) mod app_page_entry;
pub(crate) mod app_route_entry;
pub(crate) mod app_route_favicon_entry;
use anyhow::{bail, Result};
use next_core::{
create_page_loader_entry_asset,
turbopack::core::{asset::AssetsVc, chunk::EvaluatableAssetsVc},
};
use turbopack_binding::{
turbo::{tasks::primitives::StringVc, tasks_fs::FileSystemPathVc},
turbopack::{
core::{
chunk::{ChunkableModule, ChunkingContext, ChunkingContextVc},
context::{AssetContext, AssetContextVc},
source::SourceVc,
},
dev::DevChunkingContextVc,
ecmascript::EcmascriptModuleAssetVc,
},
};
#[turbo_tasks::value]
pub(crate) struct PagesBuildClientContext {
project_root: FileSystemPathVc,
client_root: FileSystemPathVc,
client_asset_context: AssetContextVc,
client_runtime_entries: EvaluatableAssetsVc,
}
#[turbo_tasks::value_impl]
impl PagesBuildClientContextVc {
#[turbo_tasks::function]
pub fn new(
project_root: FileSystemPathVc,
client_root: FileSystemPathVc,
client_asset_context: AssetContextVc,
client_runtime_entries: EvaluatableAssetsVc,
) -> PagesBuildClientContextVc {
PagesBuildClientContext {
project_root,
client_root,
client_asset_context,
client_runtime_entries,
}
.cell()
}
#[turbo_tasks::function]
async fn client_chunking_context(self) -> Result<ChunkingContextVc> {
let this = self.await?;
Ok(DevChunkingContextVc::builder(
this.project_root,
this.client_root,
this.client_root.join("static/chunks"),
this.client_root.join("static/media"),
this.client_asset_context.compile_time_info().environment(),
)
.build())
}
#[turbo_tasks::function]
pub async fn client_chunk(self, source: SourceVc, pathname: StringVc) -> Result<AssetsVc> {
let this = self.await?;
let client_asset_page =
create_page_loader_entry_asset(this.client_asset_context, source, pathname);
let Some(client_module_asset) =
EcmascriptModuleAssetVc::resolve_from(client_asset_page).await?
else {
bail!("Expected an EcmaScript module asset");
};
let client_chunking_context = self.client_chunking_context();
Ok(client_chunking_context.evaluated_chunk_group(
client_module_asset.as_root_chunk(client_chunking_context),
this.client_runtime_entries
.with_entry(client_module_asset.into()),
))
}
}
pub(crate) mod client_context;
pub(crate) mod node_context;
pub(crate) mod page_chunks;
pub(crate) mod page_entries;
use anyhow::{bail, Result};
use next_core::{next_client::RuntimeEntriesVc, turbopack::core::chunk::EvaluatableAssetsVc};
use turbo_tasks::primitives::StringVc;
use turbopack_binding::{
turbo::{tasks::Value, tasks_fs::FileSystemPathVc},
turbopack::{
build::BuildChunkingContextVc,
core::{
asset::AssetVc,
context::{AssetContext, AssetContextVc},
reference_type::{EntryReferenceSubType, ReferenceType},
resolve::{parse::RequestVc, pattern::QueryMapVc},
source::SourceVc,
},
ecmascript::chunk::EcmascriptChunkPlaceableVc,
},
};
#[turbo_tasks::value]
pub(crate) struct PagesBuildNodeContext {
project_root: FileSystemPathVc,
node_root: FileSystemPathVc,
node_asset_context: AssetContextVc,
node_runtime_entries: EvaluatableAssetsVc,
}
#[turbo_tasks::value_impl]
impl PagesBuildNodeContextVc {
#[turbo_tasks::function]
pub fn new(
project_root: FileSystemPathVc,
node_root: FileSystemPathVc,
node_asset_context: AssetContextVc,
node_runtime_entries: RuntimeEntriesVc,
) -> PagesBuildNodeContextVc {
PagesBuildNodeContext {
project_root,
node_root,
node_asset_context,
node_runtime_entries: node_runtime_entries.resolve_entries(node_asset_context),
}
.cell()
}
#[turbo_tasks::function]
pub async fn resolve_module(
self,
origin: FileSystemPathVc,
package: String,
path: String,
) -> Result<AssetVc> {
let this = self.await?;
let Some(asset) = this
.node_asset_context
.resolve_asset(
origin,
RequestVc::module(
package.clone(),
Value::new(path.clone().into()),
QueryMapVc::none(),
),
this.node_asset_context.resolve_options(
origin,
Value::new(ReferenceType::Entry(EntryReferenceSubType::Page)),
),
Value::new(ReferenceType::Entry(EntryReferenceSubType::Page)),
)
.primary_assets()
.await?
.first()
.copied()
else {
bail!("module {}/{} not found in {}", package, path, origin.await?);
};
Ok(asset)
}
#[turbo_tasks::function]
async fn node_chunking_context(self) -> Result<BuildChunkingContextVc> {
let this = self.await?;
Ok(BuildChunkingContextVc::builder(
this.project_root,
this.node_root,
this.node_root.join("server/pages"),
this.node_root.join("server/assets"),
this.node_asset_context.compile_time_info().environment(),
)
.build())
}
#[turbo_tasks::function]
pub async fn node_chunk(
self,
source: SourceVc,
original_path: StringVc,
reference_type: Value<ReferenceType>,
) -> Result<AssetVc> {
let this = self.await?;
let node_asset_page = this.node_asset_context.process(source, reference_type);
let Some(node_module_asset) =
EcmascriptChunkPlaceableVc::resolve_from(node_asset_page).await?
else {
bail!("Expected an EcmaScript module asset");
};
let original_path = original_path.await?;
let chunking_context = self.node_chunking_context();
Ok(chunking_context.generate_entry_chunk(
this.node_root
.join(&format!("server/pages/{original_path}.js")),
node_module_asset,
this.node_runtime_entries,
))
}
}
......@@ -10,7 +10,7 @@ bench = false
[dependencies]
anyhow = { workspace = true }
async-recursion = "1.0.2"
async-recursion = { workspace = true }
async-trait = { workspace = true }
const_format = "0.2.30"
once_cell = { workspace = true }
......@@ -36,6 +36,7 @@ turbopack-binding = { workspace = true, features = [
"__turbo_tasks_fs",
"__turbo_tasks_hash",
"__turbopack",
"__turbopack_build",
"__turbopack_core",
"__turbopack_dev",
"__turbopack_dev_server",
......
......@@ -10,8 +10,8 @@
"check": "tsc --noEmit"
},
"dependencies": {
"@vercel/turbopack-ecmascript-runtime": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-230711.2",
"@vercel/turbopack-node": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230711.2",
"@vercel/turbopack-ecmascript-runtime": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-230712.2",
"@vercel/turbopack-node": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230712.2",
"anser": "^2.1.1",
"css.escape": "^1.5.1",
"next": "*",
......
/**
* This is the runtime entry point for Next.js App Router client-side bundles.
*/
import './shims'
import 'next/dist/client/app-next'
/**
* This is the runtime entry point for Next.js App Router server-side bundles.
*/
import '../shims'
declare module 'CLIENT_MODULE' {
export const __turbopack_module_id__: string
}
declare module 'CLIENT_CHUNKS' {
const moduleId: string
export default moduleId
export const chunks: any[]
}
/// <reference path="./server-to-client-ssr.d.ts" />
import { createProxy } from 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
;('TURBOPACK { chunking-type: isolatedParallel }')
import { __turbopack_module_id__ as id } from 'CLIENT_MODULE'
......
declare module 'CLIENT_CHUNKS' {
const moduleId: string
export default moduleId
export const chunks: any[]
}
/// <reference path="./server-to-client.d.ts" />
import { createProxy } from 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
import client_id, { chunks } from 'CLIENT_CHUNKS'
......
......@@ -90,14 +90,3 @@ declare module 'APP_ENTRY' {
export const pathname: string
// and more...
}
declare module 'CLIENT_MODULE' {
export const __turbopack_module_id__: string
}
declare module 'CLIENT_CHUNKS' {
const moduleId: string
export default moduleId
export const chunks: any[]
}
......@@ -469,10 +469,6 @@ fn match_parallel_route(name: &str) -> Option<&str> {
name.strip_prefix('@')
}
fn is_optional_segment(name: &str) -> bool {
name.starts_with('(') && name.ends_with(')')
}
async fn add_parallel_route(
app_dir: FileSystemPathVc,
result: &mut IndexMap<String, LoaderTreeVc>,
......@@ -660,14 +656,38 @@ async fn directory_tree_to_entrypoints_internal(
add_app_route(app_dir, &mut result, path_prefix.to_string(), route).await?;
}
if path_prefix == "/" {
// Next.js has this logic in "collect-app-paths", where the root not-found page
// is considered as its own entry point.
if let Some(_not_found) = components.not_found {
add_app_page(
app_dir,
&mut result,
"/_not-found".to_string(),
LoaderTree {
segment: directory_name.to_string(),
parallel_routes: indexmap! {
// TODO(alexkirsz) Next.js has a __DEFAULT__ entry for
// next/dist/client/components/parallel-route-default
// here.
},
components: components.without_leafs().cell(),
}
.cell(),
)
.await?;
}
}
for (subdir_name, &subdirectory) in subdirectories.iter() {
let parallel_route_key = match_parallel_route(subdir_name);
let optional_segment = is_optional_segment(subdir_name);
let map = directory_tree_to_entrypoints_internal(
app_dir,
subdir_name,
subdirectory,
if parallel_route_key.is_some() || optional_segment {
// TODO(alexkirsz) We don't check optional segment here because Next.js seems to expect
// it, although this might just need to be computed as "original name".
if parallel_route_key.is_some() {
Cow::Borrowed(path_prefix)
} else if path_prefix == "/" {
format!("/{subdir_name}").into()
......
......@@ -55,6 +55,7 @@ pub async fn get_fallback_page(
project_path,
dev_server_root,
client_compile_time_info.environment(),
mode,
);
let entries =
get_client_runtime_entries(project_path, env, ty, mode, next_config, execution_context);
......@@ -95,7 +96,7 @@ pub async fn get_fallback_page(
dev_server_root.join("fallback.html"),
vec![(
module.into(),
chunking_context,
chunking_context.into(),
Some(runtime_entries.with_entry(module.into())),
)],
))
......
// TODO(alexkirsz) Remove once the diagnostic is fixed.
#![allow(rustc::untranslatable_diagnostic_trivial)]
#![feature(async_closure)]
#![feature(min_specialization)]
#![feature(str_split_remainder)]
#![feature(impl_trait_in_assoc_type)]
mod app_render;
mod app_segment_config;
......@@ -13,19 +13,24 @@ mod bootstrap;
mod embed_js;
pub mod env;
mod fallback;
pub mod loader_tree;
pub mod manifest;
pub mod mode;
pub(crate) mod next_app;
mod next_build;
pub mod next_client;
pub mod next_client_chunks;
mod next_client_component;
pub mod next_client_reference;
pub mod next_config;
pub mod next_dynamic;
mod next_edge;
mod next_font;
pub mod next_image;
mod next_import_map;
mod next_route_matcher;
pub mod next_server;
pub mod next_server_component;
pub mod next_shared;
mod page_loader;
mod page_source;
......@@ -40,10 +45,13 @@ mod util;
mod web_entry_source;
pub use app_source::create_app_source;
pub use page_loader::create_page_loader_entry_asset;
pub use next_app::unsupported_dynamic_metadata_issue::{
UnsupportedDynamicMetadataIssue, UnsupportedDynamicMetadataIssueVc,
};
pub use page_loader::create_page_loader_entry_module;
pub use page_source::create_page_source;
pub use turbopack_binding::{turbopack::node::source_map, *};
pub use util::{pathname_for_path, PathType};
pub use util::{get_asset_path_from_pathname, pathname_for_path, PathType};
pub use web_entry_source::create_web_entry_source;
pub fn register() {
......
This diff is collapsed.
use turbo_tasks::TaskInput;
use serde::{Deserialize, Serialize};
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, TaskInput};
/// The mode in which Next.js is running.
#[derive(Debug, Copy, Clone, TaskInput)]
#[derive(
Debug,
Copy,
Clone,
TaskInput,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
Serialize,
Deserialize,
TraceRawVcs,
ValueDebugFormat,
)]
pub enum NextMode {
/// `next dev`
Development,
......
pub(crate) mod unsupported_dynamic_metadata_issue;
use anyhow::Result;
use turbo_tasks::{primitives::StringVc, TryJoinIterExt, ValueToString};
use turbo_tasks_fs::FileSystemPathVc;
use turbopack_binding::turbopack::{
core::issue::{Issue, IssueSeverity, IssueSeverityVc, IssueVc},
ecmascript::utils::FormatIter,
};
#[turbo_tasks::value(shared)]
pub struct UnsupportedDynamicMetadataIssue {
pub app_dir: FileSystemPathVc,
pub files: Vec<FileSystemPathVc>,
}
#[turbo_tasks::value_impl]
impl Issue for UnsupportedDynamicMetadataIssue {
#[turbo_tasks::function]
fn severity(&self) -> IssueSeverityVc {
IssueSeverity::Warning.into()
}
#[turbo_tasks::function]
fn category(&self) -> StringVc {
StringVc::cell("unsupported".to_string())
}
#[turbo_tasks::function]
fn context(&self) -> FileSystemPathVc {
self.app_dir
}
#[turbo_tasks::function]
fn title(&self) -> StringVc {
StringVc::cell(
"Dynamic metadata from filesystem is currently not supported in Turbopack".to_string(),
)
}
#[turbo_tasks::function]
async fn description(&self) -> Result<StringVc> {
let mut files = self
.files
.iter()
.map(|file| file.to_string())
.try_join()
.await?;
files.sort();
Ok(StringVc::cell(format!(
"The following files were found in the app directory, but are not supported by \
Turbopack. They are ignored:\n{}",
FormatIter(|| files.iter().flat_map(|file| vec!["\n- ", file]))
)))
}
}
use core::{default::Default, result::Result::Ok};
use std::collections::HashMap;
use anyhow::Result;
use turbo_tasks::{primitives::StringVc, Value};
use turbo_tasks::{
primitives::{OptionStringVc, StringVc},
Value,
};
use turbo_tasks_fs::FileSystem;
use turbopack_binding::{
turbo::{tasks_env::ProcessEnvVc, tasks_fs::FileSystemPathVc},
turbopack::{
core::{
chunk::ChunkingContextVc,
compile_time_defines,
compile_time_info::{
CompileTimeDefines, CompileTimeDefinesVc, CompileTimeInfo, CompileTimeInfoVc,
FreeVarReference, FreeVarReferencesVc,
},
context::AssetContextVc,
environment::{BrowserEnvironment, EnvironmentVc, ExecutionEnvironment},
free_var_references,
resolve::{parse::RequestVc, pattern::Pattern},
},
dev::{react_refresh::assert_can_resolve_react_refresh, DevChunkingContextVc},
ecmascript::TransformPluginVc,
ecmascript::{chunk::EcmascriptChunkingContextVc, TransformPluginVc},
ecmascript_plugin::transform::directives::server::ServerDirectiveTransformer,
env::ProcessEnvAssetVc,
node::execution_context::ExecutionContextVc,
......@@ -33,8 +33,6 @@ use turbopack_binding::{
TypescriptTransformOptions, WebpackLoadersOptions,
},
resolve_options_context::{ResolveOptionsContext, ResolveOptionsContextVc},
transition::TransitionsByNameVc,
ModuleAssetContextVc,
},
},
};
......@@ -175,7 +173,7 @@ pub async fn get_client_module_options_context(
mode: NextMode,
next_config: NextConfigVc,
) -> Result<ModuleOptionsContextVc> {
let custom_rules = get_next_client_transforms_rules(next_config, ty.into_value()).await?;
let custom_rules = get_next_client_transforms_rules(next_config, ty.into_value(), mode).await?;
let resolve_options_context =
get_client_resolve_options_context(project_path, ty, mode, next_config, execution_context);
......@@ -280,57 +278,34 @@ pub async fn get_client_module_options_context(
Ok(module_options_context)
}
#[turbo_tasks::function]
pub fn get_client_asset_context(
project_path: FileSystemPathVc,
execution_context: ExecutionContextVc,
compile_time_info: CompileTimeInfoVc,
ty: Value<ClientContextType>,
mode: NextMode,
next_config: NextConfigVc,
) -> AssetContextVc {
let resolve_options_context =
get_client_resolve_options_context(project_path, ty, mode, next_config, execution_context);
let module_options_context = get_client_module_options_context(
project_path,
execution_context,
compile_time_info.environment(),
ty,
mode,
next_config,
);
let context: AssetContextVc = ModuleAssetContextVc::new(
TransitionsByNameVc::cell(HashMap::new()),
compile_time_info,
module_options_context,
resolve_options_context,
)
.into();
context
}
#[turbo_tasks::function]
pub fn get_client_chunking_context(
project_path: FileSystemPathVc,
client_root: FileSystemPathVc,
environment: EnvironmentVc,
) -> ChunkingContextVc {
DevChunkingContextVc::builder(
mode: NextMode,
) -> EcmascriptChunkingContextVc {
let builder = DevChunkingContextVc::builder(
project_path,
client_root,
client_root.join("/_next/static/chunks"),
client_root.join("_next/static/chunks"),
get_client_assets_path(client_root),
environment,
)
.hot_module_replacement()
.build()
);
let builder = match mode {
NextMode::Development => builder.hot_module_replacement(),
NextMode::Build => {
builder.chunk_base_path(OptionStringVc::cell(Some("_next/".to_string())))
}
};
builder.build().into()
}
#[turbo_tasks::function]
pub fn get_client_assets_path(client_root: FileSystemPathVc) -> FileSystemPathVc {
client_root.join("/_next/static/media")
client_root.join("_next/static/media")
}
#[turbo_tasks::function]
......@@ -377,17 +352,31 @@ pub async fn get_client_runtime_entries(
runtime_entries.push(RuntimeEntry::Request(request, project_root.join("_")).cell())
};
}
NextMode::Build => {
runtime_entries.push(
RuntimeEntry::Request(
RequestVc::parse(Value::new(Pattern::Constant(
"./build/client/bootstrap.ts".to_string(),
))),
next_js_fs().root().join("_"),
)
.cell(),
);
}
NextMode::Build => match *ty {
ClientContextType::App { .. } => {
runtime_entries.push(
RuntimeEntry::Request(
RequestVc::parse(Value::new(Pattern::Constant(
"./build/client/app-bootstrap.ts".to_string(),
))),
next_js_fs().root().join("_"),
)
.cell(),
);
}
ClientContextType::Pages { .. } => {
runtime_entries.push(
RuntimeEntry::Request(
RequestVc::parse(Value::new(Pattern::Constant(
"./build/client/bootstrap.ts".to_string(),
))),
next_js_fs().root().join("_"),
)
.cell(),
);
}
_ => {}
},
}
Ok(RuntimeEntriesVc::cell(runtime_entries))
......
......@@ -4,7 +4,7 @@ pub(crate) mod transforms;
pub(crate) mod transition;
pub use context::{
get_client_compile_time_info, get_client_module_options_context,
get_client_chunking_context, get_client_compile_time_info, get_client_module_options_context,
get_client_resolve_options_context, get_client_runtime_entries, ClientContextType,
};
pub use runtime_entry::{RuntimeEntries, RuntimeEntriesVc, RuntimeEntry, RuntimeEntryVc};
......
......@@ -3,6 +3,7 @@ use next_transform_strip_page_exports::ExportFilter;
use turbopack_binding::turbopack::turbopack::module_options::ModuleRule;
use crate::{
mode::NextMode,
next_client::context::ClientContextType,
next_config::NextConfigVc,
next_shared::transforms::{
......@@ -16,6 +17,7 @@ use crate::{
pub async fn get_next_client_transforms_rules(
next_config: NextConfigVc,
context_ty: ClientContextType,
mode: NextMode,
) -> Result<Vec<ModuleRule>> {
let mut rules = vec![];
......@@ -38,7 +40,7 @@ pub async fn get_next_client_transforms_rules(
}
};
rules.push(get_next_dynamic_transform_rule(true, false, false, pages_dir).await?);
rules.push(get_next_dynamic_transform_rule(false, false, pages_dir, mode).await?);
rules.push(get_next_image_rule());
......
......@@ -3,7 +3,8 @@ use turbo_tasks::Value;
use turbopack_binding::{
turbo::tasks_fs::FileSystemPathVc,
turbopack::{
core::{chunk::ChunkingContextVc, compile_time_info::CompileTimeInfoVc, module::ModuleVc},
core::{compile_time_info::CompileTimeInfoVc, module::ModuleVc},
ecmascript::chunk::EcmascriptChunkingContextVc,
node::execution_context::ExecutionContextVc,
turbopack::{
ecmascript::chunk::EcmascriptChunkPlaceableVc,
......@@ -15,12 +16,11 @@ use turbopack_binding::{
},
};
use super::with_chunks::WithChunksAsset;
use super::with_chunks::WithChunksAssetVc;
use crate::{
mode::NextMode,
next_client::context::{
get_client_chunking_context, get_client_module_options_context,
get_client_resolve_options_context, ClientContextType,
get_client_module_options_context, get_client_resolve_options_context, ClientContextType,
},
next_config::NextConfigVc,
};
......@@ -30,8 +30,7 @@ pub struct NextClientChunksTransition {
pub client_compile_time_info: CompileTimeInfoVc,
pub client_module_options_context: ModuleOptionsContextVc,
pub client_resolve_options_context: ResolveOptionsContextVc,
pub client_chunking_context: ChunkingContextVc,
pub server_root: FileSystemPathVc,
pub client_chunking_context: EcmascriptChunkingContextVc,
}
#[turbo_tasks::value_impl]
......@@ -42,16 +41,10 @@ impl NextClientChunksTransitionVc {
execution_context: ExecutionContextVc,
ty: Value<ClientContextType>,
mode: NextMode,
server_root: FileSystemPathVc,
client_chunking_context: EcmascriptChunkingContextVc,
client_compile_time_info: CompileTimeInfoVc,
next_config: NextConfigVc,
) -> NextClientChunksTransitionVc {
let client_chunking_context = get_client_chunking_context(
project_path,
server_root,
client_compile_time_info.environment(),
);
let client_module_options_context = get_client_module_options_context(
project_path,
execution_context,
......@@ -71,7 +64,6 @@ impl NextClientChunksTransitionVc {
execution_context,
),
client_compile_time_info,
server_root,
}
.cell()
}
......@@ -111,12 +103,7 @@ impl Transition for NextClientChunksTransition {
) -> Result<ModuleVc> {
Ok(
if let Some(placeable) = EcmascriptChunkPlaceableVc::resolve_from(asset).await? {
WithChunksAsset {
asset: placeable,
chunking_context: self.client_chunking_context,
}
.cell()
.into()
WithChunksAssetVc::new(placeable, self.client_chunking_context).into()
} else {
asset
},
......
use std::io::Write;
use anyhow::{bail, Result};
use anyhow::Result;
use indoc::writedoc;
use turbopack_binding::{
turbo::{
......@@ -36,10 +36,42 @@ fn modifier() -> StringVc {
StringVc::cell("chunks".to_string())
}
#[turbo_tasks::value(shared)]
#[turbo_tasks::value]
pub struct WithChunksAsset {
pub asset: EcmascriptChunkPlaceableVc,
pub chunking_context: ChunkingContextVc,
asset: EcmascriptChunkPlaceableVc,
chunking_context: EcmascriptChunkingContextVc,
}
#[turbo_tasks::value_impl]
impl WithChunksAssetVc {
/// Create a new [`WithChunksAsset`].
///
/// # Arguments
///
/// * `asset` - The asset to wrap.
/// * `chunking_context` - The chunking context of the asset.
#[turbo_tasks::function]
pub fn new(
asset: EcmascriptChunkPlaceableVc,
chunking_context: EcmascriptChunkingContextVc,
) -> WithChunksAssetVc {
WithChunksAssetVc::cell(WithChunksAsset {
asset,
chunking_context,
})
}
#[turbo_tasks::function]
async fn entry_chunk(self) -> Result<ChunkVc> {
let this = self.await?;
Ok(this.asset.as_root_chunk(this.chunking_context.into()))
}
#[turbo_tasks::function]
async fn chunks(self) -> Result<AssetsVc> {
let this = self.await?;
Ok(this.chunking_context.chunk_group(self.entry_chunk()))
}
}
#[turbo_tasks::value_impl]
......@@ -60,7 +92,7 @@ impl Asset for WithChunksAsset {
let entry_chunk = self_vc.entry_chunk();
Ok(AssetReferencesVc::cell(vec![ChunkGroupReferenceVc::new(
this.chunking_context,
this.chunking_context.into(),
entry_chunk,
)
.into()]))
......@@ -109,21 +141,6 @@ impl EcmascriptChunkPlaceable for WithChunksAsset {
}
}
#[turbo_tasks::value_impl]
impl WithChunksAssetVc {
#[turbo_tasks::function]
async fn entry_chunk(self) -> Result<ChunkVc> {
let this = self.await?;
Ok(this.asset.as_root_chunk(this.chunking_context))
}
#[turbo_tasks::function]
async fn chunks(self) -> Result<AssetsVc> {
let this = self.await?;
Ok(this.chunking_context.chunk_group(self.entry_chunk()))
}
}
#[turbo_tasks::value]
struct WithChunksChunkItem {
context: EcmascriptChunkingContextVc,
......@@ -136,13 +153,8 @@ impl WithChunksChunkItemVc {
async fn chunks_data(self) -> Result<ChunksDataVc> {
let this = self.await?;
let inner = this.inner.await?;
let Some(inner_chunking_context) =
EcmascriptChunkingContextVc::resolve_from(inner.chunking_context).await?
else {
bail!("the chunking context is not an EcmascriptChunkingContextVc");
};
Ok(ChunkDataVc::from_assets(
inner_chunking_context.output_root(),
inner.chunking_context.output_root(),
this.inner.chunks(),
))
}
......@@ -159,11 +171,6 @@ impl EcmascriptChunkItem for WithChunksChunkItem {
async fn content(self_vc: WithChunksChunkItemVc) -> Result<EcmascriptChunkItemContentVc> {
let this = self_vc.await?;
let inner = this.inner.await?;
let Some(inner_chunking_context) =
EcmascriptChunkingContextVc::resolve_from(inner.chunking_context).await?
else {
bail!("the chunking context is not an EcmascriptChunkingContextVc");
};
let chunks_data = self_vc.chunks_data().await?;
let chunks_data = chunks_data.iter().try_join().await?;
......@@ -174,7 +181,7 @@ impl EcmascriptChunkItem for WithChunksChunkItem {
let module_id = &*inner
.asset
.as_chunk_item(inner_chunking_context)
.as_chunk_item(inner.chunking_context)
.id()
.await?;
......
......@@ -30,11 +30,7 @@ impl Transition for NextServerToClientTransition {
context: ModuleAssetContextVc,
_reference_type: Value<ReferenceType>,
) -> Result<ModuleVc> {
let internal_source = next_asset(if self_vc.await?.ssr {
"entry/app/server-to-client-ssr.tsx"
} else {
"entry/app/server-to-client.tsx"
});
let this = self_vc.await?;
let context = self_vc.process_context(context);
let client_chunks = context.with_transition("next-client-chunks").process(
source,
......@@ -42,18 +38,33 @@ impl Transition for NextServerToClientTransition {
EntryReferenceSubType::AppClientComponent,
)),
);
let client_module = context.with_transition("next-ssr-client-module").process(
source,
Value::new(ReferenceType::Entry(
EntryReferenceSubType::AppClientComponent,
)),
);
Ok(context.process(
internal_source,
Value::new(ReferenceType::Internal(InnerAssetsVc::cell(indexmap! {
"CLIENT_MODULE".to_string() => client_module.into(),
"CLIENT_CHUNKS".to_string() => client_chunks.into(),
}))),
))
Ok(match this.ssr {
true => {
let internal_source = next_asset("entry/app/server-to-client-ssr.tsx");
let client_module = context.with_transition("next-ssr-client-module").process(
source,
Value::new(ReferenceType::Entry(
EntryReferenceSubType::AppClientComponent,
)),
);
context.process(
internal_source,
Value::new(ReferenceType::Internal(InnerAssetsVc::cell(indexmap! {
"CLIENT_MODULE".to_string() => client_module.into(),
"CLIENT_CHUNKS".to_string() => client_chunks.into(),
}))),
)
}
false => {
let internal_source = next_asset("entry/app/server-to-client.tsx");
context.process(
internal_source,
Value::new(ReferenceType::Internal(InnerAssetsVc::cell(indexmap! {
"CLIENT_CHUNKS".to_string() => client_chunks.into(),
}))),
)
}
})
}
}
use anyhow::{bail, Result};
use turbo_tasks::primitives::StringVc;
use turbopack_binding::turbopack::{
core::{
asset::{Asset, AssetContentVc, AssetVc},
ident::AssetIdentVc,
module::{Module, ModuleVc},
reference::AssetReferencesVc,
},
turbopack::css::{chunk::CssChunkPlaceableVc, ParseCss, ParseCssResultVc, ParseCssVc},
};
/// A [`CssClientReferenceModule`] is a marker module used to indicate which
/// client reference should appear in the client reference manifest.
#[turbo_tasks::value(transparent)]
pub struct CssClientReferenceModule {
pub client_module: CssChunkPlaceableVc,
}
#[turbo_tasks::value_impl]
impl CssClientReferenceModuleVc {
/// Create a new [`CssClientReferenceModule`] from the given source CSS
/// module.
#[turbo_tasks::function]
pub fn new(client_module: CssChunkPlaceableVc) -> CssClientReferenceModuleVc {
CssClientReferenceModule { client_module }.cell()
}
}
#[turbo_tasks::function]
fn css_client_reference_modifier() -> StringVc {
StringVc::cell("css client reference".to_string())
}
#[turbo_tasks::value_impl]
impl Asset for CssClientReferenceModule {
#[turbo_tasks::function]
fn ident(&self) -> AssetIdentVc {
self.client_module
.ident()
.with_modifier(css_client_reference_modifier())
}
#[turbo_tasks::function]
fn content(&self) -> Result<AssetContentVc> {
// The client reference asset only serves as a marker asset.
bail!("CssClientReferenceModule has no content")
}
#[turbo_tasks::function]
fn references(_self_vc: CssClientReferenceModuleVc) -> AssetReferencesVc {
AssetReferencesVc::empty()
}
}
#[turbo_tasks::value_impl]
impl ParseCss for CssClientReferenceModule {
#[turbo_tasks::function]
async fn parse_css(&self) -> Result<ParseCssResultVc> {
let Some(parse_css) = ParseCssVc::resolve_from(self.client_module).await? else {
bail!("CSS client reference client module must be CSS parseable");
};
Ok(parse_css.parse_css())
}
}
#[turbo_tasks::value_impl]
impl Module for CssClientReferenceModule {}
use anyhow::{bail, Result};
use turbo_tasks::Value;
use turbopack_binding::turbopack::{
core::{
module::ModuleVc,
reference_type::{CssReferenceSubType, ReferenceType},
resolve::ModulePartVc,
source::SourceVc,
},
turbopack::{
css::chunk::CssChunkPlaceableVc,
module_options::{CustomModuleType, CustomModuleTypeVc},
transition::{Transition, TransitionVc},
ModuleAssetContextVc,
},
};
use super::css_client_reference_module::CssClientReferenceModuleVc;
/// Module type for CSS client references. This will be used to hook into CSS
/// asset processing and inject a client reference on the server side.
#[turbo_tasks::value]
pub struct CssClientReferenceModuleType {
client_transition: TransitionVc,
}
#[turbo_tasks::value_impl]
impl CssClientReferenceModuleTypeVc {
#[turbo_tasks::function]
pub fn new(client_transition: TransitionVc) -> Self {
CssClientReferenceModuleType { client_transition }.cell()
}
}
#[turbo_tasks::value_impl]
impl CustomModuleType for CssClientReferenceModuleType {
#[turbo_tasks::function]
async fn create_module(
&self,
source: SourceVc,
context: ModuleAssetContextVc,
_part: Option<ModulePartVc>,
) -> Result<ModuleVc> {
let client_module = self.client_transition.process(
source,
context,
Value::new(ReferenceType::Css(CssReferenceSubType::Internal)),
);
let Some(client_module) = CssChunkPlaceableVc::resolve_from(&client_module).await? else {
bail!("client asset is not CSS chunk placeable");
};
Ok(CssClientReferenceModuleVc::new(client_module).into())
}
}
pub(crate) mod css_client_reference_module;
pub(crate) mod css_client_reference_module_type;
pub(crate) mod css_client_reference_rule;
pub(crate) mod ecmascript_client_reference_module;
pub(crate) mod ecmascript_client_reference_proxy_module;
pub(crate) mod ecmascript_client_reference_transition;
pub(crate) mod css_client_reference;
pub(crate) mod ecmascript_client_reference;
pub(crate) mod visit_client_reference;
pub use css_client_reference::css_client_reference_module::CssClientReferenceModuleVc;
pub use ecmascript_client_reference::{
ecmascript_client_reference_module::EcmascriptClientReferenceModuleVc,
ecmascript_client_reference_transition::NextEcmascriptClientReferenceTransitionVc,
};
pub use visit_client_reference::{
ClientReference, ClientReferenceType, ClientReferencesByEntry, ClientReferencesByEntryVc,
};
pub(crate) mod dynamic_module;
pub(crate) mod dynamic_transition;
pub(crate) mod visit_dynamic;
pub use dynamic_module::NextDynamicEntryModuleVc;
pub use dynamic_transition::NextDynamicTransitionVc;
pub use visit_dynamic::NextDynamicEntriesVc;
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment