Unverified Commit 2c6b09d5 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Emit build error when `"use cache"` is used without `dynamicIO` enabled (#72781)

Using a build error instead of a runtime error allows us to fail early,
and show a proper error source in the terminal and in the dev overlay.

<img width="777" alt="Screenshot 2024-11-13 at 22 19 45"
src="https://github.com/user-attachments/assets/d0ee3c69-71f5-4aa6-8c0a-879217f66930">
parent 5c45d58c
...@@ -47,6 +47,12 @@ pub async fn get_next_client_transforms_rules( ...@@ -47,6 +47,12 @@ pub async fn get_next_client_transforms_rules(
rules.push(get_debug_fn_name_rule(enable_mdx_rs)); rules.push(get_debug_fn_name_rule(enable_mdx_rs));
} }
let dynamic_io_enabled = next_config
.experimental()
.await?
.dynamic_io
.unwrap_or(false);
let mut is_app_dir = false; let mut is_app_dir = false;
match context_ty { match context_ty {
...@@ -72,6 +78,7 @@ pub async fn get_next_client_transforms_rules( ...@@ -72,6 +78,7 @@ pub async fn get_next_client_transforms_rules(
rules.push(get_server_actions_transform_rule( rules.push(get_server_actions_transform_rule(
ActionsTransform::Client, ActionsTransform::Client,
enable_mdx_rs, enable_mdx_rs,
dynamic_io_enabled,
)); ));
} }
ClientContextType::Fallback | ClientContextType::Other => {} ClientContextType::Fallback | ClientContextType::Other => {}
......
...@@ -54,6 +54,12 @@ pub async fn get_next_server_transforms_rules( ...@@ -54,6 +54,12 @@ pub async fn get_next_server_transforms_rules(
)); ));
} }
let dynamic_io_enabled = next_config
.experimental()
.await?
.dynamic_io
.unwrap_or(false);
let mut is_app_dir = false; let mut is_app_dir = false;
let is_server_components = match context_ty { let is_server_components = match context_ty {
...@@ -89,6 +95,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -89,6 +95,7 @@ pub async fn get_next_server_transforms_rules(
rules.push(get_server_actions_transform_rule( rules.push(get_server_actions_transform_rule(
ActionsTransform::Client, ActionsTransform::Client,
mdx_rs, mdx_rs,
dynamic_io_enabled,
)); ));
is_app_dir = true; is_app_dir = true;
...@@ -99,6 +106,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -99,6 +106,7 @@ pub async fn get_next_server_transforms_rules(
rules.push(get_server_actions_transform_rule( rules.push(get_server_actions_transform_rule(
ActionsTransform::Server, ActionsTransform::Server,
mdx_rs, mdx_rs,
dynamic_io_enabled,
)); ));
is_app_dir = true; is_app_dir = true;
...@@ -109,6 +117,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -109,6 +117,7 @@ pub async fn get_next_server_transforms_rules(
rules.push(get_server_actions_transform_rule( rules.push(get_server_actions_transform_rule(
ActionsTransform::Server, ActionsTransform::Server,
mdx_rs, mdx_rs,
dynamic_io_enabled,
)); ));
is_app_dir = true; is_app_dir = true;
......
...@@ -18,9 +18,12 @@ pub enum ActionsTransform { ...@@ -18,9 +18,12 @@ pub enum ActionsTransform {
pub fn get_server_actions_transform_rule( pub fn get_server_actions_transform_rule(
transform: ActionsTransform, transform: ActionsTransform,
enable_mdx_rs: bool, enable_mdx_rs: bool,
dynamic_io_enabled: bool,
) -> ModuleRule { ) -> ModuleRule {
let transformer = let transformer = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextServerActions {
EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextServerActions { transform }) as _)); transform,
dynamic_io_enabled,
}) as _));
ModuleRule::new( ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs), module_rule_match_js_no_url(enable_mdx_rs),
vec![ModuleRuleEffect::ExtendEcmascriptTransforms { vec![ModuleRuleEffect::ExtendEcmascriptTransforms {
...@@ -33,6 +36,7 @@ pub fn get_server_actions_transform_rule( ...@@ -33,6 +36,7 @@ pub fn get_server_actions_transform_rule(
#[derive(Debug)] #[derive(Debug)]
struct NextServerActions { struct NextServerActions {
transform: ActionsTransform, transform: ActionsTransform,
dynamic_io_enabled: bool,
} }
#[async_trait] #[async_trait]
...@@ -43,6 +47,7 @@ impl CustomTransformer for NextServerActions { ...@@ -43,6 +47,7 @@ impl CustomTransformer for NextServerActions {
&FileName::Real(ctx.file_path_str.into()), &FileName::Real(ctx.file_path_str.into()),
Config { Config {
is_react_server_layer: matches!(self.transform, ActionsTransform::Server), is_react_server_layer: matches!(self.transform, ActionsTransform::Server),
dynamic_io_enabled: self.dynamic_io_enabled,
hash_salt: "".into(), hash_salt: "".into(),
}, },
ctx.comments.clone(), ctx.comments.clone(),
......
...@@ -26,6 +26,7 @@ use swc_core::{ ...@@ -26,6 +26,7 @@ use swc_core::{
#[serde(deny_unknown_fields, rename_all = "camelCase")] #[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config { pub struct Config {
pub is_react_server_layer: bool, pub is_react_server_layer: bool,
pub dynamic_io_enabled: bool,
pub hash_salt: String, pub hash_salt: String,
} }
...@@ -265,6 +266,7 @@ impl<C: Comments> ServerActions<C> { ...@@ -265,6 +266,7 @@ impl<C: Comments> ServerActions<C> {
&mut is_action_fn, &mut is_action_fn,
&mut cache_type, &mut cache_type,
&mut span, &mut span,
self.config.dynamic_io_enabled,
); );
if !self.config.is_react_server_layer { if !self.config.is_react_server_layer {
...@@ -1301,6 +1303,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1301,6 +1303,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
&mut self.in_cache_file, &mut self.in_cache_file,
&mut self.has_action, &mut self.has_action,
&mut self.has_cache, &mut self.has_cache,
self.config.dynamic_io_enabled,
); );
// If we're in a "use cache" file, collect all original IDs from export // If we're in a "use cache" file, collect all original IDs from export
...@@ -2355,6 +2358,7 @@ fn remove_server_directive_index_in_module( ...@@ -2355,6 +2358,7 @@ fn remove_server_directive_index_in_module(
in_cache_file: &mut Option<String>, in_cache_file: &mut Option<String>,
has_action: &mut bool, has_action: &mut bool,
has_cache: &mut bool, has_cache: &mut bool,
dynamic_io_enabled: bool,
) { ) {
let mut is_directive = true; let mut is_directive = true;
...@@ -2383,6 +2387,21 @@ fn remove_server_directive_index_in_module( ...@@ -2383,6 +2387,21 @@ fn remove_server_directive_index_in_module(
// `use cache` or `use cache: foo` // `use cache` or `use cache: foo`
if value == "use cache" || value.starts_with("use cache: ") { if value == "use cache" || value.starts_with("use cache: ") {
if is_directive { if is_directive {
if !dynamic_io_enabled {
HANDLER.with(|handler| {
handler
.struct_span_err(
*span,
format!(
"To use \"{value}\", please enable the experimental feature flag \"dynamicIO\" in your Next.js config.\n\n\
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage\n"
)
.as_str(),
)
.emit();
})
}
*in_cache_file = Some(if value == "use cache" { *in_cache_file = Some(if value == "use cache" {
"default".into() "default".into()
} else { } else {
...@@ -2518,6 +2537,7 @@ fn remove_server_directive_index_in_fn( ...@@ -2518,6 +2537,7 @@ fn remove_server_directive_index_in_fn(
is_action_fn: &mut bool, is_action_fn: &mut bool,
cache_type: &mut Option<String>, cache_type: &mut Option<String>,
action_span: &mut Option<Span>, action_span: &mut Option<Span>,
dynamic_io_enabled: bool,
) { ) {
let mut is_directive = true; let mut is_directive = true;
...@@ -2560,6 +2580,21 @@ fn remove_server_directive_index_in_fn( ...@@ -2560,6 +2580,21 @@ fn remove_server_directive_index_in_fn(
}); });
} else if value == "use cache" || value.starts_with("use cache: ") { } else if value == "use cache" || value.starts_with("use cache: ") {
if is_directive { if is_directive {
if !dynamic_io_enabled {
HANDLER.with(|handler| {
handler
.struct_span_err(
*span,
format!(
"To use \"{value}\", please enable the experimental feature flag \"dynamicIO\" in your Next.js config.\n\n\
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage\n"
)
.as_str(),
)
.emit();
})
}
*cache_type = Some(if value == "use cache" { *cache_type = Some(if value == "use cache" {
"default".into() "default".into()
} else { } else {
......
...@@ -176,7 +176,7 @@ fn react_server_actions_server_errors(input: PathBuf) { ...@@ -176,7 +176,7 @@ fn react_server_actions_server_errors(input: PathBuf) {
FileName::Real(PathBuf::from("/app/item.js")).into(), FileName::Real(PathBuf::from("/app/item.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: false, dynamic_io_enabled: true,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
...@@ -185,6 +185,7 @@ fn react_server_actions_server_errors(input: PathBuf) { ...@@ -185,6 +185,7 @@ fn react_server_actions_server_errors(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
}, },
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
...@@ -214,7 +215,7 @@ fn react_server_actions_client_errors(input: PathBuf) { ...@@ -214,7 +215,7 @@ fn react_server_actions_client_errors(input: PathBuf) {
FileName::Real(PathBuf::from("/app/item.js")).into(), FileName::Real(PathBuf::from("/app/item.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: false, dynamic_io_enabled: true,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
...@@ -223,6 +224,7 @@ fn react_server_actions_client_errors(input: PathBuf) { ...@@ -223,6 +224,7 @@ fn react_server_actions_client_errors(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
}, },
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
...@@ -256,3 +258,42 @@ fn next_transform_strip_page_exports_errors(input: PathBuf) { ...@@ -256,3 +258,42 @@ fn next_transform_strip_page_exports_errors(input: PathBuf) {
}, },
); );
} }
#[fixture("tests/errors/use-cache-not-allowed/**/input.js")]
fn use_cache_not_allowed(input: PathBuf) {
use next_custom_transforms::transforms::react_server_components::{Config, Options};
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|tr| {
(
resolver(Mark::new(), Mark::new(), false),
server_components(
FileName::Real(PathBuf::from("/app/item.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: true,
dynamic_io_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
),
server_actions(
&FileName::Real("/app/item.js".into()),
server_actions::Config {
is_react_server_layer: true,
dynamic_io_enabled: false,
hash_salt: "".into(),
},
tr.comments.as_ref().clone(),
),
)
},
&input,
&output,
FixtureTestConfig {
allow_error: true,
module: Some(true),
..Default::default()
},
);
}
'use cache'
export default async function Page() {
return <p>hello world</p>
}
/* __next_internal_action_entry_do_not_use__ {"803128060c414d59f8552e4788b846c0d2b7f74743":"$$RSC_SERVER_CACHE_0"} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
export var $$RSC_SERVER_CACHE_0 = $$cache__("default", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, async function Page() {
return <p>hello world</p>;
});
Object.defineProperty($$RSC_SERVER_CACHE_0, "name", {
"value": "Page",
"writable": false
});
export default registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
|
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
|
,-[input.js:1:1]
1 | 'use cache'
: ^^^^^^^^^^^
`----
export default async function Page() {
'use cache: x'
return <p>hello world</p>
}
/* __next_internal_action_entry_do_not_use__ {"803128060c414d59f8552e4788b846c0d2b7f74743":"$$RSC_SERVER_CACHE_0"} */ import { registerServerReference } from "private-next-rsc-server-reference";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
export var $$RSC_SERVER_CACHE_0 = $$cache__("x", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, async function Page() {
return <p>hello world</p>;
});
Object.defineProperty($$RSC_SERVER_CACHE_0, "name", {
"value": "Page",
"writable": false
});
export default registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
x To use "use cache: x", please enable the experimental feature flag "dynamicIO" in your Next.js config.
|
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
|
,-[input.js:2:1]
1 | export default async function Page() {
2 | 'use cache: x'
: ^^^^^^^^^^^^^^
`----
...@@ -414,6 +414,7 @@ fn server_actions_server_fixture(input: PathBuf) { ...@@ -414,6 +414,7 @@ fn server_actions_server_fixture(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
}, },
_tr.comments.as_ref().clone(), _tr.comments.as_ref().clone(),
...@@ -445,6 +446,7 @@ fn next_font_with_directive_fixture(input: PathBuf) { ...@@ -445,6 +446,7 @@ fn next_font_with_directive_fixture(input: PathBuf) {
&FileName::Real("/app/test.tsx".into()), &FileName::Real("/app/test.tsx".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
}, },
_tr.comments.as_ref().clone(), _tr.comments.as_ref().clone(),
...@@ -469,6 +471,7 @@ fn server_actions_client_fixture(input: PathBuf) { ...@@ -469,6 +471,7 @@ fn server_actions_client_fixture(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
}, },
_tr.comments.as_ref().clone(), _tr.comments.as_ref().clone(),
......
...@@ -209,6 +209,7 @@ function getBaseSWCOptions({ ...@@ -209,6 +209,7 @@ function getBaseSWCOptions({
isAppRouterPagesLayer && !jest isAppRouterPagesLayer && !jest
? { ? {
isReactServerLayer, isReactServerLayer,
dynamicIoEnabled: isDynamicIo,
hashSalt: serverReferenceHashSalt, hashSalt: serverReferenceHashSalt,
} }
: undefined, : undefined,
......
...@@ -441,11 +441,6 @@ export function cache( ...@@ -441,11 +441,6 @@ export function cache(
boundArgsLength: number, boundArgsLength: number,
fn: any fn: any
) { ) {
if (!process.env.__NEXT_DYNAMIC_IO) {
throw new Error(
'"use cache" is only available with the experimental.dynamicIO config.'
)
}
for (const [key, value] of Object.entries( for (const [key, value] of Object.entries(
_globalThis.__nextCacheHandlers || {} _globalThis.__nextCacheHandlers || {}
)) { )) {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use cache'
export default async function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { NextConfig } from 'next'
import {
assertHasRedbox,
assertNoRedbox,
getRedboxDescription,
getRedboxSource,
retry,
} from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const nextConfigWithDynamicIO: NextConfig = {
experimental: { dynamicIO: true },
}
describe('use-cache-without-dynamic-io', () => {
const { next, isNextStart, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextStart) {
it('should fail the build with an error', async () => {
const { cliOutput } = await next.build()
const buildOutput = getBuildOutput(cliOutput)
if (isTurbopack) {
expect(buildOutput).toMatchInlineSnapshot(`
"Error: Turbopack build failed with 1 errors:
Page: {"type":"app","side":"server","page":"/page"}
./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache'
| ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
at <unknown> (./app/page.tsx:1:1)"
`)
} else {
expect(buildOutput).toMatchInlineSnapshot(`
"
./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
|
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----
Import trace for requested module:
./app/page.tsx
> Build failed because of webpack errors
"
`)
}
})
} else {
it('should show a build error', async () => {
const browser = await next.browser('/')
await assertHasRedbox(browser)
const errorDescription = await getRedboxDescription(browser)
const errorSource = await getRedboxSource(browser)
expect(errorDescription).toBe('Failed to compile')
if (isTurbopack) {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache'
| ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage"
`)
} else {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
|
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----"
`)
}
})
it('should recover from the build error if dynamicIO flag is set', async () => {
const browser = await next.browser('/')
await assertHasRedbox(browser)
await next.patchFile(
'next.config.js',
`module.exports = ${JSON.stringify(nextConfigWithDynamicIO)}`,
() =>
retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('hello world')
await assertNoRedbox(browser)
})
)
})
}
})
function getBuildOutput(cliOutput: string): string {
const lines: string[] = []
let skipLines = true
for (const line of cliOutput.split('\n')) {
if (!skipLines) {
if (line.includes('at turbopackBuild')) {
break
}
lines.push(stripAnsi(line))
} else if (
line.includes('Build error occurred') ||
line.includes('Failed to compile')
) {
skipLines = false
}
}
return lines.join('\n')
}
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