Unverified Commit 8e723ede authored by Shu Ding's avatar Shu Ding Committed by GitHub

Change Server Reference creation on client (#48824)

Mostly mirrors the changed made in
https://github.com/facebook/react/pull/26632 to our SWC transform. The
implementation difference is that the AST transformer only adds a
general purpose wrapper call `createServerReference(id)` from an aliased
import, so we can easily change the underlying function in the bundler.
This change only affects the client layer (when `self.config.is_server
=== false`).

Needs to be landed after another React upgrade:
https://github.com/vercel/next.js/pull/48697.

cc @sebmarkbage.
parent fafecb84
...@@ -855,59 +855,46 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -855,59 +855,46 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// 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.
if self.in_action_file { if self.in_action_file {
for (id, export_name) in self.exported_idents.iter() { // If it's compiled in the client layer, each export field needs to be
let ident = Ident::new(id.0.clone(), DUMMY_SP.with_ctxt(id.1)); // wrapped by a reference creation call.
annotate_ident_as_action( let create_ref_ident = private_ident!("createServerReference");
&mut self.annotations,
ident.clone(),
Vec::new(),
self.file_name.to_string(),
export_name.to_string(),
false,
None,
);
if !self.config.is_server { if !self.config.is_server {
let params_ident = private_ident!("args"); // import createServerReference from 'private-next-rsc-action-client-wrapper'
let noop_fn = Box::new(Function { // createServerReference("action_id")
params: vec![Param { new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
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, span: DUMMY_SP,
arg: Some(Box::new(Expr::Call(CallExpr { specifiers: vec![ImportSpecifier::Default(ImportDefaultSpecifier {
span: DUMMY_SP, span: DUMMY_SP,
callee: Callee::Expr(Box::new(Expr::Ident(private_ident!( local: create_ref_ident.clone(),
"__build_action__"
)))),
args: vec![ident.clone().as_arg(), params_ident.as_arg()],
type_args: None,
}))),
})], })],
src: Box::new(Str {
span: DUMMY_SP,
value: "private-next-rsc-action-client-wrapper".into(),
raw: None,
}), }),
is_generator: false, type_only: false,
is_async: true, asserts: None,
type_params: None, })));
return_type: None, }
});
for (id, export_name) in self.exported_idents.iter() {
let ident = Ident::new(id.0.clone(), DUMMY_SP.with_ctxt(id.1));
if !self.config.is_server {
let action_id =
generate_action_id(self.file_name.to_string(), export_name.to_string());
if export_name == "default" { if export_name == "default" {
let export_expr = ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr( let export_expr = ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(
ExportDefaultExpr { ExportDefaultExpr {
span: DUMMY_SP, span: DUMMY_SP,
expr: Box::new(Expr::Fn(FnExpr { expr: Box::new(Expr::Call(CallExpr {
ident: Some(ident), span: DUMMY_SP,
function: noop_fn, callee: Callee::Expr(Box::new(Expr::Ident(
create_ref_ident.clone(),
))),
args: vec![action_id.as_arg()],
type_args: None,
})), })),
}, },
)); ));
...@@ -916,16 +903,41 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -916,16 +903,41 @@ impl<C: Comments> VisitMut for ServerActions<C> {
let export_expr = let export_expr =
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span: DUMMY_SP, span: DUMMY_SP,
decl: Decl::Fn(FnDecl { decl: Decl::Var(Box::new(VarDecl {
ident, span: DUMMY_SP,
kind: VarDeclKind::Const,
declare: false, declare: false,
function: noop_fn, decls: vec![VarDeclarator {
}), span: DUMMY_SP,
name: Pat::Ident(ident.into()),
init: Some(Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: Callee::Expr(Box::new(Expr::Ident(
create_ref_ident.clone(),
))),
args: vec![action_id.as_arg()],
type_args: None,
}))),
definite: false,
}],
})),
})); }));
new.push(export_expr); new.push(export_expr);
} }
} else {
annotate_ident_as_action(
&mut self.annotations,
ident.clone(),
Vec::new(),
self.file_name.to_string(),
export_name.to_string(),
false,
None,
);
} }
} }
if self.config.is_server {
new.append(&mut self.extra_items); new.append(&mut self.extra_items);
// Ensure that the exports are valid by appending a check // Ensure that the exports are valid by appending a check
...@@ -977,6 +989,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -977,6 +989,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// Append annotations to the end of the file. // Append annotations to the end of the file.
new.extend(self.annotations.drain(..).map(ModuleItem::Stmt)); new.extend(self.annotations.drain(..).map(ModuleItem::Stmt));
} }
}
*stmts = new; *stmts = new;
...@@ -1149,6 +1162,18 @@ fn pat_to_assign_pat( ...@@ -1149,6 +1162,18 @@ fn pat_to_assign_pat(
} }
} }
fn generate_action_id(file_name: String, export_name: String) -> String {
// Attach a checksum to the action using sha1:
// $$id = sha1('file_name' + ':' + 'export_name');
let mut hasher = Sha1::new();
hasher.update(file_name.as_bytes());
hasher.update(b":");
hasher.update(export_name.as_bytes());
let result = hasher.finalize();
hex_encode(result)
}
fn annotate_ident_as_action( fn annotate_ident_as_action(
annotations: &mut Vec<Stmt>, annotations: &mut Vec<Stmt>,
ident: Ident, ident: Ident,
...@@ -1173,16 +1198,12 @@ fn annotate_ident_as_action( ...@@ -1173,16 +1198,12 @@ fn annotate_ident_as_action(
.into(), .into(),
)); ));
// Attach a checksum to the action using sha1:
// myAction.$$id = sha1('file_name' + ':' + 'export_name');
let mut hasher = Sha1::new();
hasher.update(file_name.as_bytes());
hasher.update(b":");
hasher.update(export_name.as_bytes());
let result = hasher.finalize();
// Convert result to hex string // Convert result to hex string
annotations.push(annotate(&ident, "$$id", hex_encode(result).into())); annotations.push(annotate(
&ident,
"$$id",
generate_action_id(file_name, export_name).into(),
));
// myAction.$$bound = []; // myAction.$$bound = [];
annotations.push(annotate( annotations.push(annotate(
......
// app/send.ts // app/send.ts
/* __next_internal_action_entry_do_not_use__ myAction,default */ export async function myAction(...args) { /* __next_internal_action_entry_do_not_use__ myAction,default */ import createServerReference from "private-next-rsc-action-client-wrapper";
return __build_action__(myAction, args); export const myAction = createServerReference("e10665baac148856374b2789aceb970f66fec33e");
} export default createServerReference("c18c215a6b7cdc64bf709f3a714ffdef1bf9651d");
export default async function $$ACTION_0(...args) {
return __build_action__($$ACTION_0, args);
};
import ensureServerEntryExports from "private-next-rsc-action-proxy";
ensureServerEntryExports([
myAction,
$$ACTION_0
]);
myAction.$$typeof = Symbol.for("react.server.reference");
myAction.$$id = "e10665baac148856374b2789aceb970f66fec33e";
myAction.$$bound = [];
myAction.$$with_bound = false;
$$ACTION_0.$$typeof = Symbol.for("react.server.reference");
$$ACTION_0.$$id = "c18c215a6b7cdc64bf709f3a714ffdef1bf9651d";
$$ACTION_0.$$bound = [];
$$ACTION_0.$$with_bound = false;
// app/send.ts // app/send.ts
/* __next_internal_action_entry_do_not_use__ foo */ export async function foo(...args) { /* __next_internal_action_entry_do_not_use__ foo */ import createServerReference from "private-next-rsc-action-client-wrapper";
return __build_action__(foo, args); export const foo = createServerReference("ab21efdafbe611287bc25c0462b1e0510d13e48b");
}
import ensureServerEntryExports from "private-next-rsc-action-proxy";
ensureServerEntryExports([
foo
]);
foo.$$typeof = Symbol.for("react.server.reference");
foo.$$id = "ab21efdafbe611287bc25c0462b1e0510d13e48b";
foo.$$bound = [];
foo.$$with_bound = false;
declare module 'next/dist/compiled/react-server-dom-webpack/client' declare module 'next/dist/compiled/react-server-dom-webpack/client'
declare module 'next/dist/client/app-call-server'
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
APP_DIR_ALIAS, APP_DIR_ALIAS,
WEBPACK_LAYERS, WEBPACK_LAYERS,
RSC_ACTION_PROXY_ALIAS, RSC_ACTION_PROXY_ALIAS,
RSC_ACTION_CLIENT_WRAPPER_ALIAS,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js' import { CustomRoutes } from '../lib/load-custom-routes.js'
...@@ -1058,6 +1059,9 @@ export default async function getBaseWebpackConfig( ...@@ -1058,6 +1059,9 @@ export default async function getBaseWebpackConfig(
[RSC_ACTION_PROXY_ALIAS]: [RSC_ACTION_PROXY_ALIAS]:
'next/dist/build/webpack/loaders/next-flight-loader/action-proxy', 'next/dist/build/webpack/loaders/next-flight-loader/action-proxy',
[RSC_ACTION_CLIENT_WRAPPER_ALIAS]:
'next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper',
...(isClient || isEdgeServer ...(isClient || isEdgeServer
? { ? {
[clientResolveRewrites]: hasRewrites [clientResolveRewrites]: hasRewrites
...@@ -1263,7 +1267,7 @@ export default async function getBaseWebpackConfig( ...@@ -1263,7 +1267,7 @@ export default async function getBaseWebpackConfig(
} }
const notExternalModules = const notExternalModules =
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|legacy\/image|constants|dynamic|script|navigation|headers)$)|string-hash|private-next-rsc-action-proxy$)/ /^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|legacy\/image|constants|dynamic|script|navigation|headers)$)|string-hash|private-next-rsc-action-proxy|private-next-rsc-action-client-wrapper$)/
if (notExternalModules.test(request)) { if (notExternalModules.test(request)) {
return return
} }
......
// This file must be bundled in the app's client layer.
import { createServerReference } from 'next/dist/compiled/react-server-dom-webpack/client'
import { callServer } from 'next/dist/client/app-call-server'
// A noop wrapper to let the Flight client create the server reference.
// See also: https://github.com/facebook/react/pull/26632
export default function (id: string) {
return createServerReference(id, callServer)
}
...@@ -25,6 +25,8 @@ export const ROOT_DIR_ALIAS = 'private-next-root-dir' ...@@ -25,6 +25,8 @@ export const ROOT_DIR_ALIAS = 'private-next-root-dir'
export const APP_DIR_ALIAS = 'private-next-app-dir' export const APP_DIR_ALIAS = 'private-next-app-dir'
export const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy' export const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy'
export const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-action-proxy' export const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-action-proxy'
export const RSC_ACTION_CLIENT_WRAPPER_ALIAS =
'private-next-rsc-action-client-wrapper'
export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict` export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`
......
...@@ -15,6 +15,7 @@ declare module 'next/dist/compiled/react-server-dom-webpack/client.edge' ...@@ -15,6 +15,7 @@ declare module 'next/dist/compiled/react-server-dom-webpack/client.edge'
declare module 'next/dist/compiled/react-server-dom-webpack/client.browser' declare module 'next/dist/compiled/react-server-dom-webpack/client.browser'
declare module 'next/dist/compiled/react-server-dom-webpack/server.browser' declare module 'next/dist/compiled/react-server-dom-webpack/server.browser'
declare module 'next/dist/compiled/react-server-dom-webpack/server.edge' declare module 'next/dist/compiled/react-server-dom-webpack/server.edge'
declare module 'next/dist/client/app-call-server'
declare module 'next/dist/compiled/react-dom/server' declare module 'next/dist/compiled/react-dom/server'
declare module 'next/dist/compiled/react-dom/server.edge' declare module 'next/dist/compiled/react-dom/server.edge'
declare module 'next/dist/compiled/react-dom/server.browser' declare module 'next/dist/compiled/react-dom/server.browser'
......
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