Unverified Commit 4c3f59f8 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Implement server entry creation in client layer (#47127

In short, this PR adds a 3rd layer to the server compiler. This extra
layer is for marking the modules when re-entering the server layer from
a client component. It is almost identical to the existing server layer
and it should have all the same bundling and runtime behaviors, but it's
still special because it's not allowed to enter the client layer again
from there.

Because of that, we create the extra entry for that new layer when the
client layer compilation finishes in the `finishModules` phase. The new
entry is handled normally as it's in the server layer. But the original
module in the client layer will be compiled specially as special no-op
exports, and will then be connected via the `callServer` wrapper.

fix NEXT-809 ([link](https://linear.app/vercel/issue/NEXT-809)).
parent 02125cf3
...@@ -102,6 +102,18 @@ impl<C: Comments> ServerActions<C> { ...@@ -102,6 +102,18 @@ impl<C: Comments> ServerActions<C> {
remove_directive, remove_directive,
&mut is_action_fn, &mut is_action_fn,
); );
if is_action_fn && !self.config.is_server {
HANDLER.with(|handler| {
handler
.struct_span_err(
body.span,
"\"use server\" functions are not allowed in client components. \
You can import them from a \"use server\" file instead.",
)
.emit()
});
}
} }
} }
...@@ -692,9 +704,11 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -692,9 +704,11 @@ impl<C: Comments> VisitMut for ServerActions<C> {
stmt.visit_mut_with(self); stmt.visit_mut_with(self);
new.push(stmt); if self.config.is_server || !self.in_action_file {
new.extend(self.annotations.drain(..).map(ModuleItem::Stmt)); new.push(stmt);
new.append(&mut self.extra_items); new.extend(self.annotations.drain(..).map(ModuleItem::Stmt));
new.append(&mut self.extra_items);
}
} }
// If it's a "use server" file, all exports need to be annotated as actions. // If it's a "use server" file, all exports need to be annotated as actions.
...@@ -703,11 +717,70 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -703,11 +717,70 @@ impl<C: Comments> VisitMut for ServerActions<C> {
let ident = Ident::new(id.0.clone(), DUMMY_SP.with_ctxt(id.1)); let ident = Ident::new(id.0.clone(), DUMMY_SP.with_ctxt(id.1));
annotate_ident_as_action( annotate_ident_as_action(
&mut self.annotations, &mut self.annotations,
ident, ident.clone(),
Vec::new(), Vec::new(),
self.file_name.to_string(), self.file_name.to_string(),
export_name.to_string(), export_name.to_string(),
); );
if !self.config.is_server {
let params_ident = private_ident!("args");
let noop_fn = Box::new(Function {
params: vec![Param {
span: DUMMY_SP,
decorators: Default::default(),
pat: Pat::Rest(RestPat {
span: DUMMY_SP,
dot3_token: DUMMY_SP,
arg: Box::new(Pat::Ident(params_ident.clone().into())),
type_ann: None,
}),
}],
decorators: Vec::new(),
span: DUMMY_SP,
body: Some(BlockStmt {
span: DUMMY_SP,
stmts: vec![Stmt::Return(ReturnStmt {
span: DUMMY_SP,
arg: Some(Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: Callee::Expr(Box::new(Expr::Ident(private_ident!(
"__build_action__"
)))),
args: vec![ident.clone().as_arg(), params_ident.as_arg()],
type_args: None,
}))),
})],
}),
is_generator: false,
is_async: true,
type_params: None,
return_type: None,
});
if export_name == "default" {
let export_expr = ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(
ExportDefaultExpr {
span: DUMMY_SP,
expr: Box::new(Expr::Fn(FnExpr {
ident: Some(ident),
function: noop_fn,
})),
},
));
new.push(export_expr);
} else {
let export_expr =
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span: DUMMY_SP,
decl: Decl::Fn(FnDecl {
ident,
declare: false,
function: noop_fn,
}),
}));
new.push(export_expr);
}
}
} }
new.extend(self.annotations.drain(..).map(ModuleItem::Stmt)); new.extend(self.annotations.drain(..).map(ModuleItem::Stmt));
new.append(&mut self.extra_items); new.append(&mut self.extra_items);
......
...@@ -301,8 +301,8 @@ fn next_font_loaders_fixture(input: PathBuf) { ...@@ -301,8 +301,8 @@ fn next_font_loaders_fixture(input: PathBuf) {
); );
} }
#[fixture("tests/fixture/server-actions/**/input.js")] #[fixture("tests/fixture/server-actions/server/**/input.js")]
fn server_actions_fixture(input: PathBuf) { fn server_actions_server_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output = input.parent().unwrap().join("output.js");
test_fixture( test_fixture(
syntax(), syntax(),
...@@ -321,3 +321,24 @@ fn server_actions_fixture(input: PathBuf) { ...@@ -321,3 +321,24 @@ fn server_actions_fixture(input: PathBuf) {
Default::default(), Default::default(),
); );
} }
#[fixture("tests/fixture/server-actions/client/**/input.js")]
fn server_actions_client_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| {
chain!(
resolver(Mark::new(), Mark::new(), false),
server_actions(
&FileName::Real("/app/item.js".into()),
server_actions::Config { is_server: false },
_tr.comments.as_ref().clone(),
)
)
},
&input,
&output,
Default::default(),
);
}
// app/send.ts
"use server";
export async function myAction(a, b, c) {
console.log('a')
}
export default async function () {}
// app/send.ts
/* __next_internal_action_entry_do_not_use__ myAction,default */ export async function myAction(...args) {
return __build_action__(myAction, args);
}
export default async function $$ACTION_0(...args) {
return __build_action__($$ACTION_0, args);
};
myAction.$$typeof = Symbol.for("react.server.reference");
myAction.$$id = "e10665baac148856374b2789aceb970f66fec33e";
myAction.$$bound = [];
$$ACTION_0.$$typeof = Symbol.for("react.server.reference");
$$ACTION_0.$$id = "c18c215a6b7cdc64bf709f3a714ffdef1bf9651d";
$$ACTION_0.$$bound = [];
// app/send.ts
"use server";
import 'db'
console.log('side effect')
const foo = async () => {
console.log('function body')
}
export { foo }
\ No newline at end of file
// app/send.ts
/* __next_internal_action_entry_do_not_use__ foo */ export async function foo(...args) {
return __build_action__(foo, args);
}
foo.$$typeof = Symbol.for("react.server.reference");
foo.$$id = "ab21efdafbe611287bc25c0462b1e0510d13e48b";
foo.$$bound = [];
...@@ -47,10 +47,21 @@ const ACTION_MODULE_LABEL = ...@@ -47,10 +47,21 @@ const ACTION_MODULE_LABEL =
/\/\* __next_internal_action_entry_do_not_use__ ([^ ]+) \*\// /\/\* __next_internal_action_entry_do_not_use__ ([^ ]+) \*\//
export type RSCModuleType = 'server' | 'client' export type RSCModuleType = 'server' | 'client'
export function getRSCModuleInformation(source: string): RSCMeta { export function getRSCModuleInformation(
const clientRefs = source.match(CLIENT_MODULE_LABEL)?.[1]?.split(',') source: string,
isServerLayer = true
): RSCMeta {
const actions = source.match(ACTION_MODULE_LABEL)?.[1]?.split(',') const actions = source.match(ACTION_MODULE_LABEL)?.[1]?.split(',')
if (!isServerLayer) {
return {
type: RSC_MODULE_TYPES.client,
actions,
}
}
const clientRefs = source.match(CLIENT_MODULE_LABEL)?.[1]?.split(',')
const type = clientRefs ? RSC_MODULE_TYPES.client : RSC_MODULE_TYPES.server const type = clientRefs ? RSC_MODULE_TYPES.client : RSC_MODULE_TYPES.server
return { type, actions, clientRefs } return { type, actions, clientRefs }
} }
......
...@@ -786,13 +786,22 @@ export default async function getBaseWebpackConfig( ...@@ -786,13 +786,22 @@ export default async function getBaseWebpackConfig(
const swcLoaderForServerLayer = hasServerComponents const swcLoaderForServerLayer = hasServerComponents
? useSWCLoader ? useSWCLoader
? getSwcLoader({ isServerLayer: true }) ? [getSwcLoader({ isServerLayer: true })]
: // When using Babel, we will have to add the SWC loader : // When using Babel, we will have to add the SWC loader
// as an additional pass to handle RSC correctly. // as an additional pass to handle RSC correctly.
// This will cause some performance overhead but // This will cause some performance overhead but
// acceptable as Babel will not be recommended. // acceptable as Babel will not be recommended.
[getSwcLoader({ isServerLayer: true }), getBabelLoader()] [getSwcLoader({ isServerLayer: true }), getBabelLoader()]
: [] : []
const swcLoaderForClientLayer = hasServerComponents
? useSWCLoader
? [getSwcLoader({ isServerLayer: false })]
: // When using Babel, we will have to add the SWC loader
// as an additional pass to handle RSC correctly.
// This will cause some performance overhead but
// acceptable as Babel will not be recommended.
[getSwcLoader({ isServerLayer: false }), getBabelLoader()]
: []
// Loader for API routes needs to be differently configured as it shouldn't // Loader for API routes needs to be differently configured as it shouldn't
// have RSC transpiler enabled, so syntax checks such as invalid imports won't // have RSC transpiler enabled, so syntax checks such as invalid imports won't
...@@ -1699,6 +1708,7 @@ export default async function getBaseWebpackConfig( ...@@ -1699,6 +1708,7 @@ export default async function getBaseWebpackConfig(
'next-flight-loader', 'next-flight-loader',
'next-flight-client-entry-loader', 'next-flight-client-entry-loader',
'next-flight-action-entry-loader', 'next-flight-action-entry-loader',
'next-flight-client-action-loader',
'noop-loader', 'noop-loader',
'next-middleware-loader', 'next-middleware-loader',
'next-edge-function-loader', 'next-edge-function-loader',
...@@ -1727,7 +1737,9 @@ export default async function getBaseWebpackConfig( ...@@ -1727,7 +1737,9 @@ export default async function getBaseWebpackConfig(
...(hasAppDir && !isClient ...(hasAppDir && !isClient
? [ ? [
{ {
issuerLayer: WEBPACK_LAYERS.server, issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
},
test: { test: {
// Resolve it if it is a source code file, and it has NOT been // Resolve it if it is a source code file, and it has NOT been
// opted out of bundling. // opted out of bundling.
...@@ -1796,6 +1808,7 @@ export default async function getBaseWebpackConfig( ...@@ -1796,6 +1808,7 @@ export default async function getBaseWebpackConfig(
WEBPACK_LAYERS.server, WEBPACK_LAYERS.server,
WEBPACK_LAYERS.client, WEBPACK_LAYERS.client,
WEBPACK_LAYERS.appClient, WEBPACK_LAYERS.appClient,
WEBPACK_LAYERS.action,
], ],
}, },
resolve: { resolve: {
...@@ -1817,7 +1830,9 @@ export default async function getBaseWebpackConfig( ...@@ -1817,7 +1830,9 @@ export default async function getBaseWebpackConfig(
oneOf: [ oneOf: [
{ {
exclude: [staticGenerationAsyncStorageRegex], exclude: [staticGenerationAsyncStorageRegex],
issuerLayer: WEBPACK_LAYERS.server, issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
},
test: { test: {
// Resolve it if it is a source code file, and it has NOT been // Resolve it if it is a source code file, and it has NOT been
// opted out of bundling. // opted out of bundling.
...@@ -1888,7 +1903,9 @@ export default async function getBaseWebpackConfig( ...@@ -1888,7 +1903,9 @@ export default async function getBaseWebpackConfig(
? [ ? [
{ {
test: codeCondition.test, test: codeCondition.test,
issuerLayer: WEBPACK_LAYERS.server, issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
},
exclude: [staticGenerationAsyncStorageRegex], exclude: [staticGenerationAsyncStorageRegex],
use: swcLoaderForServerLayer, use: swcLoaderForServerLayer,
}, },
...@@ -1897,6 +1914,27 @@ export default async function getBaseWebpackConfig( ...@@ -1897,6 +1914,27 @@ export default async function getBaseWebpackConfig(
resourceQuery: /__edge_ssr_entry__/, resourceQuery: /__edge_ssr_entry__/,
use: swcLoaderForServerLayer, use: swcLoaderForServerLayer,
}, },
{
test: codeCondition.test,
issuerLayer: {
or: [WEBPACK_LAYERS.client, WEBPACK_LAYERS.appClient],
},
exclude: [staticGenerationAsyncStorageRegex],
use: [
...(dev && isClient
? [
require.resolve(
'next/dist/compiled/@next/react-refresh-utils/dist/loader'
),
defaultLoaders.babel,
]
: []),
{
loader: 'next-flight-client-action-loader',
},
...swcLoaderForClientLayer,
],
},
] ]
: []), : []),
{ {
...@@ -2037,7 +2075,9 @@ export default async function getBaseWebpackConfig( ...@@ -2037,7 +2075,9 @@ export default async function getBaseWebpackConfig(
{ {
test: /node_modules[/\\]client-only[/\\]error.js/, test: /node_modules[/\\]client-only[/\\]error.js/,
loader: 'next-invalid-import-error-loader', loader: 'next-invalid-import-error-loader',
issuerLayer: WEBPACK_LAYERS.server, issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.action],
},
options: { options: {
message: message:
"'client-only' cannot be imported from a Server Component module. It should only be used from a Client Component.", "'client-only' cannot be imported from a Server Component module. It should only be used from a Client Component.",
......
import { getRSCModuleInformation } from './../../analysis/get-page-static-info'
import { getModuleBuildInfo } from './get-module-build-info'
export default async function transformSource(
this: any,
source: string,
sourceMap: any
) {
// Avoid buffer to be consumed
if (typeof source !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const callback = this.async()
// Assign the RSC meta information to buildInfo.
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.rsc = getRSCModuleInformation(source, false)
// This is a server action entry module in the client layer. We need to attach
// noop exports of `callServer` wrappers for each action.
if (buildInfo.rsc?.actions) {
source = `
import { callServer } from 'next/dist/client/app-call-server'
function __build_action__(action, args) {
return callServer(action.$$id, args)
}
${source}
`
}
return callback(null, source, sourceMap)
}
...@@ -29,9 +29,8 @@ import { ...@@ -29,9 +29,8 @@ import {
isClientComponentModule, isClientComponentModule,
regexCSS, regexCSS,
} from '../loaders/utils' } from '../loaders/utils'
import { traverseModules } from '../utils' import { traverseModules, forEachEntryModule } from '../utils'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { getProxiedPluginState } from '../../build-context' import { getProxiedPluginState } from '../../build-context'
interface Options { interface Options {
...@@ -98,9 +97,9 @@ export class FlightClientEntryPlugin { ...@@ -98,9 +97,9 @@ export class FlightClientEntryPlugin {
} }
) )
compiler.hooks.finishMake.tapPromise(PLUGIN_NAME, (compilation) => { compiler.hooks.finishMake.tapPromise(PLUGIN_NAME, (compilation) =>
return this.createClientEntries(compiler, compilation) this.createClientEntries(compiler, compilation)
}) )
compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => { compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {
const recordModule = (modId: string, mod: any) => { const recordModule = (modId: string, mod: any) => {
...@@ -166,60 +165,9 @@ export class FlightClientEntryPlugin { ...@@ -166,60 +165,9 @@ export class FlightClientEntryPlugin {
const addActionEntryList: Array<ReturnType<typeof this.injectActionEntry>> = const addActionEntryList: Array<ReturnType<typeof this.injectActionEntry>> =
[] []
// Loop over all the entry modules.
function forEachEntryModule(
callback: ({
name,
entryModule,
}: {
name: string
entryModule: any
}) => void
) {
for (const [name, entry] of compilation.entries.entries()) {
// Skip for entries under pages/
if (
name.startsWith('pages/') ||
// Skip for route.js entries
(name.startsWith('app/') && isAppRouteRoute(name))
) {
continue
}
// Check if the page entry is a server component or not.
const entryDependency: webpack.NormalModule | undefined =
entry.dependencies?.[0]
// Ensure only next-app-loader entries are handled.
if (!entryDependency || !entryDependency.request) continue
const request = entryDependency.request
if (
!request.startsWith('next-edge-ssr-loader?') &&
!request.startsWith('next-app-loader?')
)
continue
let entryModule: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(entryDependency)
if (request.startsWith('next-edge-ssr-loader?')) {
entryModule.dependencies.forEach((dependency) => {
const modRequest: string | undefined = (dependency as any).request
if (modRequest?.includes('next-app-loader')) {
entryModule =
compilation.moduleGraph.getResolvedModule(dependency)
}
})
}
callback({ name, entryModule })
}
}
// For each SC server compilation entry, we need to create its corresponding // For each SC server compilation entry, we need to create its corresponding
// client component entry. // client component entry.
forEachEntryModule(({ name, entryModule }) => { forEachEntryModule(compilation, ({ name, entryModule }) => {
const internalClientComponentEntryImports = new Set< const internalClientComponentEntryImports = new Set<
ClientComponentImports[0] ClientComponentImports[0]
>() >()
...@@ -305,6 +253,85 @@ export class FlightClientEntryPlugin { ...@@ -305,6 +253,85 @@ export class FlightClientEntryPlugin {
} }
}) })
// To collect all CSS imports and action imports for a specific entry
// including the ones that are in the client graph, we need to store a
// map for client boundary dependencies.
function collectClientEntryDependencyMap(name: string) {
const clientEntryDependencyMap: Record<string, any> = {}
const entry = compilation.entries.get(name)
entry.includeDependencies.forEach((dep: any) => {
if (
dep.request &&
dep.request.startsWith('next-flight-client-entry-loader?')
) {
const mod: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(dep)
compilation.moduleGraph
.getOutgoingConnections(mod)
.forEach((connection: any) => {
if (connection.dependency) {
clientEntryDependencyMap[connection.dependency.request] =
connection.dependency
}
})
}
})
return clientEntryDependencyMap
}
// We need to create extra action entries that are created in the
// client layer.
compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, () => {
const addedClientActionEntryList: Promise<any>[] = []
forEachEntryModule(compilation, ({ name, entryModule }) => {
const actionEntryImports = new Map<string, string[]>()
const clientEntryDependencyMap = collectClientEntryDependencyMap(name)
const tracked = new Set<string>()
for (const connection of compilation.moduleGraph.getOutgoingConnections(
entryModule
)) {
const entryDependency = connection.dependency
const entryRequest = connection.dependency.request
// It is possible that the same entry is added multiple times in the
// connection graph. We can just skip these to speed up the process.
if (tracked.has(entryRequest)) continue
tracked.add(entryRequest)
const { clientActionImports } =
this.collectComponentInfoFromDependencies({
entryRequest,
compilation,
dependency: entryDependency,
clientEntryDependencyMap,
})
clientActionImports.forEach(([dep, names]) =>
actionEntryImports.set(dep, names)
)
}
if (actionEntryImports.size > 0) {
addedClientActionEntryList.push(
this.injectActionEntry({
compiler,
compilation,
actions: actionEntryImports,
entryName: name,
bundlePath: name,
fromClient: true,
})
)
}
})
return Promise.all(addedClientActionEntryList)
})
// After optimizing all the modules, we collect the CSS that are still used // After optimizing all the modules, we collect the CSS that are still used
// by the certain chunk. // by the certain chunk.
compilation.hooks.afterOptimizeModules.tap(PLUGIN_NAME, () => { compilation.hooks.afterOptimizeModules.tap(PLUGIN_NAME, () => {
...@@ -360,31 +387,8 @@ export class FlightClientEntryPlugin { ...@@ -360,31 +387,8 @@ export class FlightClientEntryPlugin {
}) })
}) })
forEachEntryModule(({ name, entryModule }) => { forEachEntryModule(compilation, ({ name, entryModule }) => {
// To collect all CSS imports for a specific entry including the ones const clientEntryDependencyMap = collectClientEntryDependencyMap(name)
// that are in the client graph, we need to store a map for client boundary
// dependencies.
const clientEntryDependencyMap: Record<string, any> = {}
const entry = compilation.entries.get(name)
entry.includeDependencies.forEach((dep: any) => {
if (
dep.request &&
dep.request.startsWith('next-flight-client-entry-loader?')
) {
const mod: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(dep)
compilation.moduleGraph
.getOutgoingConnections(mod)
.forEach((connection: any) => {
if (connection.dependency) {
clientEntryDependencyMap[connection.dependency.request] =
connection.dependency
}
})
}
})
const tracked = new Set<string>() const tracked = new Set<string>()
for (const connection of compilation.moduleGraph.getOutgoingConnections( for (const connection of compilation.moduleGraph.getOutgoingConnections(
entryModule entryModule
...@@ -476,6 +480,7 @@ export class FlightClientEntryPlugin { ...@@ -476,6 +480,7 @@ export class FlightClientEntryPlugin {
clientImports: ClientComponentImports clientImports: ClientComponentImports
cssImports: CssImports cssImports: CssImports
actionImports: [string, string[]][] actionImports: [string, string[]][]
clientActionImports: [string, string[]][]
} { } {
/** /**
* Keep track of checked modules to avoid infinite loops with recursive imports. * Keep track of checked modules to avoid infinite loops with recursive imports.
...@@ -483,6 +488,7 @@ export class FlightClientEntryPlugin { ...@@ -483,6 +488,7 @@ export class FlightClientEntryPlugin {
const visitedBySegment: { [segment: string]: Set<string> } = {} const visitedBySegment: { [segment: string]: Set<string> } = {}
const clientComponentImports: ClientComponentImports = [] const clientComponentImports: ClientComponentImports = []
const actionImports: [string, string[]][] = [] const actionImports: [string, string[]][] = []
const clientActionImports: [string, string[]][] = []
const CSSImports = new Set<string>() const CSSImports = new Set<string>()
const filterClientComponents = ( const filterClientComponents = (
...@@ -517,7 +523,11 @@ export class FlightClientEntryPlugin { ...@@ -517,7 +523,11 @@ export class FlightClientEntryPlugin {
const actions = getActions(mod) const actions = getActions(mod)
if (actions) { if (actions) {
actionImports.push([modRequest, actions]) if (isClientComponent) {
clientActionImports.push([modRequest, actions])
} else {
actionImports.push([modRequest, actions])
}
} }
if (isCSS) { if (isCSS) {
...@@ -564,9 +574,6 @@ export class FlightClientEntryPlugin { ...@@ -564,9 +574,6 @@ export class FlightClientEntryPlugin {
}) })
} }
// Traverse the module graph to find all client components.
filterClientComponents(dependency, false)
// Don't traverse the module graph for the action loader. // Don't traverse the module graph for the action loader.
if (!/next-flight-action-entry-loader/.test(entryRequest)) { if (!/next-flight-action-entry-loader/.test(entryRequest)) {
// Traverse the module graph to find all client components. // Traverse the module graph to find all client components.
...@@ -581,6 +588,7 @@ export class FlightClientEntryPlugin { ...@@ -581,6 +588,7 @@ export class FlightClientEntryPlugin {
} }
: {}, : {},
actionImports, actionImports,
clientActionImports,
} }
} }
...@@ -695,12 +703,14 @@ export class FlightClientEntryPlugin { ...@@ -695,12 +703,14 @@ export class FlightClientEntryPlugin {
actions, actions,
entryName, entryName,
bundlePath, bundlePath,
fromClient,
}: { }: {
compiler: webpack.Compiler compiler: webpack.Compiler
compilation: webpack.Compilation compilation: webpack.Compilation
actions: Map<string, string[]> actions: Map<string, string[]>
entryName: string entryName: string
bundlePath: string bundlePath: string
fromClient?: boolean
}) { }) {
const actionsArray = Array.from(actions.entries()) const actionsArray = Array.from(actions.entries())
const actionLoader = `next-flight-action-entry-loader?${stringify({ const actionLoader = `next-flight-action-entry-loader?${stringify({
...@@ -734,7 +744,7 @@ export class FlightClientEntryPlugin { ...@@ -734,7 +744,7 @@ export class FlightClientEntryPlugin {
actionEntryDep, actionEntryDep,
{ {
name: entryName, name: entryName,
layer: WEBPACK_LAYERS.server, layer: fromClient ? WEBPACK_LAYERS.action : WEBPACK_LAYERS.server,
} }
) )
} }
......
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { isAppRouteRoute } from '../../lib/is-app-route-route'
export function traverseModules( export function traverseModules(
compilation: webpack.Compilation, compilation: webpack.Compilation,
...@@ -27,3 +28,48 @@ export function traverseModules( ...@@ -27,3 +28,48 @@ export function traverseModules(
}) })
}) })
} }
// Loop over all the entry modules.
export function forEachEntryModule(
compilation: any,
callback: ({ name, entryModule }: { name: string; entryModule: any }) => void
) {
for (const [name, entry] of compilation.entries.entries()) {
// Skip for entries under pages/
if (
name.startsWith('pages/') ||
// Skip for route.js entries
(name.startsWith('app/') && isAppRouteRoute(name))
) {
continue
}
// Check if the page entry is a server component or not.
const entryDependency: webpack.NormalModule | undefined =
entry.dependencies?.[0]
// Ensure only next-app-loader entries are handled.
if (!entryDependency || !entryDependency.request) continue
const request = entryDependency.request
if (
!request.startsWith('next-edge-ssr-loader?') &&
!request.startsWith('next-app-loader?')
)
continue
let entryModule: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(entryDependency)
if (request.startsWith('next-edge-ssr-loader?')) {
entryModule.dependencies.forEach((dependency) => {
const modRequest: string | undefined = (dependency as any).request
if (modRequest?.includes('next-app-loader')) {
entryModule = compilation.moduleGraph.getResolvedModule(dependency)
}
})
}
callback({ name, entryModule })
}
}
export async function callServer(id: string, args: any[]) {
const actionId = id
// Fetching the current url with the action header.
// TODO: Refactor this to look up from a manifest.
const res = await fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Next-Action': actionId,
},
body: JSON.stringify({
bound: args,
}),
})
return (await res.json())[0]
}
...@@ -8,6 +8,7 @@ import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-we ...@@ -8,6 +8,7 @@ import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-we
import { HeadManagerContext } from '../shared/lib/head-manager-context' import { HeadManagerContext } from '../shared/lib/head-manager-context'
import { GlobalLayoutRouterContext } from '../shared/lib/app-router-context' import { GlobalLayoutRouterContext } from '../shared/lib/app-router-context'
import onRecoverableError from './on-recoverable-error' import onRecoverableError from './on-recoverable-error'
import { callServer } from './app-call-server'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -151,24 +152,7 @@ function useInitialServerResponse(cacheKey: string): Promise<JSX.Element> { ...@@ -151,24 +152,7 @@ function useInitialServerResponse(cacheKey: string): Promise<JSX.Element> {
}) })
const newResponse = createFromReadableStream(readable, { const newResponse = createFromReadableStream(readable, {
async callServer(id: string, args: any[]) { callServer,
const actionId = id
// Fetching the current url with the action header.
// TODO: Refactor this to look up from a manifest.
const res = await fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Next-Action': actionId,
},
body: JSON.stringify({
bound: args,
}),
})
return (await res.json())[0]
},
}) })
rscCache.set(cacheKey, newResponse) rscCache.set(cacheKey, newResponse)
......
...@@ -80,6 +80,7 @@ export const WEBPACK_LAYERS = { ...@@ -80,6 +80,7 @@ export const WEBPACK_LAYERS = {
shared: 'sc_shared', shared: 'sc_shared',
server: 'sc_server', server: 'sc_server',
client: 'sc_client', client: 'sc_client',
action: 'sc_action',
api: 'api', api: 'api',
middleware: 'middleware', middleware: 'middleware',
edgeAsset: 'edge-asset', edgeAsset: 'edge-asset',
......
...@@ -41,7 +41,7 @@ https://nextjs.org/docs/messages/module-not-found" ...@@ -41,7 +41,7 @@ https://nextjs.org/docs/messages/module-not-found"
`; `;
exports[`ReactRefreshLogBox app default Node.js builtins 1`] = ` exports[`ReactRefreshLogBox app default Node.js builtins 1`] = `
"./node_modules/my-package/index.js:2:0 "./node_modules/my-package/index.js:2:22
Module not found: Can't resolve 'dns' Module not found: Can't resolve 'dns'
https://nextjs.org/docs/messages/module-not-found https://nextjs.org/docs/messages/module-not-found
......
...@@ -64,5 +64,24 @@ createNextDescribe( ...@@ -64,5 +64,24 @@ createNextDescribe(
return browser.elementByCss('h1').text() return browser.elementByCss('h1').text()
}, 'my-not-found') }, 'my-not-found')
}) })
it('should support importing actions in client components', async () => {
const browser = await next.browser('/client')
const cnt = await browser.elementByCss('h1').text()
expect(cnt).toBe('0')
await browser.elementByCss('#inc').click()
await check(() => browser.elementByCss('h1').text(), '1')
await browser.elementByCss('#inc').click()
await check(() => browser.elementByCss('h1').text(), '2')
await browser.elementByCss('#double').click()
await check(() => browser.elementByCss('h1').text(), '4')
await browser.elementByCss('#dec').click()
await check(() => browser.elementByCss('h1').text(), '3')
})
} }
) )
'use server'
export async function inc(value) {
return value + 1
}
export async function dec(value) {
return value - 1
}
export default async function (value) {
return value * 2
}
'use client'
import { useState } from 'react'
import double, { inc, dec } from './actions'
export default function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<h1>{count}</h1>
<button
id="inc"
onClick={async () => {
const newCount = await inc(count)
setCount(newCount)
}}
>
+1
</button>
<button
id="dec"
onClick={async () => {
const newCount = await dec(count)
setCount(newCount)
}}
>
-1
</button>
<button
id="double"
onClick={async () => {
const newCount = await double(count)
setCount(newCount)
}}
>
*2
</button>
</div>
)
}
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