Unverified Commit d54122a7 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Emit build error for unknown cache kinds (#72832)

When a `"use cache"` directive with a custom cache kind is used, e.g.
`"use cache: custom"`, a cache handler with the same name must be
specified in the Next.js config:

```js
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  experimental: {
    dynamicIO: true,
    cacheHandlers: {
      custom: require.resolve('path/to/custom/cache/handler'),
    },
  },
}

module.exports = nextConfig
```

If this is not the case, we emit a build error with an error message
that explains this requirement.

<img width="795" alt="Screenshot 2024-11-14 at 23 30 01"
src="https://github.com/user-attachments/assets/bd138c97-608f-42ce-abb2-edb3e44edc3f">

When we'll get a docs page for this experimental config, we will add the
usual "Read more: ..." hint as well.

---------
Co-authored-by: 's avatarBenjamin Woodruff <benjamin.woodruff@vercel.com>
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent ef9d0969
...@@ -4086,6 +4086,7 @@ dependencies = [ ...@@ -4086,6 +4086,7 @@ dependencies = [
"swc_relay", "swc_relay",
"testing", "testing",
"tracing", "tracing",
"turbo-rcstr",
"turbopack-ecmascript-plugins", "turbopack-ecmascript-plugins",
"walkdir", "walkdir",
] ]
......
...@@ -47,12 +47,8 @@ pub async fn get_next_client_transforms_rules( ...@@ -47,12 +47,8 @@ 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 let dynamic_io_enabled = *next_config.enable_dynamic_io().await?;
.experimental() let cache_kinds = next_config.cache_kinds().to_resolved().await?;
.await?
.dynamic_io
.unwrap_or(false);
let mut is_app_dir = false; let mut is_app_dir = false;
match context_ty { match context_ty {
...@@ -79,6 +75,7 @@ pub async fn get_next_client_transforms_rules( ...@@ -79,6 +75,7 @@ pub async fn get_next_client_transforms_rules(
ActionsTransform::Client, ActionsTransform::Client,
enable_mdx_rs, enable_mdx_rs,
dynamic_io_enabled, dynamic_io_enabled,
cache_kinds,
)); ));
} }
ClientContextType::Fallback | ClientContextType::Other => {} ClientContextType::Fallback | ClientContextType::Other => {}
......
use std::collections::HashSet; use std::collections::HashSet;
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use rustc_hash::FxHashSet;
use serde::{Deserialize, Deserializer, Serialize}; use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
...@@ -40,6 +41,9 @@ struct CustomRoutes { ...@@ -40,6 +41,9 @@ struct CustomRoutes {
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct ModularizeImports(FxIndexMap<String, ModularizeImportPackageConfig>); pub struct ModularizeImports(FxIndexMap<String, ModularizeImportPackageConfig>);
#[turbo_tasks::value(transparent)]
pub struct CacheKinds(FxHashSet<RcStr>);
#[turbo_tasks::value(serialization = "custom", eq = "manual")] #[turbo_tasks::value(serialization = "custom", eq = "manual")]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
...@@ -520,7 +524,7 @@ pub struct ExperimentalConfig { ...@@ -520,7 +524,7 @@ pub struct ExperimentalConfig {
pub sri: Option<SubResourceIntegrity>, pub sri: Option<SubResourceIntegrity>,
react_compiler: Option<ReactCompilerOptionsOrBoolean>, react_compiler: Option<ReactCompilerOptionsOrBoolean>,
#[serde(rename = "dynamicIO")] #[serde(rename = "dynamicIO")]
pub dynamic_io: Option<bool>, dynamic_io: Option<bool>,
// --- // ---
// UNSUPPORTED // UNSUPPORTED
// --- // ---
...@@ -529,6 +533,7 @@ pub struct ExperimentalConfig { ...@@ -529,6 +533,7 @@ pub struct ExperimentalConfig {
after: Option<bool>, after: Option<bool>,
amp: Option<serde_json::Value>, amp: Option<serde_json::Value>,
app_document_preloading: Option<bool>, app_document_preloading: Option<bool>,
cache_handlers: Option<FxIndexMap<RcStr, RcStr>>,
cache_life: Option<FxIndexMap<String, CacheLifeProfile>>, cache_life: Option<FxIndexMap<String, CacheLifeProfile>>,
case_sensitive_routes: Option<bool>, case_sensitive_routes: Option<bool>,
cpus: Option<f64>, cpus: Option<f64>,
...@@ -1150,10 +1155,24 @@ impl NextConfig { ...@@ -1150,10 +1155,24 @@ impl NextConfig {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn enable_react_owner_stack(self: Vc<Self>) -> Result<Vc<bool>> { pub fn enable_react_owner_stack(&self) -> Vc<bool> {
Ok(Vc::cell( Vc::cell(self.experimental.react_owner_stack.unwrap_or(false))
self.await?.experimental.react_owner_stack.unwrap_or(false), }
))
#[turbo_tasks::function]
pub fn enable_dynamic_io(&self) -> Vc<bool> {
Vc::cell(self.experimental.dynamic_io.unwrap_or(false))
}
#[turbo_tasks::function]
pub fn cache_kinds(&self) -> Vc<CacheKinds> {
Vc::cell(
self.experimental
.cache_handlers
.as_ref()
.map(|handlers| handlers.keys().cloned().collect())
.unwrap_or_default(),
)
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -54,12 +54,8 @@ pub async fn get_next_server_transforms_rules( ...@@ -54,12 +54,8 @@ pub async fn get_next_server_transforms_rules(
)); ));
} }
let dynamic_io_enabled = next_config let dynamic_io_enabled = *next_config.enable_dynamic_io().await?;
.experimental() let cache_kinds = next_config.cache_kinds().to_resolved().await?;
.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 {
...@@ -96,6 +92,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -96,6 +92,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Client, ActionsTransform::Client,
mdx_rs, mdx_rs,
dynamic_io_enabled, dynamic_io_enabled,
cache_kinds,
)); ));
is_app_dir = true; is_app_dir = true;
...@@ -107,6 +104,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -107,6 +104,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server, ActionsTransform::Server,
mdx_rs, mdx_rs,
dynamic_io_enabled, dynamic_io_enabled,
cache_kinds,
)); ));
is_app_dir = true; is_app_dir = true;
...@@ -118,6 +116,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -118,6 +116,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server, ActionsTransform::Server,
mdx_rs, mdx_rs,
dynamic_io_enabled, dynamic_io_enabled,
cache_kinds,
)); ));
is_app_dir = true; is_app_dir = true;
......
...@@ -34,11 +34,7 @@ pub async fn get_next_react_server_components_transform_rule( ...@@ -34,11 +34,7 @@ pub async fn get_next_react_server_components_transform_rule(
app_dir: Option<Vc<FileSystemPath>>, app_dir: Option<Vc<FileSystemPath>>,
) -> Result<ModuleRule> { ) -> Result<ModuleRule> {
let enable_mdx_rs = next_config.mdx_rs().await?.is_some(); let enable_mdx_rs = next_config.mdx_rs().await?.is_some();
let dynamic_io_enabled = next_config let dynamic_io_enabled = *next_config.enable_dynamic_io().await?;
.experimental()
.await?
.dynamic_io
.unwrap_or(false);
Ok(get_ecma_transform_rule( Ok(get_ecma_transform_rule(
Box::new(NextJsReactServerComponents::new( Box::new(NextJsReactServerComponents::new(
is_react_server_layer, is_react_server_layer,
......
...@@ -7,6 +7,7 @@ use turbopack::module_options::{ModuleRule, ModuleRuleEffect}; ...@@ -7,6 +7,7 @@ use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext}; use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext};
use super::module_rule_match_js_no_url; use super::module_rule_match_js_no_url;
use crate::next_config::CacheKinds;
#[derive(Debug)] #[derive(Debug)]
pub enum ActionsTransform { pub enum ActionsTransform {
...@@ -19,11 +20,13 @@ pub fn get_server_actions_transform_rule( ...@@ -19,11 +20,13 @@ pub fn get_server_actions_transform_rule(
transform: ActionsTransform, transform: ActionsTransform,
enable_mdx_rs: bool, enable_mdx_rs: bool,
dynamic_io_enabled: bool, dynamic_io_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>,
) -> ModuleRule { ) -> ModuleRule {
let transformer = let transformer =
EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextServerActions { EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextServerActions {
transform, transform,
dynamic_io_enabled, dynamic_io_enabled,
cache_kinds,
}) as _)); }) as _));
ModuleRule::new( ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs), module_rule_match_js_no_url(enable_mdx_rs),
...@@ -38,6 +41,7 @@ pub fn get_server_actions_transform_rule( ...@@ -38,6 +41,7 @@ pub fn get_server_actions_transform_rule(
struct NextServerActions { struct NextServerActions {
transform: ActionsTransform, transform: ActionsTransform,
dynamic_io_enabled: bool, dynamic_io_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>,
} }
#[async_trait] #[async_trait]
...@@ -50,6 +54,7 @@ impl CustomTransformer for NextServerActions { ...@@ -50,6 +54,7 @@ impl CustomTransformer for NextServerActions {
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, dynamic_io_enabled: self.dynamic_io_enabled,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: self.cache_kinds.await?.clone_value(),
}, },
ctx.comments.clone(), ctx.comments.clone(),
); );
......
...@@ -56,6 +56,7 @@ styled_jsx = { workspace = true } ...@@ -56,6 +56,7 @@ styled_jsx = { workspace = true }
swc_emotion = { workspace = true } swc_emotion = { workspace = true }
swc_relay = { workspace = true } swc_relay = { workspace = true }
turbopack-ecmascript-plugins = { workspace = true, optional = true } turbopack-ecmascript-plugins = { workspace = true, optional = true }
turbo-rcstr = { workspace = true }
react_remove_properties = "0.24.25" react_remove_properties = "0.24.25"
remove_console = "0.25.25" remove_console = "0.25.25"
......
use std::path::PathBuf; use std::{iter::FromIterator, path::PathBuf};
use next_custom_transforms::transforms::{ use next_custom_transforms::transforms::{
disallow_re_export_all_in_page::disallow_re_export_all_in_page, disallow_re_export_all_in_page::disallow_re_export_all_in_page,
...@@ -11,6 +11,7 @@ use next_custom_transforms::transforms::{ ...@@ -11,6 +11,7 @@ use next_custom_transforms::transforms::{
}, },
strip_page_exports::{next_transform_strip_page_exports, ExportFilter}, strip_page_exports::{next_transform_strip_page_exports, ExportFilter},
}; };
use rustc_hash::FxHashSet;
use swc_core::{ use swc_core::{
common::{FileName, Mark}, common::{FileName, Mark},
ecma::{ ecma::{
...@@ -187,6 +188,7 @@ fn react_server_actions_server_errors(input: PathBuf) { ...@@ -187,6 +188,7 @@ fn react_server_actions_server_errors(input: PathBuf) {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true, dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
}, },
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
), ),
...@@ -226,6 +228,7 @@ fn react_server_actions_client_errors(input: PathBuf) { ...@@ -226,6 +228,7 @@ fn react_server_actions_client_errors(input: PathBuf) {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: true, dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
}, },
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
), ),
...@@ -283,6 +286,7 @@ fn use_cache_not_allowed(input: PathBuf) { ...@@ -283,6 +286,7 @@ fn use_cache_not_allowed(input: PathBuf) {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: false, dynamic_io_enabled: false,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]),
}, },
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
), ),
......
'use cache: x'
export async function foo() {
return 'data'
}
/* __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 foo() {
return 'data';
});
Object.defineProperty($$RSC_SERVER_CACHE_0, "name", {
"value": "foo",
"writable": false
});
export var foo = registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
x Unknown cache kind "x". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config.
|
,-[input.js:1:1]
1 | 'use cache: x'
: ^^^^^^^^^^^^^^
`----
export async function foo() {
'use cache: x'
return 'data'
}
/* __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 foo() {
return 'data';
});
Object.defineProperty($$RSC_SERVER_CACHE_0, "name", {
"value": "foo",
"writable": false
});
export var foo = registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
x Unknown cache kind "x". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config.
|
,-[input.js:2:1]
1 | export async function foo() {
2 | 'use cache: x'
: ^^^^^^^^^^^^^^
`----
use std::{ use std::{
env::current_dir, env::current_dir,
iter::FromIterator,
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
...@@ -21,6 +22,7 @@ use next_custom_transforms::transforms::{ ...@@ -21,6 +22,7 @@ use next_custom_transforms::transforms::{
strip_page_exports::{next_transform_strip_page_exports, ExportFilter}, strip_page_exports::{next_transform_strip_page_exports, ExportFilter},
warn_for_edge_runtime::warn_for_edge_runtime, warn_for_edge_runtime::warn_for_edge_runtime,
}; };
use rustc_hash::FxHashSet;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use swc_core::{ use swc_core::{
common::{comments::SingleThreadedComments, FileName, Mark, SyntaxContext}, common::{comments::SingleThreadedComments, FileName, Mark, SyntaxContext},
...@@ -416,6 +418,7 @@ fn server_actions_server_fixture(input: PathBuf) { ...@@ -416,6 +418,7 @@ fn server_actions_server_fixture(input: PathBuf) {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true, dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]),
}, },
_tr.comments.as_ref().clone(), _tr.comments.as_ref().clone(),
), ),
...@@ -448,6 +451,7 @@ fn next_font_with_directive_fixture(input: PathBuf) { ...@@ -448,6 +451,7 @@ fn next_font_with_directive_fixture(input: PathBuf) {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true, dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
}, },
_tr.comments.as_ref().clone(), _tr.comments.as_ref().clone(),
), ),
...@@ -473,6 +477,7 @@ fn server_actions_client_fixture(input: PathBuf) { ...@@ -473,6 +477,7 @@ fn server_actions_client_fixture(input: PathBuf) {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: true, dynamic_io_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
}, },
_tr.comments.as_ref().clone(), _tr.comments.as_ref().clone(),
), ),
......
...@@ -65,6 +65,7 @@ function getBaseSWCOptions({ ...@@ -65,6 +65,7 @@ function getBaseSWCOptions({
serverReferenceHashSalt, serverReferenceHashSalt,
bundleLayer, bundleLayer,
isDynamicIo, isDynamicIo,
cacheHandlers,
}: { }: {
filename: string filename: string
jest?: boolean jest?: boolean
...@@ -82,6 +83,7 @@ function getBaseSWCOptions({ ...@@ -82,6 +83,7 @@ function getBaseSWCOptions({
serverReferenceHashSalt: string serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName bundleLayer?: WebpackLayerName
isDynamicIo?: boolean isDynamicIo?: boolean
cacheHandlers?: ExperimentalConfig['cacheHandlers']
}) { }) {
const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer) const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer)
const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer) const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer)
...@@ -211,6 +213,7 @@ function getBaseSWCOptions({ ...@@ -211,6 +213,7 @@ function getBaseSWCOptions({
isReactServerLayer, isReactServerLayer,
dynamicIoEnabled: isDynamicIo, dynamicIoEnabled: isDynamicIo,
hashSalt: serverReferenceHashSalt, hashSalt: serverReferenceHashSalt,
cacheKinds: cacheHandlers ? Object.keys(cacheHandlers) : [],
} }
: undefined, : undefined,
// For app router we prefer to bundle ESM, // For app router we prefer to bundle ESM,
...@@ -355,6 +358,7 @@ export function getLoaderSWCOptions({ ...@@ -355,6 +358,7 @@ export function getLoaderSWCOptions({
serverReferenceHashSalt, serverReferenceHashSalt,
bundleLayer, bundleLayer,
esm, esm,
cacheHandlers,
}: { }: {
filename: string filename: string
development: boolean development: boolean
...@@ -379,6 +383,7 @@ export function getLoaderSWCOptions({ ...@@ -379,6 +383,7 @@ export function getLoaderSWCOptions({
serverComponents?: boolean serverComponents?: boolean
serverReferenceHashSalt: string serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName bundleLayer?: WebpackLayerName
cacheHandlers: ExperimentalConfig['cacheHandlers']
}) { }) {
let baseOptions: any = getBaseSWCOptions({ let baseOptions: any = getBaseSWCOptions({
filename, filename,
...@@ -396,6 +401,7 @@ export function getLoaderSWCOptions({ ...@@ -396,6 +401,7 @@ export function getLoaderSWCOptions({
serverReferenceHashSalt, serverReferenceHashSalt,
esm: !!esm, esm: !!esm,
isDynamicIo, isDynamicIo,
cacheHandlers,
}) })
baseOptions.fontLoaders = { baseOptions.fontLoaders = {
fontLoaders: ['next/font/local', 'next/font/google'], fontLoaders: ['next/font/local', 'next/font/google'],
......
...@@ -142,6 +142,7 @@ async function loaderTransform( ...@@ -142,6 +142,7 @@ async function loaderTransform(
serverReferenceHashSalt, serverReferenceHashSalt,
bundleLayer, bundleLayer,
esm, esm,
cacheHandlers: nextConfig.experimental?.cacheHandlers,
}) })
const programmaticOptions = { const programmaticOptions = {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use cache: custom'
export default async function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
dynamicIO: true,
},
}
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 nextConfigWithCacheHandler: NextConfig = {
experimental: {
dynamicIO: true,
cacheHandlers: {
custom: require.resolve('next/dist/server/lib/cache-handlers/default'),
},
},
}
describe('use-cache-unknown-cache-kind', () => {
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: custom'
| ^^^^^^^^^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
Unknown cache kind "custom". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config.
at <unknown> (./app/page.tsx:1:1)"
`)
} else {
expect(buildOutput).toMatchInlineSnapshot(`
"
./app/page.tsx
Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config.
|
,-[1:1]
1 | 'use cache: custom'
: ^^^^^^^^^^^^^^^^^^^
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: custom'
| ^^^^^^^^^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
Unknown cache kind "custom". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config."
`)
} else {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx
Error: x Unknown cache kind "custom". Please configure a cache handler for this kind in the "experimental.cacheHandlers" object in your Next.js config.
|
,-[1:1]
1 | 'use cache: custom'
: ^^^^^^^^^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----"
`)
}
})
it('should recover from the build error if the cache handler is defined', async () => {
const browser = await next.browser('/')
await assertHasRedbox(browser)
await next.patchFile(
'next.config.js',
`module.exports = ${JSON.stringify(nextConfigWithCacheHandler)}`,
() =>
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