Unverified Commit 4ff11d06 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Turbopack: Implement `next/font/local` with `BeforeResolvePlugin` and show…

Turbopack: Implement `next/font/local` with `BeforeResolvePlugin` and show custom error message (#65870)

Depends on vercel/turbo#8165

This:
- Creates and uses a `BeforeResolvePlugin` to handle requests to
`next/font/local/target.css` instead of `ImportMapping` replacers
- Returns a `ResolveResultItem::Error` which includes a custom
`StyledString` describing the missing font file

Test Plan: `TURBOPACK=1 pnpm test-dev
test/e2e/app-dir/next-font/next-font.test.ts`
parent 325a4906
This diff is collapsed.
...@@ -37,11 +37,11 @@ swc_core = { version = "0.92.5", features = [ ...@@ -37,11 +37,11 @@ swc_core = { version = "0.92.5", features = [
testing = { version = "0.35.24" } testing = { version = "0.35.24" }
# Turbo crates # Turbo crates
turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240517.2" } turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240520.2" }
# [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-240517.2" } turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240520.2" }
# [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-240517.2" } turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240520.2" }
# General Deps # General Deps
......
...@@ -41,6 +41,7 @@ use crate::{ ...@@ -41,6 +41,7 @@ use crate::{
next_build::get_postcss_package_mapping, next_build::get_postcss_package_mapping,
next_client::runtime_entry::{RuntimeEntries, RuntimeEntry}, next_client::runtime_entry::{RuntimeEntries, RuntimeEntry},
next_config::NextConfig, next_config::NextConfig,
next_font::local::NextFontLocalResolvePlugin,
next_import_map::{ next_import_map::{
get_next_client_fallback_import_map, get_next_client_import_map, get_next_client_fallback_import_map, get_next_client_import_map,
get_next_client_resolved_map, get_next_client_resolved_map,
...@@ -157,7 +158,8 @@ pub async fn get_client_resolve_options_context( ...@@ -157,7 +158,8 @@ pub async fn get_client_resolve_options_context(
resolved_map: Some(next_client_resolved_map), resolved_map: Some(next_client_resolved_map),
browser: true, browser: true,
module: true, module: true,
plugins: vec![ before_resolve_plugins: vec![Vc::upcast(NextFontLocalResolvePlugin::new(project_path))],
after_resolve_plugins: vec![
Vc::upcast(ModuleFeatureReportResolvePlugin::new(project_path)), Vc::upcast(ModuleFeatureReportResolvePlugin::new(project_path)),
Vc::upcast(UnsupportedModulesResolvePlugin::new(project_path)), Vc::upcast(UnsupportedModulesResolvePlugin::new(project_path)),
Vc::upcast(NextSharedRuntimeResolvePlugin::new(project_path)), Vc::upcast(NextSharedRuntimeResolvePlugin::new(project_path)),
......
...@@ -22,6 +22,7 @@ use turbopack_binding::{ ...@@ -22,6 +22,7 @@ use turbopack_binding::{
use crate::{ use crate::{
mode::NextMode, mode::NextMode,
next_config::NextConfig, next_config::NextConfig,
next_font::local::NextFontLocalResolvePlugin,
next_import_map::get_next_edge_import_map, next_import_map::get_next_edge_import_map,
next_server::context::ServerContextType, next_server::context::ServerContextType,
next_shared::resolve::{ next_shared::resolve::{
...@@ -100,7 +101,20 @@ pub async fn get_edge_resolve_options_context( ...@@ -100,7 +101,20 @@ pub async fn get_edge_resolve_options_context(
let ty = ty.into_value(); let ty = ty.into_value();
let mut plugins = match ty { let before_resolve_plugins = match ty {
ServerContextType::Pages { .. }
| ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. } => {
vec![Vc::upcast(NextFontLocalResolvePlugin::new(project_path))]
}
ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. }
| ServerContextType::AppRoute { .. }
| ServerContextType::Middleware { .. }
| ServerContextType::Instrumentation => vec![],
};
let mut after_resolve_plugins = match ty {
ServerContextType::Pages { .. } ServerContextType::Pages { .. }
| ServerContextType::PagesApi { .. } | ServerContextType::PagesApi { .. }
| ServerContextType::AppSSR { .. } => { | ServerContextType::AppSSR { .. } => {
...@@ -124,7 +138,7 @@ pub async fn get_edge_resolve_options_context( ...@@ -124,7 +138,7 @@ pub async fn get_edge_resolve_options_context(
Vc::upcast(NextSharedRuntimeResolvePlugin::new(project_path)), Vc::upcast(NextSharedRuntimeResolvePlugin::new(project_path)),
]; ];
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().to_string()];
...@@ -146,7 +160,8 @@ pub async fn get_edge_resolve_options_context( ...@@ -146,7 +160,8 @@ pub async fn get_edge_resolve_options_context(
import_map: Some(next_edge_import_map), import_map: Some(next_edge_import_map),
module: true, module: true,
browser: true, browser: true,
plugins, after_resolve_plugins,
before_resolve_plugins,
..Default::default() ..Default::default()
}; };
......
use thiserror::Error;
#[derive(Debug, Error)]
pub enum FontError {
#[error("could not find font file")]
FontFileNotFound(String),
}
...@@ -15,6 +15,7 @@ use crate::next_font::{ ...@@ -15,6 +15,7 @@ use crate::next_font::{
AutomaticFontFallback, DefaultFallbackFont, FontAdjustment, FontFallback, FontFallbacks, AutomaticFontFallback, DefaultFallbackFont, FontAdjustment, FontFallback, FontFallbacks,
DEFAULT_SANS_SERIF_FONT, DEFAULT_SERIF_FONT, DEFAULT_SANS_SERIF_FONT, DEFAULT_SERIF_FONT,
}, },
local::errors::FontError,
util::{get_scoped_font_family, FontFamilyType}, util::{get_scoped_font_family, FontFamilyType},
}; };
...@@ -74,7 +75,7 @@ async fn get_font_adjustment( ...@@ -74,7 +75,7 @@ async fn get_font_adjustment(
let main_descriptor = pick_font_for_fallback_generation(&options.fonts)?; let main_descriptor = pick_font_for_fallback_generation(&options.fonts)?;
let font_file = &*context.join(main_descriptor.path.clone()).read().await?; let font_file = &*context.join(main_descriptor.path.clone()).read().await?;
let font_file_rope = match font_file { let font_file_rope = match font_file {
FileContent::NotFound => bail!("Expected font file content"), FileContent::NotFound => bail!(FontError::FontFileNotFound(main_descriptor.path.clone())),
FileContent::Content(file) => file.content(), FileContent::Content(file) => file.content(),
}; };
......
...@@ -27,13 +27,8 @@ use crate::{ ...@@ -27,13 +27,8 @@ use crate::{
next_client::context::ClientContextType, next_client::context::ClientContextType,
next_config::NextConfig, next_config::NextConfig,
next_edge::unsupported::NextEdgeUnsupportedModuleReplacer, next_edge::unsupported::NextEdgeUnsupportedModuleReplacer,
next_font::{ next_font::google::{
google::{ NextFontGoogleCssModuleReplacer, NextFontGoogleFontFileReplacer, NextFontGoogleReplacer,
NextFontGoogleCssModuleReplacer, NextFontGoogleFontFileReplacer, NextFontGoogleReplacer,
},
local::{
NextFontLocalCssModuleReplacer, NextFontLocalFontFileReplacer, NextFontLocalReplacer,
},
}, },
next_server::context::ServerContextType, next_server::context::ServerContextType,
util::NextRuntime, util::NextRuntime,
...@@ -797,6 +792,11 @@ async fn insert_next_shared_aliases( ...@@ -797,6 +792,11 @@ async fn insert_next_shared_aliases(
package_root, package_root,
); );
// NOTE: `@next/font/local` has moved to a BeforeResolve Plugin, so it does not
// have ImportMapping replacers here.
//
// TODO: Add BeforeResolve plugins for `@next/font/google`
import_map.insert_alias( import_map.insert_alias(
// Request path from js via next-font swc transform // Request path from js via next-font swc transform
AliasPattern::exact("next/font/google/target.css"), AliasPattern::exact("next/font/google/target.css"),
...@@ -826,28 +826,6 @@ async fn insert_next_shared_aliases( ...@@ -826,28 +826,6 @@ async fn insert_next_shared_aliases(
.into(), .into(),
); );
import_map.insert_alias(
// Request path from js via next-font swc transform
AliasPattern::exact("next/font/local/target.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalReplacer::new(project_path))).into(),
);
import_map.insert_alias(
// Request path from js via next-font swc transform
AliasPattern::exact("@next/font/local/target.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalReplacer::new(project_path))).into(),
);
import_map.insert_alias(
AliasPattern::exact("@vercel/turbopack-next/internal/font/local/cssmodule.module.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalCssModuleReplacer::new())).into(),
);
import_map.insert_alias(
AliasPattern::exact("@vercel/turbopack-next/internal/font/local/font"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalFontFileReplacer::new(project_path))).into(),
);
import_map.insert_singleton_alias("@swc/helpers", get_next_package(project_path)); import_map.insert_singleton_alias("@swc/helpers", get_next_package(project_path));
import_map.insert_singleton_alias("styled-jsx", get_next_package(project_path)); import_map.insert_singleton_alias("styled-jsx", get_next_package(project_path));
import_map.insert_singleton_alias("next", project_path); import_map.insert_singleton_alias("next", project_path);
......
...@@ -45,6 +45,7 @@ use crate::{ ...@@ -45,6 +45,7 @@ use crate::{
next_build::get_postcss_package_mapping, next_build::get_postcss_package_mapping,
next_client::RuntimeEntries, next_client::RuntimeEntries,
next_config::NextConfig, next_config::NextConfig,
next_font::local::NextFontLocalResolvePlugin,
next_import_map::get_next_server_import_map, next_import_map::get_next_server_import_map,
next_server::resolve::ExternalPredicate, next_server::resolve::ExternalPredicate,
next_shared::{ next_shared::{
...@@ -199,7 +200,20 @@ pub async fn get_server_resolve_options_context( ...@@ -199,7 +200,20 @@ pub async fn get_server_resolve_options_context(
let next_node_shared_runtime_plugin = let next_node_shared_runtime_plugin =
NextNodeSharedRuntimeResolvePlugin::new(project_path, Value::new(ty)); NextNodeSharedRuntimeResolvePlugin::new(project_path, Value::new(ty));
let mut plugins = match ty { let before_resolve_plugins = match ty {
ServerContextType::Pages { .. }
| ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. } => {
vec![Vc::upcast(NextFontLocalResolvePlugin::new(project_path))]
}
ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. }
| ServerContextType::AppRoute { .. }
| ServerContextType::Middleware { .. }
| ServerContextType::Instrumentation => vec![],
};
let mut after_resolve_plugins = match ty {
ServerContextType::Pages { .. } ServerContextType::Pages { .. }
| ServerContextType::PagesApi { .. } | ServerContextType::PagesApi { .. }
| ServerContextType::PagesData { .. } => { | ServerContextType::PagesData { .. } => {
...@@ -255,8 +269,8 @@ pub async fn get_server_resolve_options_context( ...@@ -255,8 +269,8 @@ pub async fn get_server_resolve_options_context(
| ServerContextType::AppRoute { .. } | ServerContextType::AppRoute { .. }
| ServerContextType::Middleware { .. } | ServerContextType::Middleware { .. }
| ServerContextType::Instrumentation => { | ServerContextType::Instrumentation => {
plugins.push(Vc::upcast(invalid_client_only_resolve_plugin)); after_resolve_plugins.push(Vc::upcast(invalid_client_only_resolve_plugin));
plugins.push(Vc::upcast(invalid_styled_jsx_client_only_resolve_plugin)); after_resolve_plugins.push(Vc::upcast(invalid_styled_jsx_client_only_resolve_plugin));
} }
ServerContextType::AppSSR { .. } => { ServerContextType::AppSSR { .. } => {
//[TODO] Build error in this context makes rsc-build-error.ts fail which expects runtime error code //[TODO] Build error in this context makes rsc-build-error.ts fail which expects runtime error code
...@@ -271,7 +285,8 @@ pub async fn get_server_resolve_options_context( ...@@ -271,7 +285,8 @@ pub async fn get_server_resolve_options_context(
module: true, module: true,
custom_conditions, custom_conditions,
import_map: Some(next_server_import_map), import_map: Some(next_server_import_map),
plugins, before_resolve_plugins,
after_resolve_plugins,
..Default::default() ..Default::default()
}; };
......
...@@ -11,7 +11,7 @@ use turbopack_binding::{ ...@@ -11,7 +11,7 @@ use turbopack_binding::{
node::{node_cjs_resolve_options, node_esm_resolve_options}, node::{node_cjs_resolve_options, node_esm_resolve_options},
package_json, package_json,
parse::Request, parse::Request,
plugin::{ResolvePlugin, ResolvePluginCondition}, plugin::{AfterResolvePlugin, AfterResolvePluginCondition},
resolve, ExternalType, FindContextFileResult, ResolveResult, ResolveResultItem, resolve, ExternalType, FindContextFileResult, ResolveResult, ResolveResultItem,
ResolveResultOption, ResolveResultOption,
}, },
...@@ -61,14 +61,14 @@ impl ExternalCjsModulesResolvePlugin { ...@@ -61,14 +61,14 @@ impl ExternalCjsModulesResolvePlugin {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn condition(root: Vc<FileSystemPath>) -> Vc<ResolvePluginCondition> { fn condition(root: Vc<FileSystemPath>) -> Vc<AfterResolvePluginCondition> {
ResolvePluginCondition::new(root, Glob::new("**/node_modules/**".to_string())) AfterResolvePluginCondition::new(root, Glob::new("**/node_modules/**".to_string()))
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ResolvePlugin for ExternalCjsModulesResolvePlugin { impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn after_resolve_condition(&self) -> Vc<ResolvePluginCondition> { fn after_resolve_condition(&self) -> Vc<AfterResolvePluginCondition> {
condition(self.root) condition(self.root)
} }
......
...@@ -17,7 +17,7 @@ use turbopack_binding::{ ...@@ -17,7 +17,7 @@ use turbopack_binding::{
resolve::{ resolve::{
parse::Request, parse::Request,
pattern::Pattern, pattern::Pattern,
plugin::{ResolvePlugin, ResolvePluginCondition}, plugin::{AfterResolvePlugin, AfterResolvePluginCondition},
ExternalType, ResolveResult, ResolveResultItem, ResolveResultOption, ExternalType, ResolveResult, ResolveResultItem, ResolveResultOption,
}, },
}, },
...@@ -60,10 +60,10 @@ impl UnsupportedModulesResolvePlugin { ...@@ -60,10 +60,10 @@ impl UnsupportedModulesResolvePlugin {
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ResolvePlugin for UnsupportedModulesResolvePlugin { impl AfterResolvePlugin for UnsupportedModulesResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn after_resolve_condition(&self) -> Vc<ResolvePluginCondition> { fn after_resolve_condition(&self) -> Vc<AfterResolvePluginCondition> {
ResolvePluginCondition::new(self.root.root(), Glob::new("**".to_string())) AfterResolvePluginCondition::new(self.root.root(), Glob::new("**".to_string()))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -189,10 +189,10 @@ impl InvalidImportResolvePlugin { ...@@ -189,10 +189,10 @@ impl InvalidImportResolvePlugin {
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ResolvePlugin for InvalidImportResolvePlugin { impl AfterResolvePlugin for InvalidImportResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn after_resolve_condition(&self) -> Vc<ResolvePluginCondition> { fn after_resolve_condition(&self) -> Vc<AfterResolvePluginCondition> {
ResolvePluginCondition::new(self.root.root(), Glob::new("**".to_string())) AfterResolvePluginCondition::new(self.root.root(), Glob::new("**".to_string()))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -287,10 +287,10 @@ impl NextExternalResolvePlugin { ...@@ -287,10 +287,10 @@ impl NextExternalResolvePlugin {
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ResolvePlugin for NextExternalResolvePlugin { impl AfterResolvePlugin for NextExternalResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn after_resolve_condition(&self) -> Vc<ResolvePluginCondition> { fn after_resolve_condition(&self) -> Vc<AfterResolvePluginCondition> {
ResolvePluginCondition::new( AfterResolvePluginCondition::new(
self.root.root(), self.root.root(),
Glob::new("**/next/dist/**/*.{external,runtime.dev,runtime.prod}.js".to_string()), Glob::new("**/next/dist/**/*.{external,runtime.dev,runtime.prod}.js".to_string()),
) )
...@@ -337,10 +337,10 @@ impl NextNodeSharedRuntimeResolvePlugin { ...@@ -337,10 +337,10 @@ impl NextNodeSharedRuntimeResolvePlugin {
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ResolvePlugin for NextNodeSharedRuntimeResolvePlugin { impl AfterResolvePlugin for NextNodeSharedRuntimeResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn after_resolve_condition(&self) -> Vc<ResolvePluginCondition> { fn after_resolve_condition(&self) -> Vc<AfterResolvePluginCondition> {
ResolvePluginCondition::new( AfterResolvePluginCondition::new(
self.root.root(), self.root.root(),
Glob::new("**/next/dist/**/*.shared-runtime.js".to_string()), Glob::new("**/next/dist/**/*.shared-runtime.js".to_string()),
) )
...@@ -402,10 +402,10 @@ impl ModuleFeatureReportResolvePlugin { ...@@ -402,10 +402,10 @@ impl ModuleFeatureReportResolvePlugin {
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ResolvePlugin for ModuleFeatureReportResolvePlugin { impl AfterResolvePlugin for ModuleFeatureReportResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn after_resolve_condition(&self) -> Vc<ResolvePluginCondition> { fn after_resolve_condition(&self) -> Vc<AfterResolvePluginCondition> {
ResolvePluginCondition::new(self.root.root(), Glob::new("**".to_string())) AfterResolvePluginCondition::new(self.root.root(), Glob::new("**".to_string()))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -455,10 +455,10 @@ impl NextSharedRuntimeResolvePlugin { ...@@ -455,10 +455,10 @@ impl NextSharedRuntimeResolvePlugin {
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ResolvePlugin for NextSharedRuntimeResolvePlugin { impl AfterResolvePlugin for NextSharedRuntimeResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
fn after_resolve_condition(&self) -> Vc<ResolvePluginCondition> { fn after_resolve_condition(&self) -> Vc<AfterResolvePluginCondition> {
ResolvePluginCondition::new( AfterResolvePluginCondition::new(
self.root.root(), self.root.root(),
Glob::new("**/next/dist/esm/**/*.shared-runtime.js".to_string()), Glob::new("**/next/dist/esm/**/*.shared-runtime.js".to_string()),
) )
......
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