Unverified Commit 3a87f000 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Change the Server Actions feature flag to be validated at compile time (#52147)

Currently we are validating the `experimental.serverActions` flag when creating the actual entries for Server Actions, this causes two problems. One is that syntax errors caught at compilation time are still shown, even if you don't have this flag enabled. Another problem is we still traverse the client graph to collect these action modules even if the flag isn't enabled.

This PR moves that check to be happening at compilation time, which addresses the two above but also brings the extra benefit of showing the exact span and module trace that errors:

<img width="974" alt="CleanShot 2023-07-03 at 20 26 34@2x" src="https://github.com/vercel/next.js/assets/3676859/1676b1f6-e205-4963-bce4-5b515a698e9c">
parent cd9372c1
...@@ -22,6 +22,7 @@ use turbopack_binding::swc::core::{ ...@@ -22,6 +22,7 @@ use turbopack_binding::swc::core::{
#[serde(deny_unknown_fields, rename_all = "camelCase")] #[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config { pub struct Config {
pub is_server: bool, pub is_server: bool,
pub enabled: bool
} }
pub fn server_actions<C: Comments>( pub fn server_actions<C: Comments>(
...@@ -101,6 +102,7 @@ impl<C: Comments> ServerActions<C> { ...@@ -101,6 +102,7 @@ impl<C: Comments> ServerActions<C> {
&mut body.stmts, &mut body.stmts,
remove_directive, remove_directive,
&mut is_action_fn, &mut is_action_fn,
self.config.enabled,
); );
if is_action_fn && !self.config.is_server { if is_action_fn && !self.config.is_server {
...@@ -721,6 +723,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -721,6 +723,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
stmts, stmts,
&mut self.in_action_file, &mut self.in_action_file,
&mut self.has_action, &mut self.has_action,
self.config.enabled,
); );
let old_annotations = self.annotations.take(); let old_annotations = self.annotations.take();
...@@ -1231,6 +1234,7 @@ fn remove_server_directive_index_in_module( ...@@ -1231,6 +1234,7 @@ fn remove_server_directive_index_in_module(
stmts: &mut Vec<ModuleItem>, stmts: &mut Vec<ModuleItem>,
in_action_file: &mut bool, in_action_file: &mut bool,
has_action: &mut bool, has_action: &mut bool,
enabled: bool,
) { ) {
let mut is_directive = true; let mut is_directive = true;
...@@ -1244,6 +1248,16 @@ fn remove_server_directive_index_in_module( ...@@ -1244,6 +1248,16 @@ fn remove_server_directive_index_in_module(
if is_directive { if is_directive {
*in_action_file = true; *in_action_file = true;
*has_action = true; *has_action = true;
if !enabled {
HANDLER.with(|handler| {
handler
.struct_span_err(
*span,
"To use Server Actions, please enable the feature flag in your Next.js config. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#convention",
)
.emit()
});
}
return false; return false;
} else { } else {
HANDLER.with(|handler| { HANDLER.with(|handler| {
...@@ -1320,6 +1334,7 @@ fn remove_server_directive_index_in_fn( ...@@ -1320,6 +1334,7 @@ fn remove_server_directive_index_in_fn(
stmts: &mut Vec<Stmt>, stmts: &mut Vec<Stmt>,
remove_directive: bool, remove_directive: bool,
is_action_fn: &mut bool, is_action_fn: &mut bool,
enabled: bool,
) { ) {
let mut is_directive = true; let mut is_directive = true;
...@@ -1332,6 +1347,16 @@ fn remove_server_directive_index_in_fn( ...@@ -1332,6 +1347,16 @@ fn remove_server_directive_index_in_fn(
if value == "use server" { if value == "use server" {
if is_directive { if is_directive {
*is_action_fn = true; *is_action_fn = true;
if !enabled {
HANDLER.with(|handler| {
handler
.struct_span_err(
*span,
"To use Server Actions, please enable the feature flag in your Next.js config. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#convention",
)
.emit()
});
}
if remove_directive { if remove_directive {
return false; return false;
} }
......
...@@ -43,6 +43,7 @@ function getBaseSWCOptions({ ...@@ -43,6 +43,7 @@ function getBaseSWCOptions({
swcCacheDir, swcCacheDir,
isServerLayer, isServerLayer,
hasServerComponents, hasServerComponents,
isServerActionsEnabled,
}: { }: {
filename: string filename: string
jest?: boolean jest?: boolean
...@@ -57,6 +58,7 @@ function getBaseSWCOptions({ ...@@ -57,6 +58,7 @@ function getBaseSWCOptions({
swcCacheDir?: string swcCacheDir?: string
isServerLayer?: boolean isServerLayer?: boolean
hasServerComponents?: boolean hasServerComponents?: boolean
isServerActionsEnabled?: boolean
}) { }) {
const parserConfig = getParserOptions({ filename, jsConfig }) const parserConfig = getParserOptions({ filename, jsConfig })
const paths = jsConfig?.compilerOptions?.paths const paths = jsConfig?.compilerOptions?.paths
...@@ -157,6 +159,8 @@ function getBaseSWCOptions({ ...@@ -157,6 +159,8 @@ function getBaseSWCOptions({
: undefined, : undefined,
serverActions: hasServerComponents serverActions: hasServerComponents
? { ? {
// TODO-APP: When Server Actions is stable, we need to remove this flag.
enabled: !!isServerActionsEnabled,
isServer: !!isServerLayer, isServer: !!isServerLayer,
} }
: undefined, : undefined,
...@@ -285,6 +289,7 @@ export function getLoaderSWCOptions({ ...@@ -285,6 +289,7 @@ export function getLoaderSWCOptions({
relativeFilePathFromRoot, relativeFilePathFromRoot,
hasServerComponents, hasServerComponents,
isServerLayer, isServerLayer,
isServerActionsEnabled,
}: // This is not passed yet as "paths" resolving is handled by webpack currently. }: // This is not passed yet as "paths" resolving is handled by webpack currently.
// resolvedBaseUrl, // resolvedBaseUrl,
{ {
...@@ -304,6 +309,7 @@ export function getLoaderSWCOptions({ ...@@ -304,6 +309,7 @@ export function getLoaderSWCOptions({
relativeFilePathFromRoot: string relativeFilePathFromRoot: string
hasServerComponents?: boolean hasServerComponents?: boolean
isServerLayer: boolean isServerLayer: boolean
isServerActionsEnabled?: boolean
}) { }) {
let baseOptions: any = getBaseSWCOptions({ let baseOptions: any = getBaseSWCOptions({
filename, filename,
...@@ -318,6 +324,7 @@ export function getLoaderSWCOptions({ ...@@ -318,6 +324,7 @@ export function getLoaderSWCOptions({
swcCacheDir, swcCacheDir,
hasServerComponents, hasServerComponents,
isServerLayer, isServerLayer,
isServerActionsEnabled,
}) })
baseOptions.fontLoaders = { baseOptions.fontLoaders = {
fontLoaders: [ fontLoaders: [
......
...@@ -73,6 +73,7 @@ async function loaderTransform( ...@@ -73,6 +73,7 @@ async function loaderTransform(
swcCacheDir, swcCacheDir,
relativeFilePathFromRoot, relativeFilePathFromRoot,
hasServerComponents, hasServerComponents,
isServerActionsEnabled: nextConfig?.experimental?.serverActions,
isServerLayer, isServerLayer,
}) })
......
...@@ -350,21 +350,13 @@ export class FlightClientEntryPlugin { ...@@ -350,21 +350,13 @@ export class FlightClientEntryPlugin {
) )
if (actionEntryImports.size > 0) { if (actionEntryImports.size > 0) {
if (!this.useServerActions) { if (!actionMapsPerEntry[name]) {
compilation.errors.push( actionMapsPerEntry[name] = new Map()
new Error(
'Server Actions require `experimental.serverActions` option to be enabled in your Next.js config: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions'
)
)
} else {
if (!actionMapsPerEntry[name]) {
actionMapsPerEntry[name] = new Map()
}
actionMapsPerEntry[name] = new Map([
...actionMapsPerEntry[name],
...actionEntryImports,
])
} }
actionMapsPerEntry[name] = new Map([
...actionMapsPerEntry[name],
...actionEntryImports,
])
} }
}) })
...@@ -388,31 +380,28 @@ export class FlightClientEntryPlugin { ...@@ -388,31 +380,28 @@ export class FlightClientEntryPlugin {
) )
} }
compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, () => { if (this.useServerActions) {
const addedClientActionEntryList: Promise<any>[] = [] compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, () => {
const actionMapsPerClientEntry: Record<string, Map<string, string[]>> = {} const addedClientActionEntryList: Promise<any>[] = []
const actionMapsPerClientEntry: Record<
// We need to create extra action entries that are created from the string,
// client layer. Map<string, string[]>
// Start from each entry's created SSR dependency from our previous step. > = {}
for (const [name, ssrEntryDepdendencies] of Object.entries(
createdSSRDependenciesForEntry // We need to create extra action entries that are created from the
)) { // client layer.
// Collect from all entries, e.g. layout.js, page.js, loading.js, ... // Start from each entry's created SSR dependency from our previous step.
// add agregate them. for (const [name, ssrEntryDepdendencies] of Object.entries(
const actionEntryImports = this.collectClientActionsFromDependencies({ createdSSRDependenciesForEntry
compilation, )) {
dependencies: ssrEntryDepdendencies, // Collect from all entries, e.g. layout.js, page.js, loading.js, ...
}) // add agregate them.
const actionEntryImports = this.collectClientActionsFromDependencies({
compilation,
dependencies: ssrEntryDepdendencies,
})
if (actionEntryImports.size > 0) { if (actionEntryImports.size > 0) {
if (!this.useServerActions) {
compilation.errors.push(
new Error(
'Server Actions require `experimental.serverActions` option to be enabled in your Next.js config: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions'
)
)
} else {
if (!actionMapsPerClientEntry[name]) { if (!actionMapsPerClientEntry[name]) {
actionMapsPerClientEntry[name] = new Map() actionMapsPerClientEntry[name] = new Map()
} }
...@@ -422,47 +411,47 @@ export class FlightClientEntryPlugin { ...@@ -422,47 +411,47 @@ export class FlightClientEntryPlugin {
]) ])
} }
} }
}
for (const [name, actionEntryImports] of Object.entries( for (const [name, actionEntryImports] of Object.entries(
actionMapsPerClientEntry actionMapsPerClientEntry
)) { )) {
// If an action method is already created in the server layer, we don't // If an action method is already created in the server layer, we don't
// need to create it again in the action layer. // need to create it again in the action layer.
// This is to avoid duplicate action instances and make sure the module // This is to avoid duplicate action instances and make sure the module
// state is shared. // state is shared.
let remainingClientImportedActions = false let remainingClientImportedActions = false
const remainingActionEntryImports = new Map<string, string[]>() const remainingActionEntryImports = new Map<string, string[]>()
for (const [dep, actionNames] of actionEntryImports) { for (const [dep, actionNames] of actionEntryImports) {
const remainingActionNames = [] const remainingActionNames = []
for (const actionName of actionNames) { for (const actionName of actionNames) {
const id = name + '@' + dep + '@' + actionName const id = name + '@' + dep + '@' + actionName
if (!createdActions.has(id)) { if (!createdActions.has(id)) {
remainingActionNames.push(actionName) remainingActionNames.push(actionName)
}
}
if (remainingActionNames.length > 0) {
remainingActionEntryImports.set(dep, remainingActionNames)
remainingClientImportedActions = true
} }
} }
if (remainingActionNames.length > 0) {
remainingActionEntryImports.set(dep, remainingActionNames)
remainingClientImportedActions = true
}
}
if (remainingClientImportedActions) { if (remainingClientImportedActions) {
addedClientActionEntryList.push( addedClientActionEntryList.push(
this.injectActionEntry({ this.injectActionEntry({
compiler, compiler,
compilation, compilation,
actions: remainingActionEntryImports, actions: remainingActionEntryImports,
entryName: name, entryName: name,
bundlePath: name, bundlePath: name,
fromClient: true, fromClient: true,
}) })
) )
}
} }
}
return Promise.all(addedClientActionEntryList) return Promise.all(addedClientActionEntryList)
}) })
}
// Invalidate in development to trigger recompilation // Invalidate in development to trigger recompilation
const invalidator = getInvalidator(compiler.outputPath) const invalidator = getInvalidator(compiler.outputPath)
......
...@@ -34,7 +34,7 @@ createNextDescribe( ...@@ -34,7 +34,7 @@ createNextDescribe(
it('should error if serverActions is not enabled', async () => { it('should error if serverActions is not enabled', async () => {
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
'Server Actions require `experimental.serverActions` option' 'To use Server Actions, please enable the feature flag in your Next.js config.'
) )
}) })
} }
......
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