Unverified Commit fd59a007 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix Server Actions compiler bug (#60794)

This PR fixes the issue where an inline Server Action gets exported. As
this isn't the designed use case for inline Server Actions (they're
supposed to be defined and used inside another closure, such as
components), we are not handling the export cases currently:

```ts
export async function action() {
  "use server"
  ...
}

<form action={action}/>
```

...which gets compiled into:

```ts
export async function action() {} // No-op function

<form action={...actionReference...}/>
```

Note that everything works inside this module until you `import` that
action and use it in another module.

To tackle that, this PR changes how that works as described in
`server/27/output.js`.

Closes NEXT-2140
parent 4b50313f
......@@ -56,6 +56,10 @@ pub fn server_actions<C: Comments>(
exported_idents: Default::default(),
inlined_action_closure_idents: Default::default(),
// This flag allows us to rewrite `function foo() {}` to `const foo = createProxy(...)`.
rewrite_fn_decl_to_proxy_decl: None,
rewrite_default_fn_expr_to_proxy_expr: None,
annotations: Default::default(),
extra_items: Default::default(),
export_actions: Default::default(),
......@@ -92,6 +96,10 @@ struct ServerActions<C: Comments> {
action_closure_idents: Vec<Name>,
inlined_action_closure_idents: Vec<(Id, Id)>,
// This flag allows us to rewrite `function foo() {}` to `const foo = createProxy(...)`.
rewrite_fn_decl_to_proxy_decl: Option<VarDecl>,
rewrite_default_fn_expr_to_proxy_expr: Option<Box<Expr>>,
// (ident, export name)
exported_idents: Vec<(Id, String)>,
replaced_action_proxies: Vec<(Ident, Box<Expr>)>,
......@@ -144,7 +152,7 @@ impl<C: Comments> ServerActions<C> {
ident: &Ident,
function: Option<&mut Box<Function>>,
arrow: Option<&mut ArrowExpr>,
) -> Option<Box<Expr>> {
) -> (Option<Box<Expr>>, Option<Box<Expr>>) {
let action_name: JsWord = gen_ident(&mut self.ident_cnt);
let action_ident = private_ident!(action_name.clone());
......@@ -153,11 +161,7 @@ impl<C: Comments> ServerActions<C> {
.push((ident.to_id(), action_ident.to_id()));
}
let export_name: JsWord = if self.in_default_export_decl {
"default".into()
} else {
action_name
};
let export_name: JsWord = action_name;
self.has_action = true;
self.export_actions.push(export_name.to_string());
......@@ -196,7 +200,7 @@ impl<C: Comments> ServerActions<C> {
});
self.replaced_action_proxies
.push((ident.clone(), Box::new(register_action_expr)));
.push((ident.clone(), Box::new(register_action_expr.clone())));
}
// export const $ACTION_myAction = async () => {}
......@@ -305,7 +309,10 @@ impl<C: Comments> ServerActions<C> {
.into(),
})));
return Some(Box::new(Expr::Ident(ident.clone())));
return (
Some(Box::new(Expr::Ident(ident.clone()))),
Some(Box::new(register_action_expr)),
);
} else if let Some(f) = function {
let register_action_expr = annotate_ident_as_action(
action_ident.clone(),
......@@ -323,7 +330,7 @@ impl<C: Comments> ServerActions<C> {
});
self.replaced_action_proxies
.push((ident.clone(), Box::new(register_action_expr)));
.push((ident.clone(), Box::new(register_action_expr.clone())));
// export async function $ACTION_myAction () {}
let mut new_params: Vec<Param> = vec![];
......@@ -404,10 +411,13 @@ impl<C: Comments> ServerActions<C> {
.into(),
})));
return Some(Box::new(Expr::Ident(ident.clone())));
return (
Some(Box::new(Expr::Ident(ident.clone()))),
Some(Box::new(register_action_expr)),
);
}
None
(None, None)
}
}
......@@ -424,6 +434,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
let old_default = self.in_default_export_decl;
self.in_export_decl = true;
self.in_default_export_decl = true;
self.rewrite_default_fn_expr_to_proxy_expr = None;
decl.decl.visit_mut_with(self);
self.in_export_decl = old;
self.in_default_export_decl = old_default;
......@@ -475,6 +486,38 @@ impl<C: Comments> VisitMut for ServerActions<C> {
.emit();
});
}
if !self.in_action_file && self.in_default_export_decl {
// This function expression is also the default export:
// `export default async function() {}`
// In this case, we need to collect the action and hoist, because this specific
// case (default export) isn't handled by `visit_mut_expr`.
let ident = match f.ident.as_mut() {
None => {
let action_name = gen_ident(&mut self.ident_cnt);
let ident = Ident::new(action_name, DUMMY_SP);
f.ident.insert(ident)
}
Some(i) => i,
};
let (_, register_action_expr) =
self.maybe_hoist_and_create_proxy(ident, Some(&mut f.function), None);
// Replace the original function expr with a action proxy expr.
self.rewrite_default_fn_expr_to_proxy_expr = register_action_expr;
}
}
fn visit_mut_decl(&mut self, d: &mut Decl) {
self.rewrite_fn_decl_to_proxy_decl = None;
d.visit_mut_children_with(self);
if let Some(decl) = &self.rewrite_fn_decl_to_proxy_decl {
*d = (*decl).clone().into();
}
self.rewrite_fn_decl_to_proxy_decl = None;
}
fn visit_mut_fn_decl(&mut self, f: &mut FnDecl) {
......@@ -513,21 +556,21 @@ impl<C: Comments> VisitMut for ServerActions<C> {
.emit();
});
} else if !self.in_action_file {
self.maybe_hoist_and_create_proxy(&f.ident, Some(&mut f.function), None);
let (_, register_action_expr) =
self.maybe_hoist_and_create_proxy(&f.ident, Some(&mut f.function), None);
// Make the original function declaration empty, as we have hoisted it already.
f.function = Box::new(Function {
params: vec![],
decorators: vec![],
// Replace the original function declaration with a action proxy declaration
// expr.
self.rewrite_fn_decl_to_proxy_decl = Some(VarDecl {
span: DUMMY_SP,
body: Some(BlockStmt {
kind: VarDeclKind::Var,
declare: false,
decls: vec![VarDeclarator {
span: DUMMY_SP,
stmts: vec![],
}),
is_generator: false,
is_async: false,
type_params: None,
return_type: None,
name: Pat::Ident(f.ident.clone().into()),
init: register_action_expr,
definite: false,
}],
});
}
}
......@@ -663,7 +706,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
let action_name = gen_ident(&mut self.ident_cnt);
let ident = private_ident!(action_name);
let maybe_new_expr = self.maybe_hoist_and_create_proxy(&ident, None, Some(a));
let (maybe_new_expr, _) = self.maybe_hoist_and_create_proxy(&ident, None, Some(a));
*n = if let Some(new_expr) = maybe_new_expr {
*new_expr
......@@ -686,7 +729,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
Some(i) => i,
};
let maybe_new_expr =
let (maybe_new_expr, _) =
self.maybe_hoist_and_create_proxy(ident, Some(&mut f.function), None);
if let Some(new_expr) = maybe_new_expr {
......@@ -865,8 +908,20 @@ impl<C: Comments> VisitMut for ServerActions<C> {
stmt.visit_mut_with(self);
let mut new_stmt = stmt;
if let Some(expr) = &self.rewrite_default_fn_expr_to_proxy_expr {
// If this happens, we need to replace the statement with a default export expr.
new_stmt =
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
span: DUMMY_SP,
expr: expr.clone(),
}));
self.rewrite_default_fn_expr_to_proxy_expr = None;
}
if self.config.is_react_server_layer || !self.in_action_file {
new.push(stmt);
new.push(new_stmt);
new.extend(self.annotations.drain(..).map(ModuleItem::Stmt));
new.append(&mut self.extra_items);
}
......
/* __next_internal_client_entry_do_not_use__ default auto */ /* __next_internal_action_entry_do_not_use__ {"6d53ce510b2e36499b8f56038817b9bad86cabb4":"$$ACTION_0"} */ export async function $$ACTION_0() {}
export default function App() {
function fn() {}
var fn = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0);
return <div>App</div>;
}
......@@ -2,7 +2,10 @@
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
import deleteFromDb from 'db';
export function Item({ id1, id2 }) {
function deleteItem() {}
var deleteItem = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
id1,
id2
]));
return <Button action={createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
id1,
id2
......
......@@ -17,7 +17,9 @@ export async function $$ACTION_1($$ACTION_CLOSURE_BOUND) {
await deleteFromDb($$ACTION_ARG_1);
}
const f = (x)=>{
function g() {}
var g = createActionProxy("9878bfa39811ca7650992850a8751f9591b6a557", $$ACTION_2).bind(null, encryptActionBoundArgs("9878bfa39811ca7650992850a8751f9591b6a557", [
x
]));
};
export async function $$ACTION_2($$ACTION_CLOSURE_BOUND, y, ...z) {
var [$$ACTION_ARG_0] = await decryptActionBoundArgs("9878bfa39811ca7650992850a8751f9591b6a557", $$ACTION_CLOSURE_BOUND);
......
/* __next_internal_action_entry_do_not_use__ {"6d53ce510b2e36499b8f56038817b9bad86cabb4":"$$ACTION_0","9878bfa39811ca7650992850a8751f9591b6a557":"$$ACTION_2"} */ import { createActionProxy } from "private-next-rsc-action-proxy";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
function myAction() {}
var myAction = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0);
export async function $$ACTION_0(a, b, c) {
console.log('a');
}
......
/* __next_internal_action_entry_do_not_use__ {"6d53ce510b2e36499b8f56038817b9bad86cabb4":"$$ACTION_0","9878bfa39811ca7650992850a8751f9591b6a557":"$$ACTION_2"} */ import { createActionProxy } from "private-next-rsc-action-proxy";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
export default function Page({ foo, x, y }) {
function action() {}
var action = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
x
]));
createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
x
])).bind(null, foo[0], foo[1], foo.x, foo[y]);
......
/* __next_internal_action_entry_do_not_use__ {"6d53ce510b2e36499b8f56038817b9bad86cabb4":"$$ACTION_0"} */ import { createActionProxy } from "private-next-rsc-action-proxy";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
export default function Page({ foo, x, y }) {
function action() {}
var action = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
foo
]));
}
export async function $$ACTION_0($$ACTION_CLOSURE_BOUND, a, b, c, { d }) {
var [$$ACTION_ARG_0] = await decryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_CLOSURE_BOUND);
......
......@@ -10,7 +10,10 @@ export function Item({ id1, id2 }) {
id2
]))}>Delete</Button>;
})();
function deleteItem() {}
var deleteItem = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
id1,
id2
]));
}
export async function $$ACTION_0($$ACTION_CLOSURE_BOUND) {
var [$$ACTION_ARG_0, $$ACTION_ARG_1] = await decryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_CLOSURE_BOUND);
......@@ -32,7 +35,10 @@ export function Item2({ id1, id2 }) {
id2
]))}>Delete</Button>);
return temp;
function deleteItem() {}
var deleteItem = createActionProxy("188d5d945750dc32e2c842b93c75a65763d4a922", $$ACTION_1).bind(null, encryptActionBoundArgs("188d5d945750dc32e2c842b93c75a65763d4a922", [
id1,
id2
]));
}
export async function $$ACTION_1($$ACTION_CLOSURE_BOUND) {
var [$$ACTION_ARG_0, $$ACTION_ARG_1] = await decryptActionBoundArgs("188d5d945750dc32e2c842b93c75a65763d4a922", $$ACTION_CLOSURE_BOUND);
......
// Rules here:
// 1. Each exported function should still be exported, but as a reference `createActionProxy(...)`.
// 2. Actual action functions should be renamed to `$$ACTION_...` and got exported.
async function foo() {
'use server'
console.log(1)
}
export { foo }
export async function bar() {
'use server'
console.log(2)
}
export default async function baz() {
'use server'
console.log(3)
}
export const qux = async () => {
'use server'
console.log(4)
}
export const quux = async function quuux() {
'use server'
console.log(5)
}
// Rules here:
// 1. Each exported function should still be exported, but as a reference `createActionProxy(...)`.
// 2. Actual action functions should be renamed to `$$ACTION_...` and got exported.
/* __next_internal_action_entry_do_not_use__ {"1383664d1dc2d9cfe33b88df3fa0eaffef8b99bc":"$$ACTION_5","188d5d945750dc32e2c842b93c75a65763d4a922":"$$ACTION_1","6d53ce510b2e36499b8f56038817b9bad86cabb4":"$$ACTION_0","9878bfa39811ca7650992850a8751f9591b6a557":"$$ACTION_2","9c0dd1f7c2b3f41d32e10f5c437de3d67ad32c6c":"$$ACTION_4"} */ import { createActionProxy } from "private-next-rsc-action-proxy";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
var foo = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0);
export async function $$ACTION_0() {
console.log(1);
}
export { foo };
export var bar = createActionProxy("188d5d945750dc32e2c842b93c75a65763d4a922", $$ACTION_1);
export async function $$ACTION_1() {
console.log(2);
}
export default createActionProxy("9878bfa39811ca7650992850a8751f9591b6a557", $$ACTION_2);
export async function $$ACTION_2() {
'use server';
console.log(3);
}
export const qux = createActionProxy("9c0dd1f7c2b3f41d32e10f5c437de3d67ad32c6c", $$ACTION_4);
export async function $$ACTION_4() {
console.log(4);
}
export const quux = createActionProxy("1383664d1dc2d9cfe33b88df3fa0eaffef8b99bc", $$ACTION_5);
export async function $$ACTION_5() {
console.log(5);
}
......@@ -4,7 +4,12 @@ import deleteFromDb from 'db';
const v1 = 'v1';
export function Item({ id1, id2, id3, id4 }) {
const v2 = id2;
function deleteItem() {}
var deleteItem = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
id1,
v2,
id3,
id4.x
]));
return <Button action={createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
id1,
v2,
......
......@@ -19,7 +19,14 @@ export function y(p, [p1, { p2 }], ...p3) {
if (true) {
const f8 = 1;
}
function action() {}
var action = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
f2,
f11,
p,
p1,
p2,
p3
]));
return <Button action={createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0).bind(null, encryptActionBoundArgs("6d53ce510b2e36499b8f56038817b9bad86cabb4", [
f2,
f11,
......
......@@ -17,7 +17,14 @@ export async function $$ACTION_0($$ACTION_CLOSURE_BOUND) {
await deleteFromDb($$ACTION_ARG_3.id, $$ACTION_ARG_3?.foo, $$ACTION_ARG_3.bar.baz, $$ACTION_ARG_3[$$ACTION_ARG_4, $$ACTION_ARG_5]);
}
export function Item2(product, foo, bar) {
function deleteItem2() {}
var deleteItem2 = createActionProxy("188d5d945750dc32e2c842b93c75a65763d4a922", $$ACTION_1).bind(null, encryptActionBoundArgs("188d5d945750dc32e2c842b93c75a65763d4a922", [
product.id,
product?.foo,
product.bar.baz,
product,
foo,
bar
]));
return <Button action={createActionProxy("188d5d945750dc32e2c842b93c75a65763d4a922", $$ACTION_1).bind(null, encryptActionBoundArgs("188d5d945750dc32e2c842b93c75a65763d4a922", [
product.id,
product?.foo,
......
/* __next_internal_action_entry_do_not_use__ {"6d53ce510b2e36499b8f56038817b9bad86cabb4":"$$ACTION_0"} */ import { createActionProxy } from "private-next-rsc-action-proxy";
import { encryptActionBoundArgs, decryptActionBoundArgs } from "private-next-rsc-action-encryption";
function myAction() {}
var myAction = createActionProxy("6d53ce510b2e36499b8f56038817b9bad86cabb4", $$ACTION_0);
export async function $$ACTION_0(a, b, c) {
// comment
'use strict';
......
......@@ -35,7 +35,7 @@ createNextDescribe(
await check(() => {
return browser.eval('window.location.pathname + window.location.search')
}, '/header?name=test&constructor=_FormData&hidden-info=hi')
}, '/header?name=test&hidden-info=hi')
expect(responseCode).toBe(303)
})
......@@ -52,7 +52,7 @@ createNextDescribe(
await check(() => {
return browser.eval('window.location.pathname + window.location.search')
}, '/header?name=test&constructor=_FormData&hidden-info=hi')
}, '/header?name=test&hidden-info=hi')
})
}
)
......@@ -134,7 +134,7 @@ createNextDescribe(
await check(() => {
return browser.eval('window.location.pathname + window.location.search')
}, '/header?name=test&constructor=_FormData&hidden-info=hi')
}, '/header?name=test&hidden-info=hi')
})
it('should support .bind', async () => {
......@@ -465,7 +465,7 @@ createNextDescribe(
if (isNextDev) {
describe('HMR', () => {
it('should support updating the action', async () => {
const filePath = 'app/server/actions.js'
const filePath = 'app/server/actions-3.js'
const origContent = await next.readFile(filePath)
try {
......
export async function inc(value) {
'use server'
return value + 1
}
......@@ -2,10 +2,6 @@
import { redirect } from 'next/navigation'
export async function inc(value) {
return value + 1
}
export async function slowInc(value) {
await new Promise((resolve) => setTimeout(resolve, 10000))
return value + 1
......@@ -20,8 +16,6 @@ export async function redirectAction(formData) {
redirect(
'/header?name=' +
formData.get('name') +
'&constructor=' +
formData.constructor.name +
'&hidden-info=' +
formData.get('hidden-info')
)
......
import Counter from '../counter'
import Form from '../form'
import dec, { inc } from '../actions'
import dec from '../actions'
import { inc } from '../actions-3'
export default function Page() {
const two = 2
......
......@@ -5,8 +5,6 @@ async function action(formData) {
redirect(
'/header?name=' +
formData.get('name') +
'&constructor=' +
formData.constructor.name +
'&hidden-info=' +
formData.get('hidden-info')
)
......
......@@ -2,8 +2,9 @@ import Counter from './counter'
import Form from './form'
import ClientForm from './client-form'
import dec, { inc, slowInc } from './actions'
import dec, { slowInc } from './actions'
import { log } from './actions-2'
import { inc } from './actions-3'
export default function Page() {
const two = { value: 2 }
......
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