Unverified Commit 775e8986 authored by OJ Kwon's avatar OJ Kwon Committed by GitHub

feat(next-core): build time client|server-only assertion (#61732)

### What

This PR injects a build-time error for the turbopack if
`client|server-only` is imported in incorrect context. The basic idea is
using resolve plugin, so in resolve time if matching context (which
alises erroneous import), raise a build time error.

Unfortunately this won't fix all of the tests in `invalid-imports`, due
to

1. resolveplugin does not have way to trace import from transformed, so
not able to detect `styled-jsx` from using `<styled..` tags
2. webpack (in our implementation) and turbopack's resolveplugin have
different order of transform / module trace chain, so enabling resolve
plugin in some context raises build error instead of runtime error in
rsc-build-error.

Closes PACK-2397
parent 2d0ed6c3
......@@ -531,6 +531,10 @@ async fn insert_next_server_special_aliases(
}
// see https://github.com/vercel/next.js/blob/8013ef7372fc545d49dbd060461224ceb563b454/packages/next/src/build/webpack-config.ts#L1449-L1531
// Sets runtime aliases for the import to client|server-only. Depends on the
// context, it'll resolve to the noop where it's allowed, or aliased into
// the error which throws a runtime error. This works with in combination of
// build-time error as well, refer https://github.com/vercel/next.js/blob/0060de1c4905593ea875fa7250d4b5d5ce10897d/packages/next-swc/crates/next-core/src/next_server/context.rs#L103
match ty {
ServerContextType::Pages { .. } => {
insert_exact_alias_map(
......@@ -548,7 +552,6 @@ async fn insert_next_server_special_aliases(
| ServerContextType::PagesApi { .. }
| ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. }
| ServerContextType::Middleware
| ServerContextType::Instrumentation => {
insert_exact_alias_map(
import_map,
......@@ -573,21 +576,22 @@ async fn insert_next_server_special_aliases(
},
);
}
}
// Potential the bundle introduced into middleware and api can be poisoned by
// client-only but not being used, so we disabled the `client-only` erroring
// on these layers. `server-only` is still available.
if ty == ServerContextType::Middleware {
insert_exact_alias_map(
import_map,
project_path,
indexmap! {
"client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/client-only/error" => "next/dist/compiled/client-only/index".to_string(),
},
);
// Potential the bundle introduced into middleware and api can be poisoned by
// client-only but not being used, so we disabled the `client-only` erroring
// on these layers. `server-only` is still available.
ServerContextType::Middleware => {
insert_exact_alias_map(
import_map,
project_path,
indexmap! {
"server-only" => "next/dist/compiled/server-only/empty".to_string(),
"client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/server-only" => "next/dist/compiled/server-only/empty".to_string(),
"next/dist/compiled/client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/client-only/error" => "next/dist/compiled/client-only/index".to_string(),
},
);
}
}
import_map.insert_exact_alias(
......
......@@ -52,8 +52,9 @@ use crate::{
next_server::resolve::ExternalPredicate,
next_shared::{
resolve::{
ModuleFeatureReportResolvePlugin, NextExternalResolvePlugin,
NextNodeSharedRuntimeResolvePlugin, UnsupportedModulesResolvePlugin,
get_invalid_client_only_resolve_plugin, ModuleFeatureReportResolvePlugin,
NextExternalResolvePlugin, NextNodeSharedRuntimeResolvePlugin,
UnsupportedModulesResolvePlugin,
},
transforms::{
emotion::get_emotion_transform_rule, get_ecma_transform_rule,
......@@ -114,6 +115,7 @@ pub async fn get_server_resolve_options_context(
let root_dir = project_path.root().resolve().await?;
let module_feature_report_resolve_plugin = ModuleFeatureReportResolvePlugin::new(project_path);
let unsupported_modules_resolve_plugin = UnsupportedModulesResolvePlugin::new(project_path);
let invalid_client_only_resolve_plugin = get_invalid_client_only_resolve_plugin(project_path);
// Always load these predefined packages as external.
let mut external_packages: Vec<String> = load_next_js_templateon(
......@@ -165,7 +167,7 @@ pub async fn get_server_resolve_options_context(
let next_node_shared_runtime_plugin =
NextNodeSharedRuntimeResolvePlugin::new(project_path, Value::new(ty));
let plugins = match ty {
let mut plugins = match ty {
ServerContextType::Pages { .. }
| ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. } => {
......@@ -204,6 +206,34 @@ pub async fn get_server_resolve_options_context(
]
}
};
// Inject resolve plugin to assert incorrect import to client|server-only for
// the corresponding context. Refer https://github.com/vercel/next.js/blob/ad15817f0368ba154bed6d85320335d4b67b7348/packages/next/src/build/webpack-config.ts#L1205-L1235
// how it is applied in the webpack config.
// Unlike webpack which alias client-only -> runtime code -> build-time error
// code, we use resolve plugin to detect original import directly. This
// means each resolve plugin must be injected only for the context where the
// alias resolves into the error. The alias lives in here: https://github.com/vercel/next.js/blob/0060de1c4905593ea875fa7250d4b5d5ce10897d/packages/next-swc/crates/next-core/src/next_import_map.rs#L534
match ty {
ServerContextType::Pages { .. } => {
//noop
}
ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. }
| ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. }
| ServerContextType::Instrumentation => {
plugins.push(Vc::upcast(invalid_client_only_resolve_plugin));
}
ServerContextType::AppSSR { .. } => {
//[TODO] Build error in this context makes rsc-build-error.ts fail which expects runtime error code
// looks like webpack and turbopack have different order, webpack runs rsc transform first, turbopack triggers resolve plugin first.
}
ServerContextType::Middleware => {
//noop
}
}
let resolve_options_context = ResolveOptionsContext {
enable_node_modules: Some(root_dir),
enable_node_externals: true,
......
......@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
use anyhow::Result;
use lazy_static::lazy_static;
use turbo_tasks::{TaskInput, Value, Vc};
use turbo_tasks::{Value, Vc};
use turbo_tasks_fs::glob::Glob;
use turbopack_binding::{
turbo::tasks_fs::FileSystemPath,
......@@ -44,8 +44,6 @@ lazy_static! {
),
("@next", vec!["/font/google", "/font/local"])
]);
static ref CLIENT_ONLY_IMPORTS: HashSet<&'static str> = ["client-only", "next/dist/compiled/server-only/error"].into();
static ref SERVER_ONLY_IMPORTS: HashSet<&'static str> = ["server-only", "next/dist/compiled/server-only/index"].into();
}
#[turbo_tasks::value]
......@@ -110,24 +108,17 @@ impl ResolvePlugin for UnsupportedModulesResolvePlugin {
}
}
#[turbo_tasks::value(shared)]
#[derive(Debug, Copy, Clone, TaskInput, Ord, PartialOrd, Hash)]
pub(crate) enum InvalidImportType {
ClientOnly,
ServerOnly,
}
#[turbo_tasks::value(shared)]
pub struct InvalidImportModuleIssue {
pub file_path: Vc<FileSystemPath>,
pub import_type: InvalidImportType,
pub messages: Vec<String>,
}
#[turbo_tasks::value_impl]
impl Issue for InvalidImportModuleIssue {
#[turbo_tasks::function]
fn severity(&self) -> Vc<IssueSeverity> {
IssueSeverity::Warning.into()
IssueSeverity::Error.into()
}
#[turbo_tasks::function]
......@@ -147,36 +138,50 @@ impl Issue for InvalidImportModuleIssue {
#[turbo_tasks::function]
async fn description(&self) -> Result<Vc<OptionStyledString>> {
let message = match self.import_type {
InvalidImportType::ClientOnly => {
"'client-only' cannot be imported from a Server Component module. It should only \
be used from a Client Component."
}
InvalidImportType::ServerOnly => {
"'server-only' cannot be imported from a Client Component module. It should only \
be used from a Server Component."
}
};
let raw_context = &*self.file_path.await?;
let mut messages = self.messages.clone();
messages.push("\n".to_string());
//[TODO]: how do we get the import trace?
messages.push(format!(
"The error was caused by importing '{}'",
raw_context.path
));
Ok(Vc::cell(Some(
StyledString::Text(message.to_string()).cell(),
StyledString::Line(
messages
.iter()
.map(|v| StyledString::Text(v.into()))
.collect::<Vec<StyledString>>(),
)
.cell(),
)))
}
}
/// A resolve plugin detects import to the `client-only`/`server-only`, then
/// emits an error according to the context.
/// A resolver plugin emits an error when specific context imports
/// specified import requests. It doesn't detect if the import is correctly
/// alised or not unlike webpack-config does; Instead it should be correctly
/// configured when each context sets up its resolve options.
#[turbo_tasks::value]
pub(crate) struct InvalidImportResolvePlugin {
root: Vc<FileSystemPath>,
import_type: InvalidImportType,
invalid_import: String,
message: Vec<String>,
}
#[turbo_tasks::value_impl]
impl InvalidImportResolvePlugin {
#[turbo_tasks::function]
pub fn new(root: Vc<FileSystemPath>, import_type: InvalidImportType) -> Vc<Self> {
InvalidImportResolvePlugin { root, import_type }.cell()
pub fn new(root: Vc<FileSystemPath>, invalid_import: String, message: Vec<String>) -> Vc<Self> {
InvalidImportResolvePlugin {
root,
invalid_import,
message,
}
.cell()
}
}
......@@ -191,48 +196,60 @@ impl ResolvePlugin for InvalidImportResolvePlugin {
async fn after_resolve(
&self,
_fs_path: Vc<FileSystemPath>,
file_path: Vc<FileSystemPath>,
context: Vc<FileSystemPath>,
_reference_type: Value<ReferenceType>,
request: Vc<Request>,
) -> Result<Vc<ResolveResultOption>> {
let imports = if self.import_type == InvalidImportType::ClientOnly {
&*CLIENT_ONLY_IMPORTS
} else {
&*SERVER_ONLY_IMPORTS
};
if let Request::Module {
module,
path,
query: _,
} = &*request.await?
{
if imports.contains(module.as_str()) {
UnsupportedModuleIssue {
file_path,
package: module.into(),
package_path: None,
if let Request::Module { module, .. } = &*request.await? {
if module.as_str() == self.invalid_import.as_str() {
InvalidImportModuleIssue {
file_path: context,
messages: self.message.clone(),
}
.cell()
.emit();
}
if let Pattern::Constant(path) = path {
if imports.contains(path.as_str()) {
InvalidImportModuleIssue {
file_path,
import_type: self.import_type,
}
.cell()
.emit();
}
}
}
Ok(ResolveResultOption::none())
}
}
/// Returns a resolve plugin if context have imports to `client-only`.
/// Only the contexts that alises `client-only` to
/// `next/dist/compiled/client-only/error` should use this.
pub(crate) fn get_invalid_client_only_resolve_plugin(
root: Vc<FileSystemPath>,
) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new(
root,
"client-only".to_string(),
vec![
"'client-only' cannot be imported from a Client Component module. It should only be \
used from a Server Component."
.to_string(),
],
)
}
/// Returns a resolve plugin if context have imports to `server-only`.
/// Only the contexts that alises `server-only` to
/// `next/dist/compiled/server-only/index` should use this.
#[allow(unused)]
pub(crate) fn get_invalid_server_only_resolve_plugin(
root: Vc<FileSystemPath>,
) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new(
root,
"server-only".to_string(),
vec![
"'server-only' cannot be imported from a Client Component module. It should only be \
used from a Server Component."
.to_string(),
],
)
}
#[turbo_tasks::value]
pub(crate) struct NextExternalResolvePlugin {
root: Vc<FileSystemPath>,
......
......@@ -141,7 +141,15 @@ describe('Error Overlay invalid imports', () => {
await session.patch(pageFile, withoutUseClient)
expect(await session.hasRedbox()).toBe(true)
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
if (process.env.TURBOPACK) {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./node_modules/client-only-package
Invalid import
'client-only' cannot be imported from a Client Component module. It should only be used from a Server Component.
The error was caused by importing 'node_modules/client-only-package'"
`)
} else {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./app/comp2.js
'client-only' cannot be imported from a Server Component module. It should only be used from a Client Component.
......@@ -152,6 +160,7 @@ describe('Error Overlay invalid imports', () => {
./app/comp1.js
./app/page.js"
`)
}
await cleanup()
})
......@@ -214,7 +223,15 @@ describe('Error Overlay invalid imports', () => {
await session.patch(file, "'use client'\n" + content)
expect(await session.hasRedbox()).toBe(true)
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
if (process.env.TURBOPACK) {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./node_modules/server-only-package
Invalid import
'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.
The error was caused by importing 'node_modules/server-only-package'"
`)
} else {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./app/comp2.js
'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.
......@@ -225,6 +242,7 @@ describe('Error Overlay invalid imports', () => {
./app/comp1.js
./app/page.js"
`)
}
await cleanup()
})
......
......@@ -1119,9 +1119,10 @@
"runtimeError": false
},
"test/development/acceptance-app/invalid-imports.test.ts": {
"passed": [],
"passed": [
"Error Overlay invalid imports should show error when external package imports client-only in server component"
],
"failed": [
"Error Overlay invalid imports should show error when external package imports client-only in server component",
"Error Overlay invalid imports should show error when external package imports server-only in client component",
"Error Overlay invalid imports should show error when using styled-jsx in server component"
],
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