Unverified Commit 9151d0aa authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Emit server-layer actions from their own module

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 3f06bc37
......@@ -3266,12 +3266,19 @@ fn emit_server_action(
) -> Vec<Stmt> {
if mode == ServerActionsMode::Turbopack {
let emit = quote_ident!(unresolved_ctxt, "__turbopack_emit__");
let req: Expr = format!(
"./{}{}",
PathBuf::from(file_name).file_name().unwrap().display(),
file_query.as_deref().unwrap_or(""),
)
.into();
let req: Expr = if is_react_server_layer {
// Processed filenames (e.g. MDX) may not exist on disk. Emit this module directly.
Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))
} else {
// Client emits can live in per-export data: proxies, so their target is the action
// file rather than the proxy module containing this call.
format!(
"./{}{}",
PathBuf::from(file_name).file_name().unwrap().display(),
file_query.as_deref().unwrap_or(""),
)
.into()
};
let data: Expr = format!("{action_id}\0{export}\0{file_name}").into();
if is_react_server_layer {
......
......@@ -3,7 +3,7 @@
import { registerServerReference } from "private-next-rsc-server-reference";
export const $$RSC_SERVER_ACTION_0 = async function action() {};
registerServerReference($$RSC_SERVER_ACTION_0, "006a88810ecce4a4e8b59d53b8327d7e98bbf251d7", null);
__turbopack_emit__("./item.js", {
__turbopack_emit__(null, {
namespace: process.env.NEXT_RUNTIME === 'nodejs' ? 'next/server-actions/rsc-nodejs' : 'next/server-actions/rsc-edge',
data: "006a88810ecce4a4e8b59d53b8327d7e98bbf251d7\0$$RSC_SERVER_ACTION_0\0/app/item.js"
});
......
......@@ -61,7 +61,7 @@ declare function __turbopack_emit__(opts: {
}
}): void
declare function __turbopack_emit__(
req: string,
req: string | null,
opts: {
namespace: string
data: any
......
......@@ -4,7 +4,7 @@ export const $$RSC_SERVER_ACTION_0 = async function deleteItem() {
console.log('delete item');
};
registerServerReference($$RSC_SERVER_ACTION_0, "006a88810ecce4a4e8b59d53b8327d7e98bbf251d7", null);
__turbopack_emit__("./item.js", {
__turbopack_emit__(null, {
namespace: process.env.NEXT_RUNTIME === 'nodejs' ? 'next/server-actions/rsc-nodejs' : 'next/server-actions/rsc-edge',
data: "006a88810ecce4a4e8b59d53b8327d7e98bbf251d7\0$$RSC_SERVER_ACTION_0\0/app/item.js"
});
......@@ -18,7 +18,7 @@ export const $$RSC_SERVER_ACTION_1 = async function action($$ACTION_CLOSURE_BOUN
console.log($$ACTION_ARG_1);
};
registerServerReference($$RSC_SERVER_ACTION_1, "4090b5db271335765a4b0eab01f044b381b5ebd5cd", null);
__turbopack_emit__("./item.js", {
__turbopack_emit__(null, {
namespace: process.env.NEXT_RUNTIME === 'nodejs' ? 'next/server-actions/rsc-nodejs' : 'next/server-actions/rsc-edge',
data: "4090b5db271335765a4b0eab01f044b381b5ebd5cd\0$$RSC_SERVER_ACTION_1\0/app/item.js"
});
......
......@@ -8,7 +8,7 @@ ensureServerEntryExports([
myAction
]);
registerServerReference(myAction, "70e10665baac148856374b2789aceb970f66fec33e", null);
__turbopack_emit__("./item.js", {
__turbopack_emit__(null, {
namespace: process.env.NEXT_RUNTIME === 'nodejs' ? 'next/server-actions/rsc-nodejs' : 'next/server-actions/rsc-edge',
data: "70e10665baac148856374b2789aceb970f66fec33e\0myAction\0/app/item.js"
});
......@@ -8,7 +8,7 @@ export var $$RSC_SERVER_CACHE_0 = $$reactCache__(function my_fn() {
return $$cache__("default", "803128060c414d59f8552e4788b846c0d2b7f74743", 0, $$RSC_SERVER_CACHE_0_INNER, []);
});
registerServerReference($$RSC_SERVER_CACHE_0, "803128060c414d59f8552e4788b846c0d2b7f74743", null);
__turbopack_emit__("./item.js", {
__turbopack_emit__(null, {
namespace: process.env.NEXT_RUNTIME === 'nodejs' ? 'next/server-actions/rsc-nodejs' : 'next/server-actions/rsc-edge',
data: "803128060c414d59f8552e4788b846c0d2b7f74743\0$$RSC_SERVER_CACHE_0\0/app/item.js"
});
......
import { redirect } from 'next/navigation'
export async function submit() {
'use server'
redirect('/import?from=mdx-action')
}
# MDX Server Action
<form action={submit}>
<button id="submit-mdx-action">Submit</button>
</form>
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
for (const type of ['with-mdx-rs', 'without-mdx-rs']) {
describe(`mdx ${type}`, () => {
......@@ -20,6 +21,15 @@ for (const type of ['with-mdx-rs', 'without-mdx-rs']) {
})
describe('app directory', () => {
it('should invoke an inline server action from MDX', async () => {
const browser = await next.browser('/actions')
await browser.elementById('submit-mdx-action').click()
await retry(async () => {
expect(await browser.url()).toContain('/import?from=mdx-action')
})
expect(await browser.elementByCss('h1').text()).toBe('This is a title')
})
it('should work in initial html', async () => {
const $ = await next.render$('/')
expect($('h1').text()).toBe('Hello World')
......
......@@ -38,11 +38,12 @@ use crate::{
};
#[turbo_tasks::value]
#[derive(Hash, Debug, ValueToString)]
#[value_to_string("emit {request} {namespace}")]
#[derive(Hash, Debug)]
pub struct EmitReference {
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: ResolvedVc<Request>,
parent_module: ResolvedVc<Box<dyn Module>>,
/// `None` denotes an explicit null target: emit the originating module.
request: Option<ResolvedVc<Request>>,
annotations: ImportAnnotations,
issue_source: IssueSource,
error_mode: ResolveErrorMode,
......@@ -55,7 +56,8 @@ pub struct EmitReference {
impl EmitReference {
pub fn new(
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: ResolvedVc<Request>,
parent_module: ResolvedVc<Box<dyn Module>>,
request: Option<ResolvedVc<Request>>,
issue_source: IssueSource,
annotations: ImportAnnotations,
error_mode: ResolveErrorMode,
......@@ -66,6 +68,7 @@ impl EmitReference {
) -> Self {
EmitReference {
origin,
parent_module,
request,
issue_source,
annotations,
......@@ -103,9 +106,17 @@ impl ModuleReference for EmitReference {
);
}
let Some(request) = self.request else {
if self.annotations.transition().is_some() {
bail!("Transitions are not supported with a null emit target");
}
// Keep the module identity instead of resolving a processed filename on disk.
return Ok(*ModuleResolveResult::module(self.parent_module));
};
esm_resolve(
*origin,
*self.request,
*request,
EcmaScriptModulesReferenceSubType::Emit,
self.error_mode,
Some(self.issue_source),
......@@ -128,6 +139,18 @@ impl ModuleReference for EmitReference {
}
}
#[turbo_tasks::value_impl]
impl ValueToString for EmitReference {
#[turbo_tasks::function]
async fn to_string(&self) -> Result<Vc<RcStr>> {
let target = match self.request {
Some(request) => (*request.to_string().await?).clone(),
None => rcstr!("<self>"),
};
Ok(Vc::cell(format!("emit {target} {}", self.namespace).into()))
}
}
#[turbo_tasks::value_impl]
impl EmittedModuleReference for EmitReference {
#[turbo_tasks::function]
......
......@@ -3402,13 +3402,17 @@ where
}
WellKnownFunctionKind::TurbopackEmit => {
let args = linked_args().await?;
let (specifier, options) = match &args[..] {
let (specifier, options, is_self_reference) = match &args[..] {
[
JsValue::Constant(JsConstantValue::Str(specifier)),
JsValue::Object { parts: options, .. },
] => (Some(specifier), Some(options)),
[JsValue::Object { parts: options, .. }] => (None, Some(options)),
_ => (None, None),
] => (Some(specifier), Some(options), false),
[
JsValue::Constant(JsConstantValue::Null),
JsValue::Object { parts: options, .. },
] => (None, Some(options), true),
[JsValue::Object { parts: options, .. }] => (None, Some(options), false),
_ => (None, None, false),
};
if let Some(options) = options {
......@@ -3493,9 +3497,10 @@ where
_ => return invalid_args("exports"),
};
analysis.add_reference_code_gen(
EmitReference::new(
origin,
let request = if is_self_reference {
None
} else {
Some(
Request::parse_string(
specifier
// TODO support data-only emit
......@@ -3504,6 +3509,13 @@ where
)
.to_resolved()
.await?,
)
};
analysis.add_reference_code_gen(
EmitReference::new(
origin,
parent_module,
request,
issue_source(source, span),
annotations,
ResolveErrorMode::Error,
......
__turbopack_emit__(null, {
namespace: 'self-test',
data: 'self-emitted data',
})
export const value = 'self-emitted value'
import { value as firstValue } from './emitter.js?first'
import { value as secondValue } from './emitter.js?second'
const getList = __turbopack_collect__({ namespace: 'self-test' })
it('should emit the originating module and preserve its query', async () => {
expect(firstValue).toBe('self-emitted value')
expect(secondValue).toBe('self-emitted value')
const list = getList()
expect(list).toHaveLength(2)
expect(list.map((entry) => entry.id)).toEqual(
expect.arrayContaining([
expect.stringContaining('emitter.js?first'),
expect.stringContaining('emitter.js?second'),
])
)
const modules = await Promise.all(
list.map(async (entry) => {
expect(entry.data).toBe('self-emitted data')
const module = await entry.import()
expect(module.value).toBe('self-emitted value')
return module
})
)
expect(modules[0]).not.toBe(modules[1])
})
{
"scopeHoisting": false,
"inferModuleSideEffects": false
}
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