turbopack_ecmascript_plugins/transform/directives/
server.rs

1use anyhow::Result;
2use async_trait::async_trait;
3use swc_core::{
4    ecma::ast::{ModuleItem, Program},
5    quote,
6};
7use turbo_rcstr::RcStr;
8use turbo_tasks::Vc;
9use turbopack_core::issue::IssueExt;
10use turbopack_ecmascript::{CustomTransformer, TransformContext, UnsupportedServerActionIssue};
11
12use super::is_server_module;
13
14#[derive(Debug)]
15pub struct ServerDirectiveTransformer {
16    // ServerDirective is not implemented yet and always reports an issue.
17    // We don't have to pass a valid transition name yet, but the API is prepared.
18    #[allow(unused)]
19    transition_name: Vc<RcStr>,
20}
21
22impl ServerDirectiveTransformer {
23    pub fn new(transition_name: &Vc<RcStr>) -> Self {
24        Self {
25            transition_name: *transition_name,
26        }
27    }
28}
29
30#[async_trait]
31impl CustomTransformer for ServerDirectiveTransformer {
32    #[tracing::instrument(level = tracing::Level::TRACE, name = "server_directive", skip_all)]
33    async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
34        if is_server_module(program) {
35            let stmt = quote!(
36                "throw new Error('Server actions (\"use server\") are not yet supported in \
37                 Turbopack');" as Stmt
38            );
39            match program {
40                Program::Module(m) => m.body = vec![ModuleItem::Stmt(stmt)],
41                Program::Script(s) => s.body = vec![stmt],
42            }
43            UnsupportedServerActionIssue {
44                file_path: ctx.file_path,
45            }
46            .resolved_cell()
47            .emit();
48        }
49
50        Ok(())
51    }
52}