Unverified Commit 783d8455 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Implement next/font BeforeResolvePlugins as ImportMappingReplacement (#95808)

ImportMappingReplacement are more efficient: import maps are backed by a
single radix tree, as opposed to having to run every single
ResolvePlugin's matchers in sequence.

This basically undoes https://github.com/vercel/next.js/pull/65870 by
@wbinnssmith, but I don't entirely understand why this was done:
> This is used to replace ImportMapping replacers for @next/font/local
in an upcoming Next.js PR
parent c4430500
......@@ -48,7 +48,6 @@ use crate::{
transforms::get_next_client_transforms_rules,
},
next_config::NextConfig,
next_font::local::NextFontLocalResolvePlugin,
next_import_map::{
get_next_client_fallback_import_map, get_next_client_import_map,
get_next_client_resolved_map,
......@@ -189,11 +188,6 @@ pub async fn get_client_resolve_options_context(
resolved_map: Some(next_client_resolved_map),
browser: true,
module: true,
before_resolve_plugins: vec![ResolvedVc::upcast(
NextFontLocalResolvePlugin::new(project_path.clone())
.to_resolved()
.await?,
)],
after_resolve_plugins: vec![ResolvedVc::upcast(
NextSharedRuntimeResolvePlugin::new(project_path.clone())
.to_resolved()
......
......@@ -27,7 +27,6 @@ use crate::{
app_structure::CollectedRootParams,
mode::NextMode,
next_config::NextConfig,
next_font::local::NextFontLocalResolvePlugin,
next_import_map::{get_next_edge_and_server_fallback_import_map, get_next_edge_import_map},
next_server::context::ServerContextType,
next_shared::resolve::NextSharedRuntimeResolvePlugin,
......@@ -114,21 +113,6 @@ pub async fn get_edge_resolve_options_context(
.to_resolved()
.await?;
let before_resolve_plugins = if matches!(
ty,
ServerContextType::Pages { .. }
| ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. }
) {
vec![ResolvedVc::upcast(
NextFontLocalResolvePlugin::new(project_path.clone())
.to_resolved()
.await?,
)]
} else {
vec![]
};
let after_resolve_plugins = vec![ResolvedVc::upcast(
NextSharedRuntimeResolvePlugin::new(project_path.clone())
.to_resolved()
......@@ -156,7 +140,6 @@ pub async fn get_edge_resolve_options_context(
module: true,
browser: true,
after_resolve_plugins,
before_resolve_plugins,
..Default::default()
};
......
......@@ -4,19 +4,15 @@ use indoc::formatdoc;
use serde::{Deserialize, Serialize};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{
FileContent, FileSystemPath,
glob::{Glob, GlobOptions},
json::parse_json_with_source_context,
};
use turbo_tasks_fs::{FileContent, FileSystemPath, json::parse_json_with_source_context};
use turbopack_core::{
asset::AssetContent,
issue::{Issue, IssueSeverity, IssueStage, StyledString},
reference_type::ReferenceType,
resolve::{
ResolveResult, ResolveResultItem, ResolveResultOption,
ResolveResult, ResolveResultItem,
options::{ImportMapResult, ImportMappingReplacement, ReplacedImportMapping},
parse::Request,
plugin::{BeforeResolvePlugin, BeforeResolvePluginCondition},
pattern::Pattern,
},
virtual_source::VirtualSource,
};
......@@ -27,7 +23,7 @@ use crate::{
font_fallback::FontFallbacks,
local::{
font_fallback::{FontFallbackResult, get_font_fallbacks},
options::{FontDescriptors, FontWeight, NextFontLocalOptions, options_from_request},
options::{FontDescriptors, FontWeight, NextFontLocalOptions},
stylesheet::build_stylesheet,
util::build_font_family_string,
},
......@@ -48,47 +44,162 @@ struct NextFontLocalFontFileOptions {
pub preload: bool,
pub has_size_adjust: bool,
}
impl NextFontLocalFontFileOptions {
pub fn from_query_map(query: &RcStr) -> Result<NextFontLocalFontFileOptions> {
let query_map = qstring::QString::from(query.as_str());
if query_map.len() != 1 {
bail!("next/font/local queries have exactly one entry");
}
let Some((json, _)) = query_map.into_iter().next() else {
bail!("Expected one entry");
};
parse_json_with_source_context(&json)
}
}
// Replacer for `next/font/local/target.css`
#[turbo_tasks::value]
pub(crate) struct NextFontLocalResolvePlugin {
pub(crate) struct NextFontLocalReplacer {
root: FileSystemPath,
condition: ResolvedVc<BeforeResolvePluginCondition>,
}
#[turbo_tasks::value_impl]
impl NextFontLocalResolvePlugin {
impl NextFontLocalReplacer {
#[turbo_tasks::function]
pub fn new(root: FileSystemPath) -> Vc<Self> {
Self::cell(NextFontLocalReplacer { root })
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontLocalReplacer {
#[turbo_tasks::function]
pub async fn new(root: FileSystemPath) -> Result<Vc<Self>> {
let condition = BeforeResolvePluginCondition::from_request_glob(Glob::new(
rcstr!("{next,@vercel/turbopack-next/internal}/font/local/*"),
GlobOptions::default(),
))
fn replace(&self, _capture: Vc<Pattern>) -> Vc<ReplacedImportMapping> {
ReplacedImportMapping::Ignore.cell()
}
#[turbo_tasks::function]
async fn result(
&self,
lookup_path: FileSystemPath,
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let request = &*request.await?;
let Request::Module {
module: _,
path: _,
query,
fragment: _,
} = request
else {
return Ok(ImportMapResult::NoEntry.cell());
};
if !can_use_next_font(self.root.clone(), query).await? {
return Ok(ImportMapResult::NoEntry.cell());
}
let request_hash = get_request_hash(query.as_str());
let qstr = qstring::QString::from(query.as_str());
let options_vc = NextFontLocalOptions::from_query_map(query.clone());
let font_fallbacks = &*get_font_fallbacks(lookup_path.clone(), options_vc).await?;
let font_fallbacks = match font_fallbacks {
FontFallbackResult::FontFileNotFound(err) => {
return Ok(ImportMapResult::Result(
ResolveResult::primary(ResolveResultItem::Error(ResolvedVc::upcast(
FontResolvingIssue {
font_path: ResolvedVc::cell(err.0.clone()),
}
.resolved_cell(),
)))
.resolved_cell(),
)
.cell());
}
FontFallbackResult::Ok(font_fallbacks) => *font_fallbacks,
};
let properties = get_font_css_properties(options_vc, *font_fallbacks).await?;
let file_content = formatdoc!(
r#"
import cssModule from "@vercel/turbopack-next/internal/font/local/cssmodule.module.css?{}";
const fontData = {{
className: cssModule.className,
style: {{
fontFamily: "{}",
{}{}
}},
}};
if (cssModule.variable != null) {{
fontData.variable = cssModule.variable;
}}
export default fontData;
"#,
// Pass along whichever options we received to the css handler
qstr,
properties.font_family.await?,
properties
.weight
.await?
.as_ref()
.map(|w| format!("fontWeight: {w},\n"))
.unwrap_or_else(|| "".to_owned()),
properties
.style
.await?
.as_ref()
.map(|s| format!("fontStyle: \"{s}\",\n"))
.unwrap_or_else(|| "".to_owned()),
);
let js_asset = VirtualSource::new(
lookup_path.join(&format!(
"{}.js",
get_request_id(options_vc.font_family().await?, request_hash)
))?,
AssetContent::file(FileContent::Content(file_content.into()).cell()),
)
.to_resolved()
.await?;
Ok(NextFontLocalResolvePlugin { root, condition }.cell())
Ok(ImportMapResult::Result(
ResolveResult::source(ResolvedVc::upcast(js_asset)).resolved_cell(),
)
.cell())
}
}
// Replacer for `@vercel/turbopack-next/internal/font/local/cssmodule.module.css` requests.
#[turbo_tasks::value]
pub(crate) struct NextFontLocalCssModuleReplacer {}
#[turbo_tasks::value_impl]
impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
fn before_resolve_condition(&self) -> Vc<BeforeResolvePluginCondition> {
*self.condition
impl NextFontLocalCssModuleReplacer {
#[turbo_tasks::function]
pub fn new() -> Vc<Self> {
Self::cell(NextFontLocalCssModuleReplacer {})
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontLocalCssModuleReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: Vc<Pattern>) -> Vc<ReplacedImportMapping> {
ReplacedImportMapping::Ignore.cell()
}
#[turbo_tasks::function]
async fn before_resolve(
async fn result(
self: Vc<Self>,
lookup_path: FileSystemPath,
_reference_type: ReferenceType,
request_vc: Vc<Request>,
) -> Result<Vc<ResolveResultOption>> {
let this = &*self.await?;
let request = &*request_vc.await?;
let Some(request_key) = request.request() else {
return Ok(ResolveResultOption::none());
};
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let request = &*request.await?;
let Request::Module {
module: _,
path: _,
......@@ -96,158 +207,119 @@ impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
fragment: _,
} = request
else {
return Ok(ResolveResultOption::none());
return Ok(ImportMapResult::NoEntry.cell());
};
match request_key.as_str() {
"next/font/local/target.css" => {
if !can_use_next_font(this.root.clone(), query).await? {
return Ok(ResolveResultOption::none());
}
let request_hash = get_request_hash(query.as_str());
let qstr = qstring::QString::from(query.as_str());
let options_vc = font_options_from_query_map(query.clone());
let font_fallbacks = &*get_font_fallbacks(lookup_path.clone(), options_vc).await?;
let font_fallbacks = match font_fallbacks {
FontFallbackResult::FontFileNotFound(err) => {
return Ok(ResolveResultOption::some(
ResolveResult::primary(ResolveResultItem::Error(ResolvedVc::upcast(
FontResolvingIssue {
font_path: ResolvedVc::cell(err.0.clone()),
}
.resolved_cell(),
)))
.cell(),
));
}
FontFallbackResult::Ok(font_fallbacks) => *font_fallbacks,
};
let properties = get_font_css_properties(options_vc, *font_fallbacks).await?;
let file_content = formatdoc!(
r#"
import cssModule from "@vercel/turbopack-next/internal/font/local/cssmodule.module.css?{}";
const fontData = {{
className: cssModule.className,
style: {{
fontFamily: "{}",
{}{}
}},
}};
if (cssModule.variable != null) {{
fontData.variable = cssModule.variable;
}}
export default fontData;
"#,
// Pass along whichever options we received to the css handler
qstr,
properties.font_family.await?,
properties
.weight
.await?
.as_ref()
.map(|w| format!("fontWeight: {w},\n"))
.unwrap_or_else(|| "".to_owned()),
properties
.style
.await?
.as_ref()
.map(|s| format!("fontStyle: \"{s}\",\n"))
.unwrap_or_else(|| "".to_owned()),
);
let js_asset = VirtualSource::new(
lookup_path.join(&format!(
"{}.js",
get_request_id(options_vc.font_family().await?, request_hash)
))?,
AssetContent::file(FileContent::Content(file_content.into()).cell()),
let request_hash = get_request_hash(query);
let options = NextFontLocalOptions::from_query_map(query.clone());
let css_virtual_path = lookup_path.join(&format!(
"/{}.module.css",
get_request_id(options.font_family().await?, request_hash)
))?;
let fallback = &*get_font_fallbacks(lookup_path.clone(), options).await?;
let fallback = match fallback {
FontFallbackResult::FontFileNotFound(err) => {
return Ok(ImportMapResult::Result(
ResolveResult::primary(ResolveResultItem::Error(ResolvedVc::upcast(
FontResolvingIssue {
font_path: ResolvedVc::cell(err.0.clone()),
}
.resolved_cell(),
)))
.resolved_cell(),
)
.to_resolved()
.await?;
Ok(ResolveResultOption::some(
ResolveResult::source(ResolvedVc::upcast(js_asset)).cell(),
))
.cell());
}
"@vercel/turbopack-next/internal/font/local/cssmodule.module.css" => {
let request_hash = get_request_hash(query);
let options = font_options_from_query_map(query.clone());
let css_virtual_path = lookup_path.join(&format!(
"/{}.module.css",
get_request_id(options.font_family().await?, request_hash)
))?;
let fallback = &*get_font_fallbacks(lookup_path.clone(), options).await?;
let fallback = match fallback {
FontFallbackResult::FontFileNotFound(err) => {
return Ok(ResolveResultOption::some(
ResolveResult::primary(ResolveResultItem::Error(ResolvedVc::upcast(
FontResolvingIssue {
font_path: ResolvedVc::cell(err.0.clone()),
}
.resolved_cell(),
)))
.cell(),
));
}
FontFallbackResult::Ok(font_fallbacks) => **font_fallbacks,
};
let stylesheet = build_stylesheet(
font_options_from_query_map(query.clone()),
fallback,
get_font_css_properties(options, fallback),
)
.await?;
FontFallbackResult::Ok(font_fallbacks) => **font_fallbacks,
};
let css_asset = VirtualSource::new(
css_virtual_path,
AssetContent::file(FileContent::Content(stylesheet.into()).cell()),
)
.to_resolved()
.await?;
let stylesheet = build_stylesheet(
NextFontLocalOptions::from_query_map(query.clone()),
fallback,
get_font_css_properties(options, fallback),
)
.await?;
Ok(ResolveResultOption::some(
ResolveResult::source(ResolvedVc::upcast(css_asset)).cell(),
))
}
"@vercel/turbopack-next/internal/font/local/font" => {
let NextFontLocalFontFileOptions {
path,
preload,
has_size_adjust: size_adjust,
} = font_file_options_from_query_map(query)?;
let (filename, ext) = split_extension(&path);
let ext = ext.with_context(|| format!("font {} needs an extension", path))?;
// remove dashes and dots as they might be used for the markers below.
let mut name = filename.replace(['-', '.'], "_");
if size_adjust {
name.push_str("-s")
}
if preload {
name.push_str(".p")
}
let font_virtual_path = lookup_path.join(&format!("/{name}.{ext}"))?;
let font_file = lookup_path.join(&path)?.read();
let font_source =
VirtualSource::new(font_virtual_path, AssetContent::file(font_file))
.to_resolved()
.await?;
Ok(ResolveResultOption::some(
ResolveResult::source(ResolvedVc::upcast(font_source)).cell(),
))
}
_ => Ok(ResolveResultOption::none()),
let css_asset = VirtualSource::new(
css_virtual_path,
AssetContent::file(FileContent::Content(stylesheet.into()).cell()),
)
.to_resolved()
.await?;
Ok(ImportMapResult::Result(
ResolveResult::source(ResolvedVc::upcast(css_asset)).resolved_cell(),
)
.cell())
}
}
// Replacer for `@vercel/turbopack-next/internal/font/local/font`
#[turbo_tasks::value]
pub(crate) struct NextFontLocalFontFileReplacer {}
#[turbo_tasks::value_impl]
impl NextFontLocalFontFileReplacer {
#[turbo_tasks::function]
pub fn new() -> Vc<Self> {
Self::cell(NextFontLocalFontFileReplacer {})
}
}
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextFontLocalFontFileReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: Vc<Pattern>) -> Vc<ReplacedImportMapping> {
ReplacedImportMapping::Ignore.cell()
}
#[turbo_tasks::function]
async fn result(
&self,
lookup_path: FileSystemPath,
request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let request = &*request.await?;
let Request::Module {
module: _,
path: _,
query,
fragment: _,
} = request
else {
return Ok(ImportMapResult::NoEntry.cell());
};
let NextFontLocalFontFileOptions {
path,
preload,
has_size_adjust: size_adjust,
} = NextFontLocalFontFileOptions::from_query_map(query)?;
let (filename, ext) = split_extension(&path);
let ext = ext.with_context(|| format!("font {} needs an extension", path))?;
// remove dashes and dots as they might be used for the markers below.
let mut name = filename.replace(['-', '.'], "_");
if size_adjust {
name.push_str("-s")
}
if preload {
name.push_str(".p")
}
let font_virtual_path = lookup_path.join(&format!("/{name}.{ext}"))?;
let font_file = lookup_path.join(&path)?.read();
let font_source = VirtualSource::new(font_virtual_path, AssetContent::file(font_file))
.to_resolved()
.await?;
Ok(ImportMapResult::Result(
ResolveResult::source(ResolvedVc::upcast(font_source)).resolved_cell(),
)
.cell())
}
}
......@@ -284,35 +356,6 @@ async fn get_font_css_properties(
}))
}
#[turbo_tasks::function]
fn font_options_from_query_map(query: RcStr) -> Result<Vc<NextFontLocalOptions>> {
let query_map = qstring::QString::from(query.as_str());
if query_map.len() != 1 {
bail!("next/font/local queries have exactly one entry");
}
let Some((json, _)) = query_map.into_iter().next() else {
bail!("Expected one entry");
};
options_from_request(&parse_json_with_source_context(&json)?).map(NextFontLocalOptions::new)
}
fn font_file_options_from_query_map(query: &RcStr) -> Result<NextFontLocalFontFileOptions> {
let query_map = qstring::QString::from(query.as_str());
if query_map.len() != 1 {
bail!("next/font/local queries have exactly one entry");
}
let Some((json, _)) = query_map.into_iter().next() else {
bail!("Expected one entry");
};
parse_json_with_source_context(&json)
}
#[turbo_tasks::value(shared)]
struct FontResolvingIssue {
font_path: ResolvedVc<RcStr>,
......
use std::{fmt::Display, str::FromStr};
use anyhow::{Context, Result};
use anyhow::{Context, Result, bail};
use bincode::{Decode, Encode};
use turbo_rcstr::RcStr;
use turbo_tasks::{Vc, trace::TraceRawVcs};
use turbo_tasks_fs::json::parse_json_with_source_context;
use crate::next_font::local::request::{
AdjustFontFallback, NextFontLocalDeclaration, NextFontLocalRequest,
......@@ -48,6 +49,23 @@ impl NextFontLocalOptions {
pub fn new(options: NextFontLocalOptions) -> Vc<NextFontLocalOptions> {
Self::cell(options)
}
#[turbo_tasks::function]
pub fn from_query_map(query: RcStr) -> Result<Vc<NextFontLocalOptions>> {
let query_map = qstring::QString::from(query.as_str());
if query_map.len() != 1 {
bail!("next/font/local queries have exactly one entry");
}
let Some((json, _)) = query_map.into_iter().next() else {
bail!("Expected one entry");
};
Ok(NextFontLocalOptions::new(options_from_request(
&parse_json_with_source_context(&json)?,
)?))
}
}
/// Describes an individual font file's path, weight, style, etc. Derived from
......
......@@ -37,12 +37,18 @@ use crate::{
next_client::context::ClientContextType,
next_config::{NextConfig, OptionFileSystemPath},
next_edge::unsupported::NextEdgeUnsupportedModuleReplacer,
next_font::google::{
GOOGLE_FONTS_INTERNAL_PREFIX, NextFontGoogleCssModuleReplacer,
NextFontGoogleFontFileReplacer, NextFontGoogleReplacer,
next_font::{
google::{
GOOGLE_FONTS_INTERNAL_PREFIX, NextFontGoogleCssModuleReplacer,
NextFontGoogleFontFileReplacer, NextFontGoogleReplacer,
},
local::{
NextFontLocalCssModuleReplacer, NextFontLocalFontFileReplacer, NextFontLocalReplacer,
},
},
next_root_params::insert_next_root_params_mapping,
next_server::context::ServerContextType,
next_shared::ContextType,
util::NextRuntime,
};
......@@ -64,6 +70,7 @@ pub async fn get_next_client_import_map(
execution_context,
next_config,
next_mode,
ContextType::Client(ty.clone()),
false,
)
.await?;
......@@ -286,6 +293,7 @@ pub async fn get_next_server_import_map(
execution_context,
next_config,
next_mode,
ContextType::Server(ty.clone()),
false,
)
.await?;
......@@ -431,6 +439,7 @@ pub async fn get_next_edge_import_map(
execution_context,
next_config,
next_mode,
ContextType::Server(ty.clone()),
true,
)
.await?;
......@@ -1061,6 +1070,7 @@ async fn insert_next_shared_aliases(
execution_context: Vc<ExecutionContext>,
next_config: Vc<NextConfig>,
next_mode: Vc<NextMode>,
ty: ContextType,
is_runtime_edge: bool,
) -> Result<()> {
let package_root = next_js_fs().root().owned().await?;
......@@ -1082,10 +1092,43 @@ async fn insert_next_shared_aliases(
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`
match ty {
ContextType::Client(_)
| ContextType::Server(
ServerContextType::Pages { .. }
| ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. },
) => {
import_map.insert_alias(
AliasPattern::exact(rcstr!("next/font/local/target.css")),
ImportMapping::Dynamic(ResolvedVc::upcast(
NextFontLocalReplacer::new(project_path.clone())
.to_resolved()
.await?,
))
.resolved_cell(),
);
import_map.insert_alias(
AliasPattern::exact(rcstr!(
"@vercel/turbopack-next/internal/font/local/cssmodule.module.css"
)),
ImportMapping::Dynamic(ResolvedVc::upcast(
NextFontLocalCssModuleReplacer::new().to_resolved().await?,
))
.resolved_cell(),
);
import_map.insert_alias(
AliasPattern::exact(rcstr!("@vercel/turbopack-next/internal/font/local/font")),
ImportMapping::Dynamic(ResolvedVc::upcast(
NextFontLocalFontFileReplacer::new().to_resolved().await?,
))
.resolved_cell(),
);
}
_ => {}
}
let next_font_google_replacer_mapping = ImportMapping::Dynamic(ResolvedVc::upcast(
NextFontGoogleReplacer::new(project_path.clone())
......
......@@ -47,7 +47,6 @@ use crate::{
mode::NextMode,
next_build::get_postcss_package_mapping,
next_config::NextConfig,
next_font::local::NextFontLocalResolvePlugin,
next_import_map::{get_next_edge_and_server_fallback_import_map, get_next_server_import_map},
next_server::{
resolve::{ExternalCjsModulesResolvePlugin, ExternalPredicate},
......@@ -231,24 +230,6 @@ pub async fn get_server_resolve_options_context(
.to_resolved()
.await?;
let before_resolve_plugins = match &ty {
ServerContextType::Pages { .. }
| ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. } => {
vec![ResolvedVc::upcast(
NextFontLocalResolvePlugin::new(project_path.clone())
.to_resolved()
.await?,
)]
}
ServerContextType::PagesApi { .. }
| ServerContextType::AppRoute { .. }
| ServerContextType::Middleware { .. }
| ServerContextType::Instrumentation { .. } => {
vec![]
}
};
let after_resolve_plugins = match ty {
ServerContextType::Pages { .. } | ServerContextType::PagesApi { .. } => {
vec![
......@@ -283,7 +264,6 @@ pub async fn get_server_resolve_options_context(
custom_conditions,
import_map: Some(next_server_import_map),
fallback_import_map: Some(next_server_fallback_import_map),
before_resolve_plugins,
after_resolve_plugins,
..Default::default()
};
......
use crate::{next_client::ClientContextType, next_server::ServerContextType};
pub(crate) mod resolve;
pub(crate) mod transforms;
pub(crate) mod webpack_rules;
pub(crate) enum ContextType {
#[allow(dead_code)]
Client(ClientContextType),
Server(ServerContextType),
}
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