From c6a240969cdd2d6740fa4077a5cefed1d1cb61a1 Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Sun, 16 Feb 2025 05:26:10 +0100 Subject: [PATCH] fix(directive-functions-plugin): handle anonymous default exports (#3447) --- .../src/compilers.ts | 9 ++++ .../tests/compiler.test.ts | 46 +++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/packages/directive-functions-plugin/src/compilers.ts b/packages/directive-functions-plugin/src/compilers.ts index 7be7d71e76..74f66be2b9 100644 --- a/packages/directive-functions-plugin/src/compilers.ts +++ b/packages/directive-functions-plugin/src/compilers.ts @@ -568,6 +568,15 @@ const safeRemoveExports = (ast: babel.types.File) => { const insertIndex = programBody.findIndex( (node) => node === path.node.declaration, ) + // do not remove export if it is an anonymous function / class, otherwise this would produce a syntax error + if ( + babel.types.isFunctionDeclaration(path.node.declaration) || + babel.types.isClassDeclaration(path.node.declaration) + ) { + if (!path.node.declaration.id) { + return + } + } programBody.splice(insertIndex, 0, path.node.declaration as any) } } diff --git a/packages/directive-functions-plugin/tests/compiler.test.ts b/packages/directive-functions-plugin/tests/compiler.test.ts index 6aca7f1df6..81f8d2fe11 100644 --- a/packages/directive-functions-plugin/tests/compiler.test.ts +++ b/packages/directive-functions-plugin/tests/compiler.test.ts @@ -710,4 +710,50 @@ describe('server function compilation', () => { export { serverFnConstWithImport_1, serverFnNamedWithImport_1 };" `) }) + test('async function with anonymous default export', () => { + const code = ` + async function bytesSignupServerFn({ email }: { email: string }) { + 'use server' + return 'test' + } + export default function () { + return null; + } + ` + + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) + const server = compileDirectives({ + ...serverConfig, + code, + filename: + ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! + .extractedFilename, + }) + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "export default function () { + return null; + }" + `) + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "export default function () { + return null; + }" + `) + expect(server.compiledResult.code).toMatchInlineSnapshot(` + "import { createServerRpc } from "my-rpc-lib-server"; + const bytesSignupServerFn_1 = createServerRpc("test_ts--bytesSignupServerFn_1", async function ({ + email + }: { + email: string; + }) { + return 'test'; + }); + export default function () { + return null; + } + export { bytesSignupServerFn_1 };" + `) + }) })