Skip to main content

next_custom_transforms/transforms/
server_actions.rs

1use std::{
2    cell::RefCell,
3    collections::{BTreeMap, hash_map},
4    convert::{TryFrom, TryInto},
5    mem::{replace, take},
6    path::{Path, PathBuf},
7    rc::Rc,
8    sync::Arc,
9};
10
11use base64::{display::Base64Display, prelude::BASE64_STANDARD};
12use hex::encode as hex_encode;
13use indoc::formatdoc;
14use pathdiff::diff_paths;
15use rustc_hash::{FxHashMap, FxHashSet};
16use serde::Deserialize;
17use sha1::{Digest, Sha1};
18use swc_core::{
19    atoms::{Atom, Wtf8Atom, atom},
20    common::{
21        BytePos, DUMMY_SP, FileName, Mark, SourceMap, Span, SyntaxContext,
22        comments::{Comment, CommentKind, Comments, SingleThreadedComments},
23        errors::HANDLER,
24        source_map::{PURE_SP, SourceMapGenConfig},
25        util::take::Take,
26    },
27    ecma::{
28        ast::*,
29        codegen::{self, Emitter, text_writer::JsWriter},
30        utils::{ExprFactory, private_ident, quote_ident},
31        visit::{VisitMut, VisitMutWith, noop_visit_mut_type, visit_mut_pass},
32    },
33    quote,
34};
35use turbo_rcstr::{RcStr, rcstr};
36
37use crate::FxIndexMap;
38
39#[derive(Clone, Copy, Debug, Deserialize)]
40pub enum ServerActionsMode {
41    Webpack,
42    Turbopack,
43}
44
45#[derive(Clone, Debug, Deserialize)]
46#[serde(deny_unknown_fields, rename_all = "camelCase")]
47pub struct Config {
48    pub is_react_server_layer: bool,
49    pub is_development: bool,
50    pub use_cache_enabled: bool,
51    pub hash_salt: String,
52    pub cache_kinds: FxHashSet<RcStr>,
53}
54
55#[derive(Clone, Debug)]
56enum Directive {
57    UseServer,
58    UseCache { cache_kind: RcStr },
59}
60
61#[derive(Clone, Debug)]
62enum DirectiveLocation {
63    Module,
64    FunctionBody,
65}
66
67#[derive(Clone, Debug)]
68enum ThisStatus {
69    Allowed,
70    Forbidden { directive: Directive },
71}
72
73#[derive(Clone)]
74struct ServerReferenceExport {
75    ident: Ident,
76    export_name: ModuleExportName,
77    reference_id: Atom,
78    needs_cache_runtime_wrapper: bool,
79}
80
81/// Export info for serialization
82#[derive(Clone, Debug, serde::Serialize)]
83struct ServerReferenceExportInfo {
84    name: Atom,
85}
86
87#[derive(Clone, Debug)]
88enum ServerActionsErrorKind {
89    ExportedSyncFunction {
90        span: Span,
91        in_action_file: bool,
92    },
93    ForbiddenExpression {
94        span: Span,
95        expr: String,
96        directive: Directive,
97    },
98    InlineSyncFunction {
99        span: Span,
100        directive: Directive,
101    },
102    InlineUseCacheInClassInstanceMethod {
103        span: Span,
104    },
105    InlineUseCacheInClientComponent {
106        span: Span,
107    },
108    InlineUseServerInClassInstanceMethod {
109        span: Span,
110    },
111    InlineUseServerInClientComponent {
112        span: Span,
113    },
114    MisplacedDirective {
115        span: Span,
116        directive: String,
117        location: DirectiveLocation,
118    },
119    MisplacedWrappedDirective {
120        span: Span,
121        directive: String,
122        location: DirectiveLocation,
123    },
124    MisspelledDirective {
125        span: Span,
126        directive: String,
127        expected_directive: String,
128    },
129    MultipleDirectives {
130        span: Span,
131        location: DirectiveLocation,
132    },
133    UnknownCacheKind {
134        span: Span,
135        cache_kind: RcStr,
136    },
137    UseCacheWithoutCacheComponents {
138        span: Span,
139        directive: String,
140    },
141    WrappedDirective {
142        span: Span,
143        directive: String,
144    },
145}
146
147#[allow(clippy::too_many_arguments)]
148#[tracing::instrument(level = tracing::Level::TRACE, skip_all)]
149pub fn server_actions<C: Comments>(
150    file_name: &FileName,
151    file_query: Option<RcStr>,
152    config: Config,
153    comments: C,
154    unresolved_mark: Mark,
155    cm: Arc<SourceMap>,
156    use_cache_telemetry_tracker: Rc<RefCell<FxHashMap<String, usize>>>,
157    mode: ServerActionsMode,
158) -> impl Pass + use<C> {
159    visit_mut_pass(ServerActions {
160        config,
161        mode,
162        comments,
163        cm,
164        file_name: file_name.to_string(),
165        file_query,
166        start_pos: BytePos(0),
167        file_directive: None,
168        current_export_name: None,
169        fn_decl_ident: None,
170        in_callee: false,
171        has_action: false,
172        has_cache: false,
173        this_status: ThisStatus::Allowed,
174
175        reference_index: 0,
176        in_module_level: true,
177        should_track_names: false,
178        has_server_reference_with_bound_args: false,
179
180        names: Default::default(),
181        declared_idents: Default::default(),
182
183        // This flag allows us to rewrite `function foo() {}` to `const foo = createProxy(...)`.
184        rewrite_fn_decl_to_proxy_decl: None,
185        rewrite_default_fn_expr_to_proxy_expr: None,
186        rewrite_expr_to_proxy_expr: None,
187
188        annotations: Default::default(),
189        extra_items: Default::default(),
190        hoisted_extra_items: Default::default(),
191        reference_ids_by_export_name: Default::default(),
192        server_reference_exports: Default::default(),
193
194        private_ctxt: SyntaxContext::empty().apply_mark(Mark::new()),
195        unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
196
197        arrow_or_fn_expr_ident: None,
198        export_name_by_local_id: Default::default(),
199        local_ids_that_need_cache_runtime_wrapper_if_exported: FxHashSet::default(),
200
201        use_cache_telemetry_tracker,
202    })
203}
204
205/// Serializes the Server References into a magic comment prefixed by
206/// `__next_internal_action_entry_do_not_use__`.
207fn generate_server_references_comment(
208    export_infos_ordered_by_reference_id: &BTreeMap<&Atom, ServerReferenceExportInfo>,
209    entry_path_query: Option<(&str, &str)>,
210) -> String {
211    format!(
212        " __next_internal_action_entry_do_not_use__ {} ",
213        if let Some(entry_path_query) = entry_path_query {
214            serde_json::to_string(&(
215                &export_infos_ordered_by_reference_id,
216                entry_path_query.0,
217                entry_path_query.1,
218            ))
219        } else {
220            serde_json::to_string(&export_infos_ordered_by_reference_id)
221        }
222        .unwrap()
223    )
224}
225
226struct ServerActions<C: Comments> {
227    #[allow(unused)]
228    config: Config,
229    file_name: String,
230    file_query: Option<RcStr>,
231    comments: C,
232    cm: Arc<SourceMap>,
233    mode: ServerActionsMode,
234
235    start_pos: BytePos,
236    file_directive: Option<Directive>,
237    current_export_name: Option<ModuleExportName>,
238    fn_decl_ident: Option<Ident>,
239    in_callee: bool,
240    has_action: bool,
241    has_cache: bool,
242    this_status: ThisStatus,
243
244    reference_index: u32,
245    in_module_level: bool,
246    should_track_names: bool,
247    has_server_reference_with_bound_args: bool,
248
249    names: Vec<Name>,
250    declared_idents: Vec<Ident>,
251
252    // This flag allows us to rewrite `function foo() {}` to `const foo = createProxy(...)`.
253    rewrite_fn_decl_to_proxy_decl: Option<VarDecl>,
254    rewrite_default_fn_expr_to_proxy_expr: Option<Box<Expr>>,
255    rewrite_expr_to_proxy_expr: Option<Box<Expr>>,
256
257    annotations: Vec<Stmt>,
258    extra_items: Vec<ModuleItem>,
259    hoisted_extra_items: Vec<ModuleItem>,
260
261    /// A map of all server references (inline + exported): export_name -> reference_id
262    reference_ids_by_export_name: FxIndexMap<ModuleExportName, Atom>,
263
264    /// A list of server references for originally exported server functions only.
265    server_reference_exports: Vec<ServerReferenceExport>,
266
267    private_ctxt: SyntaxContext,
268    unresolved_ctxt: SyntaxContext,
269
270    arrow_or_fn_expr_ident: Option<Ident>,
271    export_name_by_local_id: FxIndexMap<Id, ModuleExportName>,
272
273    /// Tracks which local IDs need cache runtime wrappers if exported (collected during pre-pass).
274    /// Includes imports, destructured identifiers, and variables with unknown-type init
275    /// expressions (calls, identifiers, etc.). Excludes known functions (arrow/fn
276    /// declarations) and known non-functions (object/array/literals). When these IDs are
277    /// exported, their exports are stripped and replaced with conditional wrappers.
278    local_ids_that_need_cache_runtime_wrapper_if_exported: FxHashSet<Id>,
279
280    use_cache_telemetry_tracker: Rc<RefCell<FxHashMap<String, usize>>>,
281}
282
283impl<C: Comments> ServerActions<C> {
284    fn generate_server_reference_id(
285        &self,
286        export_name: &ModuleExportName,
287        is_cache: bool,
288        params: Option<&Vec<Param>>,
289    ) -> Atom {
290        // Attach a checksum to the action using sha1:
291        // $$id = special_byte + sha1('hash_salt' + 'file_name' + ':' + 'export_name');
292        // Currently encoded as hex.
293
294        let mut hasher = Sha1::new();
295        hasher.update(self.config.hash_salt.as_bytes());
296        hasher.update(self.file_name.as_bytes());
297        hasher.update(b":");
298
299        let export_name_bytes = match export_name {
300            ModuleExportName::Ident(ident) => &ident.sym.as_bytes(),
301            ModuleExportName::Str(s) => &s.value.as_bytes(),
302        };
303
304        hasher.update(export_name_bytes);
305
306        let mut result = hasher.finalize().to_vec();
307
308        // Prepend an extra byte to the ID, with the following format:
309        // 0     000000    0
310        // ^type ^arg mask ^rest args
311        //
312        // The type bit represents if the action is a cache function or not.
313        // For cache functions, the type bit is set to 1. Otherwise, it's 0.
314        //
315        // The arg mask bit is used to determine which arguments are used by
316        // the function itself, up to 6 arguments. The bit is set to 1 if the
317        // argument is used, or being spread or destructured (so it can be
318        // indirectly or partially used). The bit is set to 0 otherwise.
319        //
320        // The rest args bit is used to determine if there's a ...rest argument
321        // in the function signature. If there is, the bit is set to 1.
322        //
323        //  For example:
324        //
325        //   async function foo(a, foo, b, bar, ...baz) {
326        //     'use cache';
327        //     return a + b;
328        //   }
329        //
330        // will have it encoded as [1][101011][1]. The first bit is set to 1
331        // because it's a cache function. The second part has 1010 because the
332        // only arguments used are `a` and `b`. The subsequent 11 bits are set
333        // to 1 because there's a ...rest argument starting from the 5th. The
334        // last bit is set to 1 as well for the same reason.
335        let type_bit = if is_cache { 1u8 } else { 0u8 };
336        let mut arg_mask = 0u8;
337        let mut rest_args = 0u8;
338
339        if let Some(params) = params {
340            // TODO: For the current implementation, we don't track if an
341            // argument ident is actually referenced in the function body.
342            // Instead, we go with the easy route and assume defined ones are
343            // used. This can be improved in the future.
344            for (i, param) in params.iter().enumerate() {
345                if let Pat::Rest(_) = param.pat {
346                    // If there's a ...rest argument, we set the rest args bit
347                    // to 1 and set the arg mask to 0b111111.
348                    arg_mask = 0b111111;
349                    rest_args = 0b1;
350                    break;
351                }
352                if i < 6 {
353                    arg_mask |= 0b1 << (5 - i);
354                } else {
355                    // More than 6 arguments, we set the rest args bit to 1.
356                    // This is rare for a Server Action, usually.
357                    rest_args = 0b1;
358                    break;
359                }
360            }
361        } else {
362            // If we can't determine the arguments (e.g. not statically analyzable),
363            // we assume all arguments are used.
364            arg_mask = 0b111111;
365            rest_args = 0b1;
366        }
367
368        result.push((type_bit << 7) | (arg_mask << 1) | rest_args);
369        result.rotate_right(1);
370
371        Atom::from(hex_encode(result))
372    }
373
374    fn is_default_export(&self) -> bool {
375        matches!(
376            self.current_export_name,
377            Some(ModuleExportName::Ident(ref i)) if i.sym == *"default"
378        )
379    }
380
381    fn gen_action_ident(&mut self) -> Atom {
382        let id: Atom = format!("$$RSC_SERVER_ACTION_{0}", self.reference_index).into();
383        self.reference_index += 1;
384        id
385    }
386
387    fn gen_cache_ident(&mut self) -> Atom {
388        let id: Atom = format!("$$RSC_SERVER_CACHE_{0}", self.reference_index).into();
389        self.reference_index += 1;
390        id
391    }
392
393    fn create_bound_action_args_array_pat(&mut self, arg_len: usize) -> Pat {
394        Pat::Array(ArrayPat {
395            span: DUMMY_SP,
396            elems: (0..arg_len)
397                .map(|i| {
398                    Some(Pat::Ident(
399                        Ident::new(
400                            format!("$$ACTION_ARG_{i}").into(),
401                            DUMMY_SP,
402                            self.private_ctxt,
403                        )
404                        .into(),
405                    ))
406                })
407                .collect(),
408            optional: false,
409            type_ann: None,
410        })
411    }
412
413    // Check if the function or arrow function is an action or cache function,
414    // and remove any server function directive.
415    fn get_directive_for_function(
416        &mut self,
417        maybe_body: Option<&mut BlockStmt>,
418    ) -> Option<Directive> {
419        let mut directive: Option<Directive> = None;
420
421        // Even if it's a file-level action or cache module, the function body
422        // might still have directives that override the module-level annotations.
423        if let Some(body) = maybe_body {
424            let directive_visitor = &mut DirectiveVisitor {
425                config: &self.config,
426                directive: None,
427                has_file_directive: self.file_directive.is_some(),
428                is_allowed_position: true,
429                location: DirectiveLocation::FunctionBody,
430                use_cache_telemetry_tracker: self.use_cache_telemetry_tracker.clone(),
431            };
432
433            body.stmts.retain(|stmt| {
434                let has_directive = directive_visitor.visit_stmt(stmt);
435
436                !has_directive
437            });
438
439            directive = directive_visitor.directive.clone();
440        }
441
442        // All exported functions inherit the file directive if they don't have their own directive.
443        if self.current_export_name.is_some()
444            && directive.is_none()
445            && self.file_directive.is_some()
446        {
447            return self.file_directive.clone();
448        }
449
450        directive
451    }
452
453    fn get_directive_for_module(&mut self, stmts: &mut Vec<ModuleItem>) -> Option<Directive> {
454        let directive_visitor = &mut DirectiveVisitor {
455            config: &self.config,
456            directive: None,
457            has_file_directive: false,
458            is_allowed_position: true,
459            location: DirectiveLocation::Module,
460            use_cache_telemetry_tracker: self.use_cache_telemetry_tracker.clone(),
461        };
462
463        stmts.retain(|item| {
464            if let ModuleItem::Stmt(stmt) = item {
465                let has_directive = directive_visitor.visit_stmt(stmt);
466
467                !has_directive
468            } else {
469                directive_visitor.is_allowed_position = false;
470                true
471            }
472        });
473
474        directive_visitor.directive.clone()
475    }
476
477    fn maybe_hoist_and_create_proxy_for_server_action_arrow_expr(
478        &mut self,
479        ids_from_closure: Vec<Name>,
480        arrow: &mut ArrowExpr,
481    ) -> Box<Expr> {
482        let mut new_params: Vec<Param> = vec![];
483
484        let closure_bound_ident =
485            Ident::new(atom!("$$ACTION_CLOSURE_BOUND"), DUMMY_SP, self.private_ctxt);
486
487        if !ids_from_closure.is_empty() {
488            // First param is the encrypted closure variables.
489            new_params.push(Param {
490                span: DUMMY_SP,
491                decorators: vec![],
492                pat: Pat::Ident(closure_bound_ident.clone().into()),
493            });
494        }
495
496        for p in arrow.params.iter() {
497            new_params.push(Param::from(p.clone()));
498        }
499
500        let action_name = self.gen_action_ident();
501        let action_ident = Ident::new(action_name.clone(), arrow.span, self.private_ctxt);
502        let action_id = self.generate_server_reference_id(
503            &ModuleExportName::Ident(action_ident.clone()),
504            false,
505            Some(&new_params),
506        );
507
508        self.has_action = true;
509        self.reference_ids_by_export_name.insert(
510            ModuleExportName::Ident(action_ident.clone()),
511            action_id.clone(),
512        );
513
514        // If this is an exported arrow, remove it from export_name_by_local_id so the
515        // post-pass doesn't register it again (it's already registered above).
516        if self.current_export_name.is_some()
517            && let Some(arrow_ident) = &self.arrow_or_fn_expr_ident
518        {
519            self.export_name_by_local_id
520                .swap_remove(&arrow_ident.to_id());
521        }
522
523        if let BlockStmtOrExpr::BlockStmt(block) = &mut *arrow.body {
524            block.visit_mut_with(&mut ClosureReplacer {
525                used_ids: &ids_from_closure,
526                private_ctxt: self.private_ctxt,
527            });
528        }
529
530        let mut new_body: BlockStmtOrExpr = *arrow.body.clone();
531
532        if !ids_from_closure.is_empty() {
533            // Prepend the decryption declaration to the body.
534            // var [arg1, arg2, arg3] = await decryptActionBoundArgs(actionId,
535            // $$ACTION_CLOSURE_BOUND)
536            let decryption_decl = VarDecl {
537                span: DUMMY_SP,
538                kind: VarDeclKind::Var,
539                declare: false,
540                decls: vec![VarDeclarator {
541                    span: DUMMY_SP,
542                    name: self.create_bound_action_args_array_pat(ids_from_closure.len()),
543                    init: Some(Box::new(Expr::Await(AwaitExpr {
544                        span: DUMMY_SP,
545                        arg: Box::new(Expr::Call(CallExpr {
546                            span: DUMMY_SP,
547                            callee: quote_ident!("decryptActionBoundArgs").as_callee(),
548                            args: vec![action_id.clone().as_arg(), closure_bound_ident.as_arg()],
549                            ..Default::default()
550                        })),
551                    }))),
552                    definite: Default::default(),
553                }],
554                ..Default::default()
555            };
556
557            match &mut new_body {
558                BlockStmtOrExpr::BlockStmt(body) => {
559                    body.stmts.insert(0, decryption_decl.into());
560                }
561                BlockStmtOrExpr::Expr(body_expr) => {
562                    new_body = BlockStmtOrExpr::BlockStmt(BlockStmt {
563                        span: DUMMY_SP,
564                        stmts: vec![
565                            decryption_decl.into(),
566                            Stmt::Return(ReturnStmt {
567                                span: DUMMY_SP,
568                                arg: Some(body_expr.take()),
569                            }),
570                        ],
571                        ..Default::default()
572                    });
573                }
574            }
575        }
576
577        // Create the action export decl from the arrow function
578        // export const $$RSC_SERVER_ACTION_0 = async function action($$ACTION_CLOSURE_BOUND) {}
579        self.hoisted_extra_items
580            .push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
581                span: DUMMY_SP,
582                decl: VarDecl {
583                    kind: VarDeclKind::Const,
584                    span: DUMMY_SP,
585                    decls: vec![VarDeclarator {
586                        span: DUMMY_SP,
587                        name: Pat::Ident(action_ident.clone().into()),
588                        definite: false,
589                        init: Some(Box::new(Expr::Fn(FnExpr {
590                            ident: self.arrow_or_fn_expr_ident.clone(),
591                            function: Box::new(Function {
592                                params: new_params,
593                                body: match new_body {
594                                    BlockStmtOrExpr::BlockStmt(body) => Some(body),
595                                    BlockStmtOrExpr::Expr(expr) => Some(BlockStmt {
596                                        span: DUMMY_SP,
597                                        stmts: vec![Stmt::Return(ReturnStmt {
598                                            span: DUMMY_SP,
599                                            arg: Some(expr),
600                                        })],
601                                        ..Default::default()
602                                    }),
603                                },
604                                is_async: true,
605                                ..Default::default()
606                            }),
607                        }))),
608                    }],
609                    declare: Default::default(),
610                    ctxt: self.private_ctxt,
611                }
612                .into(),
613            })));
614
615        self.hoisted_extra_items
616            .push(ModuleItem::Stmt(Stmt::Expr(ExprStmt {
617                span: DUMMY_SP,
618                expr: Box::new(annotate_ident_as_server_reference(
619                    action_ident.clone(),
620                    action_id.clone(),
621                    arrow.span,
622                )),
623            })));
624
625        if ids_from_closure.is_empty() {
626            Box::new(action_ident.clone().into())
627        } else {
628            self.has_server_reference_with_bound_args = true;
629            Box::new(bind_args_to_ident(
630                action_ident.clone(),
631                ids_from_closure
632                    .iter()
633                    .cloned()
634                    .map(|id| Some(id.as_arg()))
635                    .collect(),
636                action_id.clone(),
637            ))
638        }
639    }
640
641    fn maybe_hoist_and_create_proxy_for_server_action_function(
642        &mut self,
643        ids_from_closure: Vec<Name>,
644        function: &mut Function,
645        fn_name: Option<Ident>,
646    ) -> Box<Expr> {
647        let mut new_params: Vec<Param> = vec![];
648
649        let closure_bound_ident =
650            Ident::new(atom!("$$ACTION_CLOSURE_BOUND"), DUMMY_SP, self.private_ctxt);
651
652        if !ids_from_closure.is_empty() {
653            // First param is the encrypted closure variables.
654            new_params.push(Param {
655                span: DUMMY_SP,
656                decorators: vec![],
657                pat: Pat::Ident(closure_bound_ident.clone().into()),
658            });
659        }
660
661        new_params.append(&mut function.params);
662
663        let action_name: Atom = self.gen_action_ident();
664        let mut action_ident = Ident::new(action_name.clone(), function.span, self.private_ctxt);
665        if action_ident.span.lo == self.start_pos {
666            action_ident.span = Span::dummy_with_cmt();
667        }
668
669        let action_id = self.generate_server_reference_id(
670            &ModuleExportName::Ident(action_ident.clone()),
671            false,
672            Some(&new_params),
673        );
674
675        self.has_action = true;
676        self.reference_ids_by_export_name.insert(
677            ModuleExportName::Ident(action_ident.clone()),
678            action_id.clone(),
679        );
680
681        // If this is an exported function, remove it from export_name_by_local_id so the
682        // post-pass doesn't register it again (it's already registered above).
683        if self.current_export_name.is_some()
684            && let Some(ref fn_name) = fn_name
685        {
686            self.export_name_by_local_id.swap_remove(&fn_name.to_id());
687        }
688
689        function.body.visit_mut_with(&mut ClosureReplacer {
690            used_ids: &ids_from_closure,
691            private_ctxt: self.private_ctxt,
692        });
693
694        let mut new_body: Option<BlockStmt> = function.body.clone();
695
696        if !ids_from_closure.is_empty() {
697            // Prepend the decryption declaration to the body.
698            // var [arg1, arg2, arg3] = await decryptActionBoundArgs(actionId,
699            // $$ACTION_CLOSURE_BOUND)
700            let decryption_decl = VarDecl {
701                span: DUMMY_SP,
702                kind: VarDeclKind::Var,
703                decls: vec![VarDeclarator {
704                    span: DUMMY_SP,
705                    name: self.create_bound_action_args_array_pat(ids_from_closure.len()),
706                    init: Some(Box::new(Expr::Await(AwaitExpr {
707                        span: DUMMY_SP,
708                        arg: Box::new(Expr::Call(CallExpr {
709                            span: DUMMY_SP,
710                            callee: quote_ident!("decryptActionBoundArgs").as_callee(),
711                            args: vec![action_id.clone().as_arg(), closure_bound_ident.as_arg()],
712                            ..Default::default()
713                        })),
714                    }))),
715                    definite: Default::default(),
716                }],
717                ..Default::default()
718            };
719
720            if let Some(body) = &mut new_body {
721                body.stmts.insert(0, decryption_decl.into());
722            } else {
723                new_body = Some(BlockStmt {
724                    span: DUMMY_SP,
725                    stmts: vec![decryption_decl.into()],
726                    ..Default::default()
727                });
728            }
729        }
730
731        // Create the action export decl from the function
732        // export const $$RSC_SERVER_ACTION_0 = async function action($$ACTION_CLOSURE_BOUND) {}
733        self.hoisted_extra_items
734            .push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
735                span: DUMMY_SP,
736                decl: VarDecl {
737                    kind: VarDeclKind::Const,
738                    span: DUMMY_SP,
739                    decls: vec![VarDeclarator {
740                        span: DUMMY_SP, // TODO: need to map it to the original span?
741                        name: Pat::Ident(action_ident.clone().into()),
742                        definite: false,
743                        init: Some(Box::new(Expr::Fn(FnExpr {
744                            ident: fn_name,
745                            function: Box::new(Function {
746                                params: new_params,
747                                body: new_body,
748                                ..function.take()
749                            }),
750                        }))),
751                    }],
752                    declare: Default::default(),
753                    ctxt: self.private_ctxt,
754                }
755                .into(),
756            })));
757
758        self.hoisted_extra_items
759            .push(ModuleItem::Stmt(Stmt::Expr(ExprStmt {
760                span: DUMMY_SP,
761                expr: Box::new(annotate_ident_as_server_reference(
762                    action_ident.clone(),
763                    action_id.clone(),
764                    function.span,
765                )),
766            })));
767
768        if ids_from_closure.is_empty() {
769            Box::new(action_ident.clone().into())
770        } else {
771            self.has_server_reference_with_bound_args = true;
772            Box::new(bind_args_to_ident(
773                action_ident.clone(),
774                ids_from_closure
775                    .iter()
776                    .cloned()
777                    .map(|id| Some(id.as_arg()))
778                    .collect(),
779                action_id.clone(),
780            ))
781        }
782    }
783
784    fn maybe_hoist_and_create_proxy_for_cache_arrow_expr(
785        &mut self,
786        ids_from_closure: Vec<Name>,
787        cache_kind: RcStr,
788        arrow: &mut ArrowExpr,
789    ) -> Box<Expr> {
790        let mut new_params: Vec<Param> = vec![];
791
792        // Add the collected closure variables as the first parameter to the
793        // function. They are unencrypted and passed into this function by the
794        // cache wrapper.
795        if !ids_from_closure.is_empty() {
796            new_params.push(Param {
797                span: DUMMY_SP,
798                decorators: vec![],
799                pat: self.create_bound_action_args_array_pat(ids_from_closure.len()),
800            });
801        }
802
803        for p in arrow.params.iter() {
804            new_params.push(Param::from(p.clone()));
805        }
806
807        let cache_name: Atom = self.gen_cache_ident();
808        let export_name: Atom = cache_name.clone();
809
810        let reference_id = self.generate_server_reference_id(
811            &ModuleExportName::Ident(export_name.clone().into()),
812            true,
813            Some(&new_params),
814        );
815
816        self.has_cache = true;
817        self.reference_ids_by_export_name.insert(
818            ModuleExportName::Ident(export_name.clone().into()),
819            reference_id.clone(),
820        );
821
822        // If this is an exported arrow, remove it from export_name_by_local_id so the
823        // post-pass doesn't register it again (it's already registered above).
824        if self.current_export_name.is_some()
825            && let Some(arrow_ident) = &self.arrow_or_fn_expr_ident
826        {
827            self.export_name_by_local_id
828                .swap_remove(&arrow_ident.to_id());
829        }
830
831        if let BlockStmtOrExpr::BlockStmt(block) = &mut *arrow.body {
832            block.visit_mut_with(&mut ClosureReplacer {
833                used_ids: &ids_from_closure,
834                private_ctxt: self.private_ctxt,
835            });
836        }
837
838        let inner_fn_body = match *arrow.body.take() {
839            BlockStmtOrExpr::BlockStmt(body) => Some(body),
840            BlockStmtOrExpr::Expr(expr) => Some(BlockStmt {
841                stmts: vec![Stmt::Return(ReturnStmt {
842                    span: DUMMY_SP,
843                    arg: Some(expr),
844                })],
845                ..Default::default()
846            }),
847        };
848
849        let cache_ident = create_and_hoist_cache_function(
850            cache_kind.as_str(),
851            reference_id.clone(),
852            ids_from_closure.len(),
853            cache_name,
854            self.arrow_or_fn_expr_ident.clone(),
855            new_params.clone(),
856            inner_fn_body,
857            arrow.span,
858            &mut self.hoisted_extra_items,
859            self.unresolved_ctxt,
860        );
861
862        if let Some(Ident { sym, .. }) = &self.arrow_or_fn_expr_ident {
863            self.hoisted_extra_items
864                .push(ModuleItem::Stmt(assign_name_to_ident(
865                    &cache_ident,
866                    sym.as_str(),
867                    self.unresolved_ctxt,
868                )));
869        }
870
871        let bound_args: Vec<_> = ids_from_closure
872            .iter()
873            .cloned()
874            .map(|id| Some(id.as_arg()))
875            .collect();
876
877        if bound_args.is_empty() {
878            Box::new(cache_ident.clone().into())
879        } else {
880            self.has_server_reference_with_bound_args = true;
881            Box::new(bind_args_to_ident(
882                cache_ident.clone(),
883                bound_args,
884                reference_id.clone(),
885            ))
886        }
887    }
888
889    fn maybe_hoist_and_create_proxy_for_cache_function(
890        &mut self,
891        ids_from_closure: Vec<Name>,
892        fn_name: Option<Ident>,
893        cache_kind: RcStr,
894        function: &mut Function,
895    ) -> Box<Expr> {
896        let mut new_params: Vec<Param> = vec![];
897
898        // Add the collected closure variables as the first parameter to the
899        // function. They are unencrypted and passed into this function by the
900        // cache wrapper.
901        if !ids_from_closure.is_empty() {
902            new_params.push(Param {
903                span: DUMMY_SP,
904                decorators: vec![],
905                pat: self.create_bound_action_args_array_pat(ids_from_closure.len()),
906            });
907        }
908
909        for p in function.params.iter() {
910            new_params.push(p.clone());
911        }
912
913        let cache_name: Atom = self.gen_cache_ident();
914
915        let reference_id = self.generate_server_reference_id(
916            &ModuleExportName::Ident(cache_name.clone().into()),
917            true,
918            Some(&new_params),
919        );
920
921        self.has_cache = true;
922        self.reference_ids_by_export_name.insert(
923            ModuleExportName::Ident(cache_name.clone().into()),
924            reference_id.clone(),
925        );
926
927        // If this is an exported function, remove it from export_name_by_local_id so the
928        // post-pass doesn't register it again (it's already registered above).
929        if self.current_export_name.is_some()
930            && let Some(ref fn_name) = fn_name
931        {
932            self.export_name_by_local_id.swap_remove(&fn_name.to_id());
933        }
934
935        function.body.visit_mut_with(&mut ClosureReplacer {
936            used_ids: &ids_from_closure,
937            private_ctxt: self.private_ctxt,
938        });
939
940        let function_body = function.body.take();
941        let function_span = function.span;
942
943        let cache_ident = create_and_hoist_cache_function(
944            cache_kind.as_str(),
945            reference_id.clone(),
946            ids_from_closure.len(),
947            cache_name,
948            fn_name.clone(),
949            new_params.clone(),
950            function_body,
951            function_span,
952            &mut self.hoisted_extra_items,
953            self.unresolved_ctxt,
954        );
955
956        if let Some(Ident { ref sym, .. }) = fn_name {
957            self.hoisted_extra_items
958                .push(ModuleItem::Stmt(assign_name_to_ident(
959                    &cache_ident,
960                    sym.as_str(),
961                    self.unresolved_ctxt,
962                )));
963        } else if self.is_default_export() {
964            self.hoisted_extra_items
965                .push(ModuleItem::Stmt(assign_name_to_ident(
966                    &cache_ident,
967                    "default",
968                    self.unresolved_ctxt,
969                )));
970        }
971
972        let bound_args: Vec<_> = ids_from_closure
973            .iter()
974            .cloned()
975            .map(|id| Some(id.as_arg()))
976            .collect();
977
978        if bound_args.is_empty() {
979            Box::new(cache_ident.clone().into())
980        } else {
981            self.has_server_reference_with_bound_args = true;
982            Box::new(bind_args_to_ident(
983                cache_ident.clone(),
984                bound_args,
985                reference_id.clone(),
986            ))
987        }
988    }
989
990    /// Validates that a function is async, emitting an error if not.
991    /// Returns true if async, false otherwise.
992    fn validate_async_function(
993        &self,
994        is_async: bool,
995        span: Span,
996        fn_name: Option<&Ident>,
997        directive: &Directive,
998    ) -> bool {
999        if is_async {
1000            true
1001        } else {
1002            emit_error(ServerActionsErrorKind::InlineSyncFunction {
1003                span: fn_name.as_ref().map_or(span, |ident| ident.span),
1004                directive: directive.clone(),
1005            });
1006            false
1007        }
1008    }
1009
1010    /// Registers a server action export (for a 'use server' file directive).
1011    fn register_server_action_export(
1012        &mut self,
1013        export_name: &ModuleExportName,
1014        fn_name: Option<&Ident>,
1015        params: Option<&Vec<Param>>,
1016        span: Span,
1017        take_fn_or_arrow_expr: &mut dyn FnMut() -> Box<Expr>,
1018    ) {
1019        if let Some(fn_name) = fn_name {
1020            let reference_id = self.generate_server_reference_id(export_name, false, params);
1021
1022            self.has_action = true;
1023            self.reference_ids_by_export_name
1024                .insert(export_name.clone(), reference_id.clone());
1025
1026            self.server_reference_exports.push(ServerReferenceExport {
1027                ident: fn_name.clone(),
1028                export_name: export_name.clone(),
1029                reference_id: reference_id.clone(),
1030                needs_cache_runtime_wrapper: false,
1031            });
1032        } else if self.is_default_export() {
1033            let action_ident = Ident::new(self.gen_action_ident(), span, self.private_ctxt);
1034            let reference_id = self.generate_server_reference_id(export_name, false, params);
1035
1036            self.has_action = true;
1037            self.reference_ids_by_export_name
1038                .insert(export_name.clone(), reference_id.clone());
1039
1040            self.server_reference_exports.push(ServerReferenceExport {
1041                ident: action_ident.clone(),
1042                export_name: export_name.clone(),
1043                reference_id: reference_id.clone(),
1044                needs_cache_runtime_wrapper: false,
1045            });
1046
1047            // For the server layer, also hoist the function and rewrite the default export.
1048            if self.config.is_react_server_layer {
1049                self.hoisted_extra_items
1050                    .push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
1051                        kind: VarDeclKind::Const,
1052                        decls: vec![VarDeclarator {
1053                            span: DUMMY_SP,
1054                            name: Pat::Ident(action_ident.clone().into()),
1055                            init: Some(take_fn_or_arrow_expr()),
1056                            definite: false,
1057                        }],
1058                        ..Default::default()
1059                    })))));
1060
1061                self.hoisted_extra_items
1062                    .push(ModuleItem::Stmt(assign_name_to_ident(
1063                        &action_ident,
1064                        "default",
1065                        self.unresolved_ctxt,
1066                    )));
1067
1068                self.rewrite_default_fn_expr_to_proxy_expr =
1069                    Some(Box::new(Expr::Ident(action_ident)));
1070            }
1071        }
1072    }
1073
1074    /// Registers a cache export for the client layer (for 'use cache' directive).
1075    fn register_cache_export_on_client(
1076        &mut self,
1077        export_name: &ModuleExportName,
1078        fn_name: Option<&Ident>,
1079        params: Option<&Vec<Param>>,
1080        span: Span,
1081    ) {
1082        if let Some(fn_name) = fn_name {
1083            let reference_id = self.generate_server_reference_id(export_name, true, params);
1084
1085            self.has_cache = true;
1086            self.reference_ids_by_export_name
1087                .insert(export_name.clone(), reference_id.clone());
1088
1089            self.server_reference_exports.push(ServerReferenceExport {
1090                ident: fn_name.clone(),
1091                export_name: export_name.clone(),
1092                reference_id: reference_id.clone(),
1093                needs_cache_runtime_wrapper: false,
1094            });
1095        } else if self.is_default_export() {
1096            let cache_ident = Ident::new(self.gen_cache_ident(), span, self.private_ctxt);
1097            let reference_id = self.generate_server_reference_id(export_name, true, params);
1098
1099            self.has_cache = true;
1100            self.reference_ids_by_export_name
1101                .insert(export_name.clone(), reference_id.clone());
1102
1103            self.server_reference_exports.push(ServerReferenceExport {
1104                ident: cache_ident.clone(),
1105                export_name: export_name.clone(),
1106                reference_id: reference_id.clone(),
1107                needs_cache_runtime_wrapper: false,
1108            });
1109        }
1110    }
1111}
1112
1113impl<C: Comments> VisitMut for ServerActions<C> {
1114    fn visit_mut_export_decl(&mut self, decl: &mut ExportDecl) {
1115        // For inline exports like `export function foo() {}` or `export const bar = ...`,
1116        // the export name is looked up from export_name_by_local_id and set as current_export_name
1117        // in visit_mut_fn_decl or visit_mut_var_declarator.
1118        decl.decl.visit_mut_with(self);
1119    }
1120
1121    fn visit_mut_export_default_decl(&mut self, decl: &mut ExportDefaultDecl) {
1122        let old_current_export_name = self.current_export_name.take();
1123        self.current_export_name = Some(ModuleExportName::Ident(atom!("default").into()));
1124        self.rewrite_default_fn_expr_to_proxy_expr = None;
1125        decl.decl.visit_mut_with(self);
1126        self.current_export_name = old_current_export_name;
1127    }
1128
1129    fn visit_mut_export_default_expr(&mut self, expr: &mut ExportDefaultExpr) {
1130        let old_current_export_name = self.current_export_name.take();
1131        self.current_export_name = Some(ModuleExportName::Ident(atom!("default").into()));
1132        expr.expr.visit_mut_with(self);
1133        self.current_export_name = old_current_export_name;
1134
1135        // For 'use server' or 'use cache' files with call expressions as default exports,
1136        // hoist the call expression to a const declarator.
1137        if matches!(&*expr.expr, Expr::Call(_)) {
1138            if matches!(self.file_directive, Some(Directive::UseServer)) {
1139                let export_name = ModuleExportName::Ident(atom!("default").into());
1140                let action_ident =
1141                    Ident::new(self.gen_action_ident(), expr.span, self.private_ctxt);
1142                let action_id = self.generate_server_reference_id(&export_name, false, None);
1143
1144                self.has_action = true;
1145                self.reference_ids_by_export_name
1146                    .insert(export_name.clone(), action_id.clone());
1147
1148                self.server_reference_exports.push(ServerReferenceExport {
1149                    ident: action_ident.clone(),
1150                    export_name: export_name.clone(),
1151                    reference_id: action_id.clone(),
1152                    needs_cache_runtime_wrapper: false,
1153                });
1154
1155                self.hoisted_extra_items
1156                    .push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
1157                        kind: VarDeclKind::Const,
1158                        decls: vec![VarDeclarator {
1159                            span: DUMMY_SP,
1160                            name: Pat::Ident(action_ident.clone().into()),
1161                            init: Some(expr.expr.take()),
1162                            definite: false,
1163                        }],
1164                        ..Default::default()
1165                    })))));
1166
1167                self.rewrite_default_fn_expr_to_proxy_expr =
1168                    Some(Box::new(Expr::Ident(action_ident)));
1169            } else if matches!(self.file_directive, Some(Directive::UseCache { .. })) {
1170                let cache_ident = Ident::new(self.gen_cache_ident(), expr.span, self.private_ctxt);
1171
1172                self.export_name_by_local_id.insert(
1173                    cache_ident.to_id(),
1174                    ModuleExportName::Ident(atom!("default").into()),
1175                );
1176
1177                self.local_ids_that_need_cache_runtime_wrapper_if_exported
1178                    .insert(cache_ident.to_id());
1179
1180                self.hoisted_extra_items
1181                    .push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
1182                        kind: VarDeclKind::Const,
1183                        decls: vec![VarDeclarator {
1184                            span: DUMMY_SP,
1185                            name: Pat::Ident(cache_ident.into()),
1186                            init: Some(expr.expr.take()),
1187                            definite: false,
1188                        }],
1189                        ..Default::default()
1190                    })))));
1191
1192                // Note: We don't set rewrite_default_fn_expr_to_proxy_expr here. The export will be
1193                // removed via the should_remove_statement flag in the main pass.
1194            }
1195        }
1196    }
1197
1198    fn visit_mut_fn_expr(&mut self, f: &mut FnExpr) {
1199        let old_this_status = replace(&mut self.this_status, ThisStatus::Allowed);
1200        let old_arrow_or_fn_expr_ident = self.arrow_or_fn_expr_ident.clone();
1201        if let Some(ident) = &f.ident {
1202            self.arrow_or_fn_expr_ident = Some(ident.clone());
1203        }
1204        f.visit_mut_children_with(self);
1205        self.this_status = old_this_status;
1206        self.arrow_or_fn_expr_ident = old_arrow_or_fn_expr_ident;
1207    }
1208
1209    fn visit_mut_function(&mut self, f: &mut Function) {
1210        let directive = self.get_directive_for_function(f.body.as_mut());
1211        let declared_idents_until = self.declared_idents.len();
1212        let old_names = take(&mut self.names);
1213
1214        if let Some(directive) = &directive {
1215            self.this_status = ThisStatus::Forbidden {
1216                directive: directive.clone(),
1217            };
1218        }
1219
1220        // Visit children
1221        {
1222            let old_in_module = replace(&mut self.in_module_level, false);
1223            let should_track_names = directive.is_some() || self.should_track_names;
1224            let old_should_track_names = replace(&mut self.should_track_names, should_track_names);
1225            let old_current_export_name = self.current_export_name.take();
1226            let old_fn_decl_ident = self.fn_decl_ident.take();
1227            f.visit_mut_children_with(self);
1228            self.in_module_level = old_in_module;
1229            self.should_track_names = old_should_track_names;
1230            self.current_export_name = old_current_export_name;
1231            self.fn_decl_ident = old_fn_decl_ident;
1232        }
1233
1234        let mut child_names = take(&mut self.names);
1235
1236        if self.should_track_names {
1237            self.names = [old_names, child_names.clone()].concat();
1238        }
1239
1240        if let Some(directive) = directive {
1241            let fn_name = self
1242                .fn_decl_ident
1243                .as_ref()
1244                .or(self.arrow_or_fn_expr_ident.as_ref())
1245                .cloned();
1246
1247            if !self.validate_async_function(f.is_async, f.span, fn_name.as_ref(), &directive) {
1248                // If this is an exported function that failed validation, remove it from
1249                // export_name_by_local_id so the post-pass doesn't register it.
1250                if self.current_export_name.is_some()
1251                    && let Some(fn_name) = fn_name
1252                {
1253                    self.export_name_by_local_id.swap_remove(&fn_name.to_id());
1254                }
1255
1256                return;
1257            }
1258
1259            // If this function is invalid, or any prior errors have been emitted, skip further
1260            // processing.
1261            if HANDLER.with(|handler| handler.has_errors()) {
1262                return;
1263            }
1264
1265            // For server action files, register exports without hoisting (for both server and
1266            // client layers).
1267            if matches!(self.file_directive, Some(Directive::UseServer))
1268                && matches!(directive, Directive::UseServer)
1269                && let Some(export_name) = self.current_export_name.clone()
1270            {
1271                let params = f.params.clone();
1272                let span = f.span;
1273
1274                self.register_server_action_export(
1275                    &export_name,
1276                    fn_name.as_ref(),
1277                    Some(&params),
1278                    span,
1279                    &mut || {
1280                        Box::new(Expr::Fn(FnExpr {
1281                            ident: fn_name.clone(),
1282                            function: Box::new(f.take()),
1283                        }))
1284                    },
1285                );
1286
1287                return;
1288            }
1289
1290            // For the client layer, register cache exports without hoisting.
1291            if !self.config.is_react_server_layer {
1292                if matches!(directive, Directive::UseCache { .. })
1293                    && let Some(export_name) = self.current_export_name.clone()
1294                {
1295                    self.register_cache_export_on_client(
1296                        &export_name,
1297                        fn_name.as_ref(),
1298                        Some(&f.params),
1299                        f.span,
1300                    );
1301                }
1302
1303                return;
1304            }
1305
1306            if let Directive::UseCache { cache_kind } = directive {
1307                // Collect all the identifiers defined inside the closure and used
1308                // in the cache function. With deduplication.
1309                retain_names_from_declared_idents(
1310                    &mut child_names,
1311                    &self.declared_idents[..declared_idents_until],
1312                );
1313
1314                let new_expr = self.maybe_hoist_and_create_proxy_for_cache_function(
1315                    child_names.clone(),
1316                    self.fn_decl_ident
1317                        .as_ref()
1318                        .or(self.arrow_or_fn_expr_ident.as_ref())
1319                        .cloned(),
1320                    cache_kind,
1321                    f,
1322                );
1323
1324                if self.is_default_export() {
1325                    // This function expression is also the default export:
1326                    // `export default async function() {}`
1327                    // This specific case (default export) isn't handled by `visit_mut_expr`.
1328                    // Replace the original function expr with a action proxy expr.
1329                    self.rewrite_default_fn_expr_to_proxy_expr = Some(new_expr);
1330                } else if let Some(ident) = &self.fn_decl_ident {
1331                    // Replace the original function declaration with a cache decl.
1332                    self.rewrite_fn_decl_to_proxy_decl = Some(VarDecl {
1333                        span: DUMMY_SP,
1334                        kind: VarDeclKind::Var,
1335                        decls: vec![VarDeclarator {
1336                            span: DUMMY_SP,
1337                            name: Pat::Ident(ident.clone().into()),
1338                            init: Some(new_expr),
1339                            definite: false,
1340                        }],
1341                        ..Default::default()
1342                    });
1343                } else {
1344                    self.rewrite_expr_to_proxy_expr = Some(new_expr);
1345                }
1346            } else {
1347                // Collect all the identifiers defined inside the closure and used
1348                // in the action function. With deduplication.
1349                retain_names_from_declared_idents(
1350                    &mut child_names,
1351                    &self.declared_idents[..declared_idents_until],
1352                );
1353
1354                let new_expr = self.maybe_hoist_and_create_proxy_for_server_action_function(
1355                    child_names,
1356                    f,
1357                    fn_name,
1358                );
1359
1360                if self.is_default_export() {
1361                    // This function expression is also the default export:
1362                    // `export default async function() {}`
1363                    // This specific case (default export) isn't handled by `visit_mut_expr`.
1364                    // Replace the original function expr with a action proxy expr.
1365                    self.rewrite_default_fn_expr_to_proxy_expr = Some(new_expr);
1366                } else if let Some(ident) = &self.fn_decl_ident {
1367                    // Replace the original function declaration with an action proxy
1368                    // declaration expr.
1369                    self.rewrite_fn_decl_to_proxy_decl = Some(VarDecl {
1370                        span: DUMMY_SP,
1371                        kind: VarDeclKind::Var,
1372                        decls: vec![VarDeclarator {
1373                            span: DUMMY_SP,
1374                            name: Pat::Ident(ident.clone().into()),
1375                            init: Some(new_expr),
1376                            definite: false,
1377                        }],
1378                        ..Default::default()
1379                    });
1380                } else {
1381                    self.rewrite_expr_to_proxy_expr = Some(new_expr);
1382                }
1383            }
1384        }
1385    }
1386
1387    fn visit_mut_decl(&mut self, d: &mut Decl) {
1388        self.rewrite_fn_decl_to_proxy_decl = None;
1389        d.visit_mut_children_with(self);
1390
1391        if let Some(decl) = &self.rewrite_fn_decl_to_proxy_decl {
1392            *d = (*decl).clone().into();
1393        }
1394
1395        self.rewrite_fn_decl_to_proxy_decl = None;
1396    }
1397
1398    fn visit_mut_fn_decl(&mut self, f: &mut FnDecl) {
1399        let old_this_status = replace(&mut self.this_status, ThisStatus::Allowed);
1400        let old_current_export_name = self.current_export_name.take();
1401        if self.in_module_level
1402            && let Some(export_name) = self.export_name_by_local_id.get(&f.ident.to_id())
1403        {
1404            self.current_export_name = Some(export_name.clone());
1405        }
1406        let old_fn_decl_ident = self.fn_decl_ident.replace(f.ident.clone());
1407        f.visit_mut_children_with(self);
1408        self.this_status = old_this_status;
1409        self.current_export_name = old_current_export_name;
1410        self.fn_decl_ident = old_fn_decl_ident;
1411    }
1412
1413    fn visit_mut_arrow_expr(&mut self, a: &mut ArrowExpr) {
1414        // Arrow expressions need to be visited in prepass to determine if it's
1415        // an action function or not.
1416        let directive = self.get_directive_for_function(
1417            if let BlockStmtOrExpr::BlockStmt(block) = &mut *a.body {
1418                Some(block)
1419            } else {
1420                None
1421            },
1422        );
1423
1424        if let Some(directive) = &directive {
1425            self.this_status = ThisStatus::Forbidden {
1426                directive: directive.clone(),
1427            };
1428        }
1429
1430        let declared_idents_until = self.declared_idents.len();
1431        let old_names = take(&mut self.names);
1432
1433        {
1434            // Visit children
1435            let old_in_module = replace(&mut self.in_module_level, false);
1436            let should_track_names = directive.is_some() || self.should_track_names;
1437            let old_should_track_names = replace(&mut self.should_track_names, should_track_names);
1438            let old_current_export_name = self.current_export_name.take();
1439            {
1440                for n in &mut a.params {
1441                    collect_idents_in_pat(n, &mut self.declared_idents);
1442                }
1443            }
1444            a.visit_mut_children_with(self);
1445            self.in_module_level = old_in_module;
1446            self.should_track_names = old_should_track_names;
1447            self.current_export_name = old_current_export_name;
1448        }
1449
1450        let mut child_names = take(&mut self.names);
1451
1452        if self.should_track_names {
1453            self.names = [old_names, child_names.clone()].concat();
1454        }
1455
1456        if let Some(directive) = directive {
1457            let arrow_ident = self.arrow_or_fn_expr_ident.clone();
1458
1459            if !self.validate_async_function(a.is_async, a.span, arrow_ident.as_ref(), &directive) {
1460                // If this is an exported arrow function that failed validation, remove it from
1461                // export_name_by_local_id so the post-pass doesn't register it.
1462                if self.current_export_name.is_some()
1463                    && let Some(arrow_ident) = arrow_ident
1464                {
1465                    self.export_name_by_local_id
1466                        .swap_remove(&arrow_ident.to_id());
1467                }
1468
1469                return;
1470            }
1471
1472            // If this function is invalid, or any prior errors have been emitted, skip further
1473            // processing.
1474            if HANDLER.with(|handler| handler.has_errors()) {
1475                return;
1476            }
1477
1478            // For server action files, register exports without hoisting (for both server and
1479            // client layers).
1480            if matches!(self.file_directive, Some(Directive::UseServer))
1481                && matches!(directive, Directive::UseServer)
1482                && let Some(export_name) = self.current_export_name.clone()
1483            {
1484                let params: Vec<Param> = a.params.iter().map(|p| Param::from(p.clone())).collect();
1485
1486                self.register_server_action_export(
1487                    &export_name,
1488                    arrow_ident.as_ref(),
1489                    Some(&params),
1490                    a.span,
1491                    &mut || Box::new(Expr::Arrow(a.take())),
1492                );
1493
1494                return;
1495            }
1496
1497            // For the client layer, register cache exports without hoisting.
1498            if !self.config.is_react_server_layer {
1499                if matches!(directive, Directive::UseCache { .. })
1500                    && let Some(export_name) = self.current_export_name.clone()
1501                {
1502                    let params: Vec<Param> =
1503                        a.params.iter().map(|p| Param::from(p.clone())).collect();
1504
1505                    self.register_cache_export_on_client(
1506                        &export_name,
1507                        arrow_ident.as_ref(),
1508                        Some(&params),
1509                        a.span,
1510                    );
1511                }
1512
1513                return;
1514            }
1515
1516            // Collect all the identifiers defined inside the closure and used
1517            // in the action function. With deduplication.
1518            retain_names_from_declared_idents(
1519                &mut child_names,
1520                &self.declared_idents[..declared_idents_until],
1521            );
1522
1523            if let Directive::UseCache { cache_kind } = directive {
1524                self.rewrite_expr_to_proxy_expr =
1525                    Some(self.maybe_hoist_and_create_proxy_for_cache_arrow_expr(
1526                        child_names,
1527                        cache_kind,
1528                        a,
1529                    ));
1530            } else {
1531                self.rewrite_expr_to_proxy_expr = Some(
1532                    self.maybe_hoist_and_create_proxy_for_server_action_arrow_expr(child_names, a),
1533                );
1534            }
1535        }
1536    }
1537
1538    fn visit_mut_module(&mut self, m: &mut Module) {
1539        self.start_pos = m.span.lo;
1540        m.visit_mut_children_with(self);
1541    }
1542
1543    fn visit_mut_stmt(&mut self, n: &mut Stmt) {
1544        n.visit_mut_children_with(self);
1545
1546        if self.in_module_level {
1547            return;
1548        }
1549
1550        // If it's a closure (not in the module level), we need to collect
1551        // identifiers defined in the closure.
1552        collect_decl_idents_in_stmt(n, &mut self.declared_idents);
1553    }
1554
1555    fn visit_mut_param(&mut self, n: &mut Param) {
1556        n.visit_mut_children_with(self);
1557
1558        if self.in_module_level {
1559            return;
1560        }
1561
1562        collect_idents_in_pat(&n.pat, &mut self.declared_idents);
1563    }
1564
1565    fn visit_mut_prop_or_spread(&mut self, n: &mut PropOrSpread) {
1566        let old_arrow_or_fn_expr_ident = self.arrow_or_fn_expr_ident.clone();
1567        let old_current_export_name = self.current_export_name.take();
1568
1569        match n {
1570            PropOrSpread::Prop(box Prop::KeyValue(KeyValueProp {
1571                key: PropName::Ident(ident_name),
1572                value: box Expr::Arrow(_) | box Expr::Fn(_),
1573                ..
1574            })) => {
1575                self.current_export_name = None;
1576                self.arrow_or_fn_expr_ident = Some(ident_name.clone().into());
1577            }
1578            PropOrSpread::Prop(box Prop::Method(MethodProp { key, .. })) => {
1579                let key = key.clone();
1580
1581                if let PropName::Ident(ident_name) = &key {
1582                    self.arrow_or_fn_expr_ident = Some(ident_name.clone().into());
1583                }
1584
1585                let old_this_status = replace(&mut self.this_status, ThisStatus::Allowed);
1586                self.rewrite_expr_to_proxy_expr = None;
1587                self.current_export_name = None;
1588                n.visit_mut_children_with(self);
1589                self.current_export_name = old_current_export_name.clone();
1590                self.this_status = old_this_status;
1591
1592                if let Some(expr) = self.rewrite_expr_to_proxy_expr.take() {
1593                    *n = PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
1594                        key,
1595                        value: expr,
1596                    })));
1597                }
1598
1599                return;
1600            }
1601            _ => {}
1602        }
1603
1604        if !self.in_module_level
1605            && self.should_track_names
1606            && let PropOrSpread::Prop(box Prop::Shorthand(i)) = n
1607        {
1608            self.names.push(Name::from(&*i));
1609            self.should_track_names = false;
1610            n.visit_mut_children_with(self);
1611            self.should_track_names = true;
1612            return;
1613        }
1614
1615        n.visit_mut_children_with(self);
1616        self.arrow_or_fn_expr_ident = old_arrow_or_fn_expr_ident;
1617        self.current_export_name = old_current_export_name;
1618    }
1619
1620    fn visit_mut_class(&mut self, n: &mut Class) {
1621        let old_this_status = replace(&mut self.this_status, ThisStatus::Allowed);
1622        n.visit_mut_children_with(self);
1623        self.this_status = old_this_status;
1624    }
1625
1626    fn visit_mut_class_member(&mut self, n: &mut ClassMember) {
1627        if let ClassMember::Method(ClassMethod {
1628            is_abstract: false,
1629            is_static: true,
1630            kind: MethodKind::Method,
1631            key,
1632            span,
1633            accessibility: None | Some(Accessibility::Public),
1634            ..
1635        }) = n
1636        {
1637            let key = key.clone();
1638            let span = *span;
1639            let old_arrow_or_fn_expr_ident = self.arrow_or_fn_expr_ident.clone();
1640
1641            if let PropName::Ident(ident_name) = &key {
1642                self.arrow_or_fn_expr_ident = Some(ident_name.clone().into());
1643            }
1644
1645            let old_this_status = replace(&mut self.this_status, ThisStatus::Allowed);
1646            let old_current_export_name = self.current_export_name.take();
1647            self.rewrite_expr_to_proxy_expr = None;
1648            self.current_export_name = None;
1649            n.visit_mut_children_with(self);
1650            self.this_status = old_this_status;
1651            self.current_export_name = old_current_export_name;
1652            self.arrow_or_fn_expr_ident = old_arrow_or_fn_expr_ident;
1653
1654            if let Some(expr) = self.rewrite_expr_to_proxy_expr.take() {
1655                *n = ClassMember::ClassProp(ClassProp {
1656                    span,
1657                    key,
1658                    value: Some(expr),
1659                    is_static: true,
1660                    ..Default::default()
1661                });
1662            }
1663        } else {
1664            n.visit_mut_children_with(self);
1665        }
1666    }
1667
1668    fn visit_mut_class_method(&mut self, n: &mut ClassMethod) {
1669        if n.is_static {
1670            n.visit_mut_children_with(self);
1671        } else {
1672            let (is_action_fn, is_cache_fn) = has_body_directive(&n.function.body);
1673
1674            if is_action_fn {
1675                emit_error(
1676                    ServerActionsErrorKind::InlineUseServerInClassInstanceMethod { span: n.span },
1677                );
1678            } else if is_cache_fn {
1679                emit_error(
1680                    ServerActionsErrorKind::InlineUseCacheInClassInstanceMethod { span: n.span },
1681                );
1682            } else {
1683                n.visit_mut_children_with(self);
1684            }
1685        }
1686    }
1687
1688    fn visit_mut_call_expr(&mut self, n: &mut CallExpr) {
1689        if let Callee::Expr(box Expr::Ident(Ident { sym, .. })) = &mut n.callee
1690            && (sym == "jsxDEV" || sym == "_jsxDEV")
1691        {
1692            // Do not visit the 6th arg in a generated jsxDEV call, which is a `this`
1693            // expression, to avoid emitting an error for using `this` if it's
1694            // inside of a server function. https://github.com/facebook/react/blob/9106107/packages/react/src/jsx/ReactJSXElement.js#L429
1695            if n.args.len() > 4 {
1696                for arg in &mut n.args[0..4] {
1697                    arg.visit_mut_with(self);
1698                }
1699                return;
1700            }
1701        }
1702
1703        let old_current_export_name = self.current_export_name.take();
1704        n.visit_mut_children_with(self);
1705        self.current_export_name = old_current_export_name;
1706    }
1707
1708    fn visit_mut_callee(&mut self, n: &mut Callee) {
1709        let old_in_callee = replace(&mut self.in_callee, true);
1710        n.visit_mut_children_with(self);
1711        self.in_callee = old_in_callee;
1712    }
1713
1714    fn visit_mut_expr(&mut self, n: &mut Expr) {
1715        if !self.in_module_level
1716            && self.should_track_names
1717            && let Ok(mut name) = Name::try_from(&*n)
1718        {
1719            if self.in_callee {
1720                // This is a callee i.e. `foo.bar()`,
1721                // we need to track the actual value instead of the method name.
1722                if !name.1.is_empty() {
1723                    name.1.pop();
1724                }
1725            }
1726
1727            self.names.push(name);
1728            self.should_track_names = false;
1729            n.visit_mut_children_with(self);
1730            self.should_track_names = true;
1731            return;
1732        }
1733
1734        self.rewrite_expr_to_proxy_expr = None;
1735        n.visit_mut_children_with(self);
1736        if let Some(expr) = self.rewrite_expr_to_proxy_expr.take() {
1737            *n = *expr;
1738        }
1739    }
1740
1741    fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) {
1742        self.file_directive = self.get_directive_for_module(stmts);
1743
1744        let in_cache_file = matches!(self.file_directive, Some(Directive::UseCache { .. }));
1745        let in_action_file = matches!(self.file_directive, Some(Directive::UseServer));
1746
1747        // Only track exported identifiers in server action files or cache files.
1748        let should_track_exports = in_action_file || in_cache_file;
1749
1750        // Pre-pass: Collect a mapping from local identifiers to export names for all exports
1751        // in server boundary files ('use server' or 'use cache'). This mapping is used to:
1752        // 1. Set current_export_name when visiting exported functions/variables during the main
1753        //    pass.
1754        // 2. Register any remaining exports in the post-pass that weren't handled by the visitor.
1755        if should_track_exports {
1756            for stmt in stmts.iter() {
1757                match stmt {
1758                    ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(export_default_expr)) => {
1759                        if let Expr::Ident(ident) = &*export_default_expr.expr {
1760                            self.export_name_by_local_id.insert(
1761                                ident.to_id(),
1762                                ModuleExportName::Ident(atom!("default").into()),
1763                            );
1764                        }
1765                    }
1766                    ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export_default_decl)) => {
1767                        // export default function foo() {}
1768                        if let DefaultDecl::Fn(f) = &export_default_decl.decl
1769                            && let Some(ident) = &f.ident
1770                        {
1771                            self.export_name_by_local_id.insert(
1772                                ident.to_id(),
1773                                ModuleExportName::Ident(atom!("default").into()),
1774                            );
1775                        }
1776                    }
1777                    ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) => {
1778                        // export function foo() {} or export const bar = ...
1779                        match &export_decl.decl {
1780                            Decl::Fn(f) => {
1781                                self.export_name_by_local_id.insert(
1782                                    f.ident.to_id(),
1783                                    ModuleExportName::Ident(f.ident.clone()),
1784                                );
1785                            }
1786                            Decl::Var(var) => {
1787                                for decl in &var.decls {
1788                                    // Collect all identifiers from the pattern and track which may
1789                                    // need cache runtime wrappers. For destructuring patterns, we
1790                                    // always need wrappers since we can't statically know if the
1791                                    // destructured values are functions. For simple identifiers,
1792                                    // check the init expression.
1793                                    let mut idents = vec![];
1794                                    collect_idents_in_pat(&decl.name, &mut idents);
1795
1796                                    let is_destructuring = !matches!(&decl.name, Pat::Ident(_));
1797                                    let needs_wrapper = if is_destructuring {
1798                                        true
1799                                    } else if let Some(init) = &decl.init {
1800                                        may_need_cache_runtime_wrapper(init)
1801                                    } else {
1802                                        false
1803                                    };
1804
1805                                    for ident in idents {
1806                                        self.export_name_by_local_id.insert(
1807                                            ident.to_id(),
1808                                            ModuleExportName::Ident(ident.clone()),
1809                                        );
1810
1811                                        if needs_wrapper {
1812                                            self.local_ids_that_need_cache_runtime_wrapper_if_exported
1813                                                .insert(ident.to_id());
1814                                        }
1815                                    }
1816                                }
1817                            }
1818                            _ => {}
1819                        }
1820                    }
1821                    ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(named_export))
1822                        if named_export.src.is_none() && !named_export.type_only =>
1823                    {
1824                        for spec in &named_export.specifiers {
1825                            match spec {
1826                                ExportSpecifier::Named(ExportNamedSpecifier {
1827                                    orig: ModuleExportName::Ident(orig),
1828                                    exported: Some(exported),
1829                                    is_type_only: false,
1830                                    ..
1831                                }) => {
1832                                    // export { foo as bar } or export { foo as "📙" }
1833                                    self.export_name_by_local_id
1834                                        .insert(orig.to_id(), exported.clone());
1835                                }
1836                                ExportSpecifier::Named(ExportNamedSpecifier {
1837                                    orig: ModuleExportName::Ident(orig),
1838                                    exported: None,
1839                                    is_type_only: false,
1840                                    ..
1841                                }) => {
1842                                    // export { foo }
1843                                    self.export_name_by_local_id.insert(
1844                                        orig.to_id(),
1845                                        ModuleExportName::Ident(orig.clone()),
1846                                    );
1847                                }
1848                                _ => {}
1849                            }
1850                        }
1851                    }
1852                    ModuleItem::Stmt(Stmt::Decl(Decl::Var(var_decl))) => {
1853                        // Track which declarations need cache runtime wrappers if exported.
1854                        for decl in &var_decl.decls {
1855                            if let Pat::Ident(ident_pat) = &decl.name
1856                                && let Some(init) = &decl.init
1857                                && may_need_cache_runtime_wrapper(init)
1858                            {
1859                                self.local_ids_that_need_cache_runtime_wrapper_if_exported
1860                                    .insert(ident_pat.id.to_id());
1861                            }
1862                        }
1863                    }
1864                    ModuleItem::Stmt(Stmt::Decl(Decl::Fn(_fn_decl))) => {
1865                        // Function declarations are known functions and don't need runtime
1866                        // wrappers.
1867                    }
1868                    ModuleItem::ModuleDecl(ModuleDecl::Import(import_decl)) => {
1869                        // Track all imports. We don't know if they're functions, so they need
1870                        // runtime wrappers if they end up getting re-exported.
1871                        for spec in &import_decl.specifiers {
1872                            match spec {
1873                                ImportSpecifier::Named(named) => {
1874                                    self.local_ids_that_need_cache_runtime_wrapper_if_exported
1875                                        .insert(named.local.to_id());
1876                                }
1877                                ImportSpecifier::Default(default) => {
1878                                    self.local_ids_that_need_cache_runtime_wrapper_if_exported
1879                                        .insert(default.local.to_id());
1880                                }
1881                                ImportSpecifier::Namespace(ns) => {
1882                                    self.local_ids_that_need_cache_runtime_wrapper_if_exported
1883                                        .insert(ns.local.to_id());
1884                                }
1885                            }
1886                        }
1887                    }
1888                    _ => {}
1889                }
1890            }
1891        }
1892
1893        let old_annotations = self.annotations.take();
1894        let mut new = Vec::with_capacity(stmts.len());
1895
1896        // Main pass: For each statement, validate exports in server boundary files,
1897        // visit and transform it, and add it to the output along with any hoisted items.
1898        for mut stmt in stmts.take() {
1899            let mut should_remove_statement = false;
1900
1901            if should_track_exports {
1902                let mut disallowed_export_span = DUMMY_SP;
1903
1904                match &mut stmt {
1905                    ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl, span })) => {
1906                        match decl {
1907                            Decl::Var(var) => {
1908                                let mut has_export_needing_wrapper = false;
1909
1910                                for decl in &var.decls {
1911                                    if let Pat::Ident(_) = &decl.name
1912                                        && let Some(init) = &decl.init
1913                                    {
1914                                        // Disallow exporting literals. Admittedly, this is
1915                                        // pretty arbitrary. We don't disallow exporting object
1916                                        // and array literals, as that would be too restrictive,
1917                                        // especially for page and layout files with
1918                                        // 'use cache', that may want to export metadata or
1919                                        // viewport objects.
1920                                        if let Expr::Lit(_) = &**init {
1921                                            disallowed_export_span = *span;
1922                                        }
1923                                    }
1924
1925                                    // For cache files, check if any identifier needs a runtime
1926                                    // wrapper.
1927                                    if in_cache_file {
1928                                        let mut idents: Vec<Ident> = Vec::new();
1929                                        collect_idents_in_pat(&decl.name, &mut idents);
1930
1931                                        for ident in idents {
1932                                            let needs_cache_runtime_wrapper = self
1933                                                .local_ids_that_need_cache_runtime_wrapper_if_exported
1934                                                .contains(&ident.to_id());
1935
1936                                            if needs_cache_runtime_wrapper {
1937                                                has_export_needing_wrapper = true;
1938                                            }
1939                                        }
1940                                    }
1941                                }
1942
1943                                // If this export needs a cache runtime wrapper, convert to a
1944                                // regular declaration (remove export keyword).
1945                                if in_cache_file && has_export_needing_wrapper {
1946                                    stmt = ModuleItem::Stmt(Stmt::Decl(Decl::Var(var.clone())));
1947                                }
1948                            }
1949                            Decl::Fn(_)
1950                            | Decl::TsInterface(_)
1951                            | Decl::TsTypeAlias(_)
1952                            | Decl::TsEnum(_) => {}
1953                            _ => {
1954                                disallowed_export_span = *span;
1955                            }
1956                        }
1957                    }
1958                    ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(named)) if !named.type_only => {
1959                        if let Some(src) = &named.src {
1960                            // export { x } from './module'
1961                            if in_cache_file {
1962                                // Transform re-exports into imports so we can wrap them with
1963                                // cache runtime wrappers.
1964                                let import_specs: Vec<ImportSpecifier> = named
1965                                        .specifiers
1966                                        .iter()
1967                                        .filter_map(|spec| {
1968                                            if let ExportSpecifier::Named(ExportNamedSpecifier {
1969                                                orig: ModuleExportName::Ident(orig),
1970                                                exported,
1971                                                is_type_only: false,
1972                                                ..
1973                                            }) = spec
1974                                            {
1975                                                    // Now that we're converting this to an import,
1976                                                    // track it as a local export so the post-pass
1977                                                    // can register it.
1978                                                    let export_name =
1979                                                        if let Some(exported) = exported {
1980                                                            exported.clone()
1981                                                        } else {
1982                                                            ModuleExportName::Ident(orig.clone())
1983                                                        };
1984
1985                                                    self.export_name_by_local_id
1986                                                        .insert(orig.to_id(), export_name);
1987
1988                                                    self.local_ids_that_need_cache_runtime_wrapper_if_exported
1989                                                        .insert(orig.to_id());
1990
1991                                                    return Some(ImportSpecifier::Named(
1992                                                        ImportNamedSpecifier {
1993                                                            span: DUMMY_SP,
1994                                                            local: orig.clone(),
1995                                                            imported: None,
1996                                                            is_type_only: false,
1997                                                        },
1998                                                    ));
1999                                            }
2000                                            None
2001                                        })
2002                                        .collect();
2003
2004                                if !import_specs.is_empty() {
2005                                    // Add import statement.
2006                                    self.extra_items.push(ModuleItem::ModuleDecl(
2007                                        ModuleDecl::Import(ImportDecl {
2008                                            span: named.span,
2009                                            specifiers: import_specs,
2010                                            src: src.clone(),
2011                                            type_only: false,
2012                                            with: named.with.clone(),
2013                                            phase: Default::default(),
2014                                        }),
2015                                    ));
2016                                }
2017
2018                                // Remove value specifiers from the export statement, keeping
2019                                // only type-only specifiers.
2020                                named.specifiers.retain(|spec| {
2021                                    matches!(
2022                                        spec,
2023                                        ExportSpecifier::Named(ExportNamedSpecifier {
2024                                            is_type_only: true,
2025                                            ..
2026                                        })
2027                                    )
2028                                });
2029
2030                                // If all specifiers were value specifiers (converted to
2031                                // imports), remove the entire statement.
2032                                if named.specifiers.is_empty() {
2033                                    should_remove_statement = true;
2034                                }
2035                            } else if named.specifiers.iter().any(|s| match s {
2036                                ExportSpecifier::Namespace(_) | ExportSpecifier::Default(_) => true,
2037                                ExportSpecifier::Named(s) => !s.is_type_only,
2038                            }) {
2039                                disallowed_export_span = named.span;
2040                            }
2041                        } else {
2042                            // For cache files, remove specifiers that need cache runtime
2043                            // wrappers. Keep type-only specifiers and value specifiers that
2044                            // don't need wrappers (like function declarations).
2045                            if in_cache_file {
2046                                named.specifiers.retain(|spec| {
2047                                    if let ExportSpecifier::Named(ExportNamedSpecifier {
2048                                        orig: ModuleExportName::Ident(ident),
2049                                        is_type_only: false,
2050                                        ..
2051                                    }) = spec
2052                                    {
2053                                        !self
2054                                            .local_ids_that_need_cache_runtime_wrapper_if_exported
2055                                            .contains(&ident.to_id())
2056                                    } else {
2057                                        true
2058                                    }
2059                                });
2060
2061                                if named.specifiers.is_empty() {
2062                                    should_remove_statement = true;
2063                                }
2064                            }
2065                        }
2066                    }
2067                    ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl {
2068                        decl,
2069                        span,
2070                    })) => match decl {
2071                        DefaultDecl::Fn(_) | DefaultDecl::TsInterfaceDecl(_) => {}
2072                        _ => {
2073                            disallowed_export_span = *span;
2074                        }
2075                    },
2076                    ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(default_expr)) => {
2077                        match &mut *default_expr.expr {
2078                            Expr::Fn(_) | Expr::Arrow(_) => {}
2079                            Expr::Ident(ident) => {
2080                                // For cache files, remove the export if it needs a runtime wrapper
2081                                // (we'll generate a new export when adding the wrapper).
2082                                if in_cache_file {
2083                                    let needs_cache_runtime_wrapper = self
2084                                        .local_ids_that_need_cache_runtime_wrapper_if_exported
2085                                        .contains(&ident.to_id());
2086
2087                                    if needs_cache_runtime_wrapper {
2088                                        should_remove_statement = true;
2089                                    }
2090                                }
2091                            }
2092                            Expr::Call(_call) => {
2093                                // For cache files, mark the statement for removal. After visiting
2094                                // (which transforms nested directives), we'll hoist the call to a
2095                                // const declaration that gets a cache runtime wrapper.
2096                                if in_cache_file {
2097                                    should_remove_statement = true;
2098                                }
2099                            }
2100                            _ => {
2101                                disallowed_export_span = default_expr.span;
2102                            }
2103                        }
2104                    }
2105                    ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ExportAll {
2106                        span,
2107                        type_only,
2108                        ..
2109                    })) if !*type_only => {
2110                        disallowed_export_span = *span;
2111                    }
2112                    _ => {}
2113                }
2114
2115                // Emit validation error if we found a disallowed export
2116                if disallowed_export_span != DUMMY_SP {
2117                    emit_error(ServerActionsErrorKind::ExportedSyncFunction {
2118                        span: disallowed_export_span,
2119                        in_action_file,
2120                    });
2121                    return;
2122                }
2123            }
2124
2125            stmt.visit_mut_with(self);
2126
2127            let new_stmt = if should_remove_statement {
2128                None
2129            } else if let Some(expr) = self.rewrite_default_fn_expr_to_proxy_expr.take() {
2130                Some(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(
2131                    ExportDefaultExpr {
2132                        span: DUMMY_SP,
2133                        expr,
2134                    },
2135                )))
2136            } else {
2137                Some(stmt)
2138            };
2139
2140            if self.config.is_react_server_layer || self.file_directive.is_none() {
2141                new.append(&mut self.hoisted_extra_items);
2142                if let Some(stmt) = new_stmt {
2143                    new.push(stmt);
2144                }
2145                new.extend(self.annotations.drain(..).map(ModuleItem::Stmt));
2146                new.append(&mut self.extra_items);
2147            }
2148        }
2149
2150        // Post-pass: For server boundary files, register any exports that weren't already
2151        // registered during the main pass.
2152        if should_track_exports {
2153            for (id, export_name) in &self.export_name_by_local_id {
2154                if self.reference_ids_by_export_name.contains_key(export_name) {
2155                    continue;
2156                }
2157
2158                if in_cache_file
2159                    && !self
2160                        .local_ids_that_need_cache_runtime_wrapper_if_exported
2161                        .contains(id)
2162                {
2163                    continue;
2164                }
2165
2166                self.server_reference_exports.push(ServerReferenceExport {
2167                    ident: Ident::from(id.clone()),
2168                    export_name: export_name.clone(),
2169                    reference_id: self.generate_server_reference_id(
2170                        export_name,
2171                        in_cache_file,
2172                        None,
2173                    ),
2174                    needs_cache_runtime_wrapper: in_cache_file,
2175                });
2176            }
2177        }
2178
2179        if in_action_file || in_cache_file && !self.config.is_react_server_layer {
2180            self.reference_ids_by_export_name.extend(
2181                self.server_reference_exports
2182                    .iter()
2183                    .map(|e| (e.export_name.clone(), e.reference_id.clone())),
2184            );
2185
2186            if !self.reference_ids_by_export_name.is_empty() {
2187                self.has_action |= in_action_file;
2188                self.has_cache |= in_cache_file;
2189            }
2190        };
2191
2192        // If it's compiled in the client layer, each export field needs to be
2193        // wrapped by a reference creation call.
2194        let create_ref_ident = private_ident!("createServerReference");
2195        let call_server_ident = private_ident!("callServer");
2196        let find_source_map_url_ident = private_ident!("findSourceMapURL");
2197
2198        let client_layer_import = ((self.has_action || self.has_cache)
2199            && !self.config.is_react_server_layer)
2200            .then(|| {
2201                // import {
2202                //   createServerReference,
2203                //   callServer,
2204                //   findSourceMapURL
2205                // } from 'private-next-rsc-action-client-wrapper'
2206                // createServerReference("action_id")
2207                ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
2208                    span: DUMMY_SP,
2209                    specifiers: vec![
2210                        ImportSpecifier::Named(ImportNamedSpecifier {
2211                            span: DUMMY_SP,
2212                            local: create_ref_ident.clone(),
2213                            imported: None,
2214                            is_type_only: false,
2215                        }),
2216                        ImportSpecifier::Named(ImportNamedSpecifier {
2217                            span: DUMMY_SP,
2218                            local: call_server_ident.clone(),
2219                            imported: None,
2220                            is_type_only: false,
2221                        }),
2222                        ImportSpecifier::Named(ImportNamedSpecifier {
2223                            span: DUMMY_SP,
2224                            local: find_source_map_url_ident.clone(),
2225                            imported: None,
2226                            is_type_only: false,
2227                        }),
2228                    ],
2229                    src: Box::new(Str {
2230                        span: DUMMY_SP,
2231                        value: atom!("private-next-rsc-action-client-wrapper").into(),
2232                        raw: None,
2233                    }),
2234                    type_only: false,
2235                    with: None,
2236                    phase: Default::default(),
2237                }))
2238            });
2239
2240        let mut client_layer_exports = FxIndexMap::default();
2241
2242        // If it's a "use server" or a "use cache" file, all exports need to be annotated.
2243        if should_track_exports {
2244            let server_reference_exports = self.server_reference_exports.take();
2245
2246            for ServerReferenceExport {
2247                ident,
2248                export_name,
2249                reference_id: ref_id,
2250                needs_cache_runtime_wrapper,
2251                ..
2252            } in &server_reference_exports
2253            {
2254                if !self.config.is_react_server_layer {
2255                    if matches!(export_name, ModuleExportName::Ident(i) if i.sym == *"default") {
2256                        let export_expr = ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(
2257                            ExportDefaultExpr {
2258                                span: DUMMY_SP,
2259                                expr: Box::new(Expr::Call(CallExpr {
2260                                    // In development, we generate these spans for sourcemapping
2261                                    // with better logs/errors. For production, this is not
2262                                    // generated because it would leak server code to the browser.
2263                                    span: if self.config.is_react_server_layer
2264                                        || self.config.is_development
2265                                    {
2266                                        self.comments.add_pure_comment(ident.span.lo);
2267                                        ident.span
2268                                    } else {
2269                                        PURE_SP
2270                                    },
2271                                    callee: Callee::Expr(Box::new(Expr::Ident(
2272                                        create_ref_ident.clone(),
2273                                    ))),
2274                                    args: vec![
2275                                        ref_id.clone().as_arg(),
2276                                        call_server_ident.clone().as_arg(),
2277                                        Expr::undefined(DUMMY_SP).as_arg(),
2278                                        find_source_map_url_ident.clone().as_arg(),
2279                                        "default".as_arg(),
2280                                    ],
2281                                    ..Default::default()
2282                                })),
2283                            },
2284                        ));
2285                        client_layer_exports.insert(
2286                            atom!("default"),
2287                            (
2288                                vec![export_expr],
2289                                ModuleExportName::Ident(atom!("default").into()),
2290                                ref_id.clone(),
2291                            ),
2292                        );
2293                    } else {
2294                        let var_name = if in_cache_file {
2295                            self.gen_cache_ident()
2296                        } else {
2297                            self.gen_action_ident()
2298                        };
2299
2300                        let var_ident = Ident::new(var_name.clone(), DUMMY_SP, self.private_ctxt);
2301
2302                        // Determine span for the variable name. In development, we generate these
2303                        // spans for sourcemapping with better logs/errors. For production, this is
2304                        // not generated because it would leak server code to the browser.
2305                        let name_span =
2306                            if self.config.is_react_server_layer || self.config.is_development {
2307                                ident.span
2308                            } else {
2309                                DUMMY_SP
2310                            };
2311
2312                        let export_name_str: Wtf8Atom = match export_name {
2313                            ModuleExportName::Ident(i) => i.sym.clone().into(),
2314                            ModuleExportName::Str(s) => s.value.clone(),
2315                        };
2316
2317                        let var_decl = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
2318                            span: DUMMY_SP,
2319                            kind: VarDeclKind::Const,
2320                            decls: vec![VarDeclarator {
2321                                span: DUMMY_SP,
2322                                name: Pat::Ident(
2323                                    Ident::new(var_name.clone(), name_span, self.private_ctxt)
2324                                        .into(),
2325                                ),
2326                                init: Some(Box::new(Expr::Call(CallExpr {
2327                                    span: PURE_SP,
2328                                    callee: Callee::Expr(Box::new(Expr::Ident(
2329                                        create_ref_ident.clone(),
2330                                    ))),
2331                                    args: vec![
2332                                        ref_id.clone().as_arg(),
2333                                        call_server_ident.clone().as_arg(),
2334                                        Expr::undefined(DUMMY_SP).as_arg(),
2335                                        find_source_map_url_ident.clone().as_arg(),
2336                                        export_name_str.as_arg(),
2337                                    ],
2338                                    ..Default::default()
2339                                }))),
2340                                definite: false,
2341                            }],
2342                            ..Default::default()
2343                        }))));
2344
2345                        // Determine the export name. In development, we generate these spans for
2346                        // sourcemapping with better logs/errors. For production, this is not
2347                        // generated because it would leak server code to the browser.
2348                        let exported_name =
2349                            if self.config.is_react_server_layer || self.config.is_development {
2350                                export_name.clone()
2351                            } else {
2352                                strip_export_name_span(export_name)
2353                            };
2354
2355                        let export_named =
2356                            ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport {
2357                                span: DUMMY_SP,
2358                                specifiers: vec![ExportSpecifier::Named(ExportNamedSpecifier {
2359                                    span: DUMMY_SP,
2360                                    orig: ModuleExportName::Ident(var_ident),
2361                                    exported: Some(exported_name),
2362                                    is_type_only: false,
2363                                })],
2364                                src: None,
2365                                type_only: false,
2366                                with: None,
2367                            }));
2368
2369                        client_layer_exports.insert(
2370                            var_name,
2371                            (
2372                                vec![var_decl, export_named],
2373                                export_name.clone(),
2374                                ref_id.clone(),
2375                            ),
2376                        );
2377                    }
2378                } else if in_cache_file {
2379                    // Generate cache runtime wrapper for exports that might not be functions
2380                    // at compile time (re-exported identifiers, HOC results, etc.)
2381                    // Pattern: let x = orig; if (typeof orig === "function") { x = wrapper(...) }
2382
2383                    if !*needs_cache_runtime_wrapper {
2384                        continue;
2385                    }
2386
2387                    // Generate wrapper ident: $$RSC_SERVER_CACHE_exportName
2388                    let wrapper_ident = Ident::new(
2389                        format!("$$RSC_SERVER_CACHE_{}", export_name.atom()).into(),
2390                        ident.span,
2391                        self.private_ctxt,
2392                    );
2393
2394                    self.has_cache = true;
2395                    self.reference_ids_by_export_name
2396                        .insert(export_name.clone(), ref_id.clone());
2397
2398                    // let $$RSC_SERVER_CACHE_exportName = exportName;
2399                    self.extra_items
2400                        .push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
2401                            kind: VarDeclKind::Let,
2402                            decls: vec![VarDeclarator {
2403                                span: ident.span,
2404                                name: Pat::Ident(wrapper_ident.clone().into()),
2405                                init: Some(Box::new(Expr::Ident(ident.clone()))),
2406                                definite: false,
2407                            }],
2408                            ..Default::default()
2409                        })))));
2410
2411                    let wrapper_stmts = {
2412                        let mut stmts = vec![
2413                            // $$RSC_SERVER_CACHE_exportName = $$reactCache__(...);
2414                            Stmt::Expr(ExprStmt {
2415                                span: DUMMY_SP,
2416                                expr: Box::new(Expr::Assign(AssignExpr {
2417                                    span: DUMMY_SP,
2418                                    op: op!("="),
2419                                    left: AssignTarget::Simple(SimpleAssignTarget::Ident(
2420                                        wrapper_ident.clone().into(),
2421                                    )),
2422                                    right: Box::new(create_cache_wrapper(
2423                                        "default",
2424                                        ref_id.clone(),
2425                                        0,
2426                                        // Don't use the same name as the original to avoid
2427                                        // shadowing. We don't need it here for call stacks.
2428                                        None,
2429                                        Expr::Ident(ident.clone()),
2430                                        ident.span,
2431                                        None,
2432                                        self.unresolved_ctxt,
2433                                    )),
2434                                })),
2435                            }),
2436                            // registerServerReference($$RSC_SERVER_CACHE_exportName, ...);
2437                            Stmt::Expr(ExprStmt {
2438                                span: DUMMY_SP,
2439                                expr: Box::new(annotate_ident_as_server_reference(
2440                                    wrapper_ident.clone(),
2441                                    ref_id.clone(),
2442                                    ident.span,
2443                                )),
2444                            }),
2445                        ];
2446
2447                        // Only assign a name if the original ident is not a generated one.
2448                        if !ident.sym.starts_with("$$RSC_SERVER_") {
2449                            // Object.defineProperty($$RSC_SERVER_CACHE_exportName, "name", {...});
2450                            stmts.push(assign_name_to_ident(
2451                                &wrapper_ident,
2452                                &ident.sym,
2453                                self.unresolved_ctxt,
2454                            ));
2455                        }
2456
2457                        stmts
2458                    };
2459
2460                    // if (typeof ident === "function") { $$RSC_SERVER_CACHE_exportName = wrapper }
2461                    self.extra_items.push(ModuleItem::Stmt(Stmt::If(IfStmt {
2462                        test: Box::new(Expr::Bin(BinExpr {
2463                            span: DUMMY_SP,
2464                            op: op!("==="),
2465                            left: Box::new(Expr::Unary(UnaryExpr {
2466                                span: DUMMY_SP,
2467                                op: op!("typeof"),
2468                                arg: Box::new(Expr::Ident(ident.clone())),
2469                            })),
2470                            right: Box::new(Expr::Lit(Lit::Str(Str {
2471                                span: DUMMY_SP,
2472                                value: atom!("function").into(),
2473                                raw: None,
2474                            }))),
2475                        })),
2476                        cons: Box::new(Stmt::Block(BlockStmt {
2477                            stmts: wrapper_stmts,
2478                            ..Default::default()
2479                        })),
2480                        ..Default::default()
2481                    })));
2482
2483                    // Generate export with rename: export { $$RSC_SERVER_CACHE_name as name }
2484                    if matches!(export_name, ModuleExportName::Ident(i) if i.sym == *"default") {
2485                        self.extra_items.push(ModuleItem::ModuleDecl(
2486                            ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
2487                                span: DUMMY_SP,
2488                                expr: Box::new(Expr::Ident(wrapper_ident)),
2489                            }),
2490                        ));
2491                    } else {
2492                        self.extra_items
2493                            .push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
2494                                NamedExport {
2495                                    span: DUMMY_SP,
2496                                    specifiers: vec![ExportSpecifier::Named(
2497                                        ExportNamedSpecifier {
2498                                            span: DUMMY_SP,
2499                                            orig: ModuleExportName::Ident(wrapper_ident),
2500                                            exported: Some(export_name.clone()),
2501                                            is_type_only: false,
2502                                        },
2503                                    )],
2504                                    src: None,
2505                                    type_only: false,
2506                                    with: None,
2507                                },
2508                            )));
2509                    }
2510                } else {
2511                    self.annotations.push(Stmt::Expr(ExprStmt {
2512                        span: DUMMY_SP,
2513                        expr: Box::new(annotate_ident_as_server_reference(
2514                            ident.clone(),
2515                            ref_id.clone(),
2516                            ident.span,
2517                        )),
2518                    }));
2519                }
2520            }
2521
2522            // Ensure that the exports are functions by appending a runtime check:
2523            //
2524            //   import { ensureServerEntryExports } from 'private-next-rsc-action-validate'
2525            //   ensureServerEntryExports([action1, action2, ...])
2526            //
2527            // But it's only needed for the server layer, because on the client
2528            // layer they're transformed into references already.
2529            if (self.has_action || self.has_cache) && self.config.is_react_server_layer {
2530                new.append(&mut self.extra_items);
2531
2532                // For "use cache" files, there's no need to do extra annotations.
2533                if !in_cache_file && !server_reference_exports.is_empty() {
2534                    let ensure_ident = private_ident!("ensureServerEntryExports");
2535                    new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
2536                        span: DUMMY_SP,
2537                        specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
2538                            span: DUMMY_SP,
2539                            local: ensure_ident.clone(),
2540                            imported: None,
2541                            is_type_only: false,
2542                        })],
2543                        src: Box::new(Str {
2544                            span: DUMMY_SP,
2545                            value: atom!("private-next-rsc-action-validate").into(),
2546                            raw: None,
2547                        }),
2548                        type_only: false,
2549                        with: None,
2550                        phase: Default::default(),
2551                    })));
2552                    new.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt {
2553                        span: DUMMY_SP,
2554                        expr: Box::new(Expr::Call(CallExpr {
2555                            span: DUMMY_SP,
2556                            callee: Callee::Expr(Box::new(Expr::Ident(ensure_ident))),
2557                            args: vec![ExprOrSpread {
2558                                spread: None,
2559                                expr: Box::new(Expr::Array(ArrayLit {
2560                                    span: DUMMY_SP,
2561                                    elems: server_reference_exports
2562                                        .iter()
2563                                        .map(|ServerReferenceExport { ident, .. }| {
2564                                            Some(ExprOrSpread {
2565                                                spread: None,
2566                                                expr: Box::new(Expr::Ident(ident.clone())),
2567                                            })
2568                                        })
2569                                        .collect(),
2570                                })),
2571                            }],
2572                            ..Default::default()
2573                        })),
2574                    })));
2575                }
2576
2577                // Append annotations to the end of the file.
2578                new.extend(self.annotations.drain(..).map(ModuleItem::Stmt));
2579            }
2580        }
2581
2582        // import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
2583        // import { cache as $$reactCache__ } from "react";
2584        if self.has_cache && self.config.is_react_server_layer {
2585            new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
2586                span: DUMMY_SP,
2587                specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
2588                    span: DUMMY_SP,
2589                    local: quote_ident!("$$cache__").into(),
2590                    imported: Some(quote_ident!("cache").into()),
2591                    is_type_only: false,
2592                })],
2593                src: Box::new(Str {
2594                    span: DUMMY_SP,
2595                    value: atom!("private-next-rsc-cache-wrapper").into(),
2596                    raw: None,
2597                }),
2598                type_only: false,
2599                with: None,
2600                phase: Default::default(),
2601            })));
2602
2603            new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
2604                span: DUMMY_SP,
2605                specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
2606                    span: DUMMY_SP,
2607                    local: quote_ident!("$$reactCache__").into(),
2608                    imported: Some(quote_ident!("cache").into()),
2609                    is_type_only: false,
2610                })],
2611                src: Box::new(Str {
2612                    span: DUMMY_SP,
2613                    value: atom!("react").into(),
2614                    raw: None,
2615                }),
2616                type_only: false,
2617                with: None,
2618                phase: Default::default(),
2619            })));
2620
2621            // Make them the first items
2622            new.rotate_right(2);
2623        }
2624
2625        if (self.has_action || self.has_cache) && self.config.is_react_server_layer {
2626            // Inlined actions are only allowed on the server layer.
2627            // import { registerServerReference } from 'private-next-rsc-server-reference'
2628            new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
2629                span: DUMMY_SP,
2630                specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
2631                    span: DUMMY_SP,
2632                    local: quote_ident!("registerServerReference").into(),
2633                    imported: None,
2634                    is_type_only: false,
2635                })],
2636                src: Box::new(Str {
2637                    span: DUMMY_SP,
2638                    value: atom!("private-next-rsc-server-reference").into(),
2639                    raw: None,
2640                }),
2641                type_only: false,
2642                with: None,
2643                phase: Default::default(),
2644            })));
2645
2646            let mut import_count = 1;
2647
2648            // Encryption and decryption only happens when there are bound arguments.
2649            if self.has_server_reference_with_bound_args {
2650                // import { encryptActionBoundArgs, decryptActionBoundArgs } from
2651                // 'private-next-rsc-action-encryption'
2652                new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
2653                    span: DUMMY_SP,
2654                    specifiers: vec![
2655                        ImportSpecifier::Named(ImportNamedSpecifier {
2656                            span: DUMMY_SP,
2657                            local: quote_ident!("encryptActionBoundArgs").into(),
2658                            imported: None,
2659                            is_type_only: false,
2660                        }),
2661                        ImportSpecifier::Named(ImportNamedSpecifier {
2662                            span: DUMMY_SP,
2663                            local: quote_ident!("decryptActionBoundArgs").into(),
2664                            imported: None,
2665                            is_type_only: false,
2666                        }),
2667                    ],
2668                    src: Box::new(Str {
2669                        span: DUMMY_SP,
2670                        value: atom!("private-next-rsc-action-encryption").into(),
2671                        raw: None,
2672                    }),
2673                    type_only: false,
2674                    with: None,
2675                    phase: Default::default(),
2676                })));
2677                import_count += 1;
2678            }
2679
2680            // Make them the first items
2681            new.rotate_right(import_count);
2682        }
2683
2684        if self.has_action || self.has_cache {
2685            // Build a map of reference_id -> export info
2686            let export_infos_ordered_by_reference_id = self
2687                .reference_ids_by_export_name
2688                .iter()
2689                .map(|(export_name, reference_id)| {
2690                    let name_atom = export_name.atom().into_owned();
2691                    (reference_id, ServerReferenceExportInfo { name: name_atom })
2692                })
2693                .collect::<BTreeMap<_, _>>();
2694
2695            if self.config.is_react_server_layer {
2696                // Prepend a special comment to the top of the file.
2697                self.comments.add_leading(
2698                    self.start_pos,
2699                    Comment {
2700                        span: DUMMY_SP,
2701                        kind: CommentKind::Block,
2702                        text: generate_server_references_comment(
2703                            &export_infos_ordered_by_reference_id,
2704                            match self.mode {
2705                                ServerActionsMode::Webpack => None,
2706                                ServerActionsMode::Turbopack => Some((
2707                                    &self.file_name,
2708                                    self.file_query.as_ref().map_or("", |v| v),
2709                                )),
2710                            },
2711                        )
2712                        .into(),
2713                    },
2714                );
2715            } else {
2716                match self.mode {
2717                    ServerActionsMode::Webpack => {
2718                        self.comments.add_leading(
2719                            self.start_pos,
2720                            Comment {
2721                                span: DUMMY_SP,
2722                                kind: CommentKind::Block,
2723                                text: generate_server_references_comment(
2724                                    &export_infos_ordered_by_reference_id,
2725                                    None,
2726                                )
2727                                .into(),
2728                            },
2729                        );
2730                        new.push(client_layer_import.unwrap());
2731                        new.rotate_right(1);
2732                        new.extend(
2733                            client_layer_exports
2734                                .into_iter()
2735                                .flat_map(|(_, (items, _, _))| items),
2736                        );
2737                    }
2738                    ServerActionsMode::Turbopack => {
2739                        new.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt {
2740                            expr: Box::new(Expr::Lit(Lit::Str(
2741                                atom!("use turbopack no side effects").into(),
2742                            ))),
2743                            span: DUMMY_SP,
2744                        })));
2745                        new.rotate_right(1);
2746                        for (_, (items, export_name, ref_id)) in client_layer_exports {
2747                            let mut module_items = vec![
2748                                ModuleItem::Stmt(Stmt::Expr(ExprStmt {
2749                                    expr: Box::new(Expr::Lit(Lit::Str(
2750                                        atom!("use turbopack no side effects").into(),
2751                                    ))),
2752                                    span: DUMMY_SP,
2753                                })),
2754                                client_layer_import.clone().unwrap(),
2755                            ];
2756                            module_items.extend(items);
2757
2758                            // For Turbopack, always strip spans from the main output file's
2759                            // re-exports since the actual source maps are in the data URLs.
2760                            let stripped_export_name = strip_export_name_span(&export_name);
2761
2762                            let name_atom = export_name.atom().into_owned();
2763                            let export_info = ServerReferenceExportInfo { name: name_atom };
2764
2765                            new.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
2766                                NamedExport {
2767                                    specifiers: vec![ExportSpecifier::Named(
2768                                        ExportNamedSpecifier {
2769                                            span: DUMMY_SP,
2770                                            orig: stripped_export_name,
2771                                            exported: None,
2772                                            is_type_only: false,
2773                                        },
2774                                    )],
2775                                    src: Some(Box::new(
2776                                        program_to_data_url(
2777                                            &self.file_name,
2778                                            &self.cm,
2779                                            module_items,
2780                                            Comment {
2781                                                span: DUMMY_SP,
2782                                                kind: CommentKind::Block,
2783                                                text: generate_server_references_comment(
2784                                                    &std::iter::once((&ref_id, export_info))
2785                                                        .collect(),
2786                                                    Some((
2787                                                        &self.file_name,
2788                                                        self.file_query.as_ref().map_or("", |v| v),
2789                                                    )),
2790                                                )
2791                                                .into(),
2792                                            },
2793                                        )
2794                                        .into(),
2795                                    )),
2796                                    span: DUMMY_SP,
2797                                    type_only: false,
2798                                    with: None,
2799                                },
2800                            )));
2801                        }
2802                    }
2803                }
2804            }
2805        }
2806
2807        *stmts = new;
2808
2809        self.annotations = old_annotations;
2810    }
2811
2812    fn visit_mut_stmts(&mut self, stmts: &mut Vec<Stmt>) {
2813        let old_annotations = self.annotations.take();
2814
2815        let mut new = Vec::with_capacity(stmts.len());
2816        for mut stmt in stmts.take() {
2817            stmt.visit_mut_with(self);
2818
2819            new.push(stmt);
2820            new.append(&mut self.annotations);
2821        }
2822
2823        *stmts = new;
2824
2825        self.annotations = old_annotations;
2826    }
2827
2828    fn visit_mut_jsx_attr(&mut self, attr: &mut JSXAttr) {
2829        let old_arrow_or_fn_expr_ident = self.arrow_or_fn_expr_ident.take();
2830
2831        if let (Some(JSXAttrValue::JSXExprContainer(container)), JSXAttrName::Ident(ident_name)) =
2832            (&attr.value, &attr.name)
2833        {
2834            match &container.expr {
2835                JSXExpr::Expr(box Expr::Arrow(_)) | JSXExpr::Expr(box Expr::Fn(_)) => {
2836                    self.arrow_or_fn_expr_ident = Some(ident_name.clone().into());
2837                }
2838                _ => {}
2839            }
2840        }
2841
2842        attr.visit_mut_children_with(self);
2843        self.arrow_or_fn_expr_ident = old_arrow_or_fn_expr_ident;
2844    }
2845
2846    fn visit_mut_var_declarator(&mut self, var_declarator: &mut VarDeclarator) {
2847        let old_current_export_name = self.current_export_name.take();
2848        let old_arrow_or_fn_expr_ident = self.arrow_or_fn_expr_ident.take();
2849
2850        if let (Pat::Ident(ident), Some(box Expr::Arrow(_) | box Expr::Fn(_))) =
2851            (&var_declarator.name, &var_declarator.init)
2852        {
2853            if self.in_module_level
2854                && let Some(export_name) = self.export_name_by_local_id.get(&ident.to_id())
2855            {
2856                self.current_export_name = Some(export_name.clone());
2857            }
2858
2859            self.arrow_or_fn_expr_ident = Some(ident.id.clone());
2860        }
2861
2862        var_declarator.visit_mut_children_with(self);
2863
2864        self.current_export_name = old_current_export_name;
2865        self.arrow_or_fn_expr_ident = old_arrow_or_fn_expr_ident;
2866    }
2867
2868    fn visit_mut_assign_expr(&mut self, assign_expr: &mut AssignExpr) {
2869        let old_arrow_or_fn_expr_ident = self.arrow_or_fn_expr_ident.clone();
2870
2871        if let (
2872            AssignTarget::Simple(SimpleAssignTarget::Ident(ident)),
2873            Expr::Arrow(_) | Expr::Fn(_),
2874        ) = (&assign_expr.left, &*assign_expr.right)
2875        {
2876            self.arrow_or_fn_expr_ident = Some(ident.id.clone());
2877        }
2878
2879        assign_expr.visit_mut_children_with(self);
2880        self.arrow_or_fn_expr_ident = old_arrow_or_fn_expr_ident;
2881    }
2882
2883    fn visit_mut_this_expr(&mut self, n: &mut ThisExpr) {
2884        if let ThisStatus::Forbidden { directive } = &self.this_status {
2885            emit_error(ServerActionsErrorKind::ForbiddenExpression {
2886                span: n.span,
2887                expr: "this".into(),
2888                directive: directive.clone(),
2889            });
2890        }
2891    }
2892
2893    fn visit_mut_super(&mut self, n: &mut Super) {
2894        if let ThisStatus::Forbidden { directive } = &self.this_status {
2895            emit_error(ServerActionsErrorKind::ForbiddenExpression {
2896                span: n.span,
2897                expr: "super".into(),
2898                directive: directive.clone(),
2899            });
2900        }
2901    }
2902
2903    fn visit_mut_ident(&mut self, n: &mut Ident) {
2904        if n.sym == *"arguments"
2905            && let ThisStatus::Forbidden { directive } = &self.this_status
2906        {
2907            emit_error(ServerActionsErrorKind::ForbiddenExpression {
2908                span: n.span,
2909                expr: "arguments".into(),
2910                directive: directive.clone(),
2911            });
2912        }
2913    }
2914
2915    noop_visit_mut_type!();
2916}
2917
2918fn retain_names_from_declared_idents(
2919    child_names: &mut Vec<Name>,
2920    current_declared_idents: &[Ident],
2921) {
2922    // Collect the names to retain in a separate vector
2923    let mut retained_names = Vec::new();
2924
2925    for name in child_names.iter() {
2926        let mut should_retain = true;
2927
2928        // Merge child_names. For example if both `foo.bar` and `foo.bar.baz` are used,
2929        // we only need to keep `foo.bar` as it covers the other.
2930
2931        // Currently this is O(n^2) and we can potentially improve this to O(n log n)
2932        // by sorting or using a hashset.
2933        for another_name in child_names.iter() {
2934            if name != another_name
2935                && name.0 == another_name.0
2936                && name.1.len() >= another_name.1.len()
2937            {
2938                let mut is_prefix = true;
2939                for i in 0..another_name.1.len() {
2940                    if name.1[i] != another_name.1[i] {
2941                        is_prefix = false;
2942                        break;
2943                    }
2944                }
2945                if is_prefix {
2946                    should_retain = false;
2947                    break;
2948                }
2949            }
2950        }
2951
2952        if should_retain
2953            && current_declared_idents
2954                .iter()
2955                .any(|ident| ident.to_id() == name.0)
2956            && !retained_names.contains(name)
2957        {
2958            retained_names.push(name.clone());
2959        }
2960    }
2961
2962    // Replace the original child_names with the retained names
2963    *child_names = retained_names;
2964}
2965
2966/// Returns true if the expression may need a cache runtime wrapper.
2967/// Known functions and known non-functions return false.
2968fn may_need_cache_runtime_wrapper(expr: &Expr) -> bool {
2969    match expr {
2970        // Known functions - don't need wrapper
2971        Expr::Arrow(_) | Expr::Fn(_) => false,
2972        // Known non-functions - don't need wrapper
2973        Expr::Object(_) | Expr::Array(_) | Expr::Lit(_) => false,
2974        // Unknown/might be function - needs runtime check
2975        _ => true,
2976    }
2977}
2978
2979/// Creates a cache wrapper expression:
2980/// $$reactCache__(function name() { return $$cache__(...) })
2981#[allow(clippy::too_many_arguments)]
2982fn create_cache_wrapper(
2983    cache_kind: &str,
2984    reference_id: Atom,
2985    bound_args_length: usize,
2986    fn_ident: Option<Ident>,
2987    target_expr: Expr,
2988    original_span: Span,
2989    params: Option<&[Param]>,
2990    unresolved_ctxt: SyntaxContext,
2991) -> Expr {
2992    let cache_call = CallExpr {
2993        span: original_span,
2994        callee: quote_ident!("$$cache__").as_callee(),
2995        args: vec![
2996            Box::new(Expr::from(cache_kind)).as_arg(),
2997            Box::new(Expr::from(reference_id.as_str())).as_arg(),
2998            Box::new(Expr::Lit(Lit::Num(Number {
2999                span: DUMMY_SP,
3000                value: bound_args_length as f64,
3001                raw: None,
3002            })))
3003            .as_arg(),
3004            Box::new(target_expr).as_arg(),
3005            match params {
3006                // The params are statically known and rest params are not used.
3007                Some(params) if !params.iter().any(|p| matches!(p.pat, Pat::Rest(_))) => {
3008                    if params.is_empty() {
3009                        // No params are declared, we can pass an empty array to ignore unused
3010                        // arguments.
3011                        Box::new(Expr::Array(ArrayLit {
3012                            span: DUMMY_SP,
3013                            elems: vec![],
3014                        }))
3015                        .as_arg()
3016                    } else {
3017                        // Slice to declared params length to ignore unused arguments.
3018                        Box::new(quote!(
3019                            "$array.prototype.slice.call(arguments, 0, $end)" as Expr,
3020                            array = quote_ident!(unresolved_ctxt, "Array"),
3021                            end: Expr = params.len().into(),
3022                        ))
3023                        .as_arg()
3024                    }
3025                }
3026                // The params are statically unknown, or rest params are used.
3027                _ => {
3028                    // Pass all arguments as an array.
3029                    Box::new(quote!(
3030                        "$array.prototype.slice.call(arguments)" as Expr,
3031                        array = quote_ident!(unresolved_ctxt, "Array"),
3032                    ))
3033                    .as_arg()
3034                }
3035            },
3036        ],
3037        ..Default::default()
3038    };
3039
3040    // This wrapper function ensures that we have a user-space call stack frame.
3041    let wrapper_fn_expr = Box::new(Expr::Fn(FnExpr {
3042        ident: fn_ident,
3043        function: Box::new(Function {
3044            body: Some(BlockStmt {
3045                stmts: vec![Stmt::Return(ReturnStmt {
3046                    span: DUMMY_SP,
3047                    arg: Some(Box::new(Expr::Call(cache_call))),
3048                })],
3049                ..Default::default()
3050            }),
3051            span: original_span,
3052            ..Default::default()
3053        }),
3054    }));
3055
3056    Expr::Call(CallExpr {
3057        callee: quote_ident!("$$reactCache__").as_callee(),
3058        args: vec![wrapper_fn_expr.as_arg()],
3059        ..Default::default()
3060    })
3061}
3062
3063#[allow(clippy::too_many_arguments)]
3064fn create_and_hoist_cache_function(
3065    cache_kind: &str,
3066    reference_id: Atom,
3067    bound_args_length: usize,
3068    cache_name: Atom,
3069    fn_ident: Option<Ident>,
3070    params: Vec<Param>,
3071    body: Option<BlockStmt>,
3072    original_span: Span,
3073    hoisted_extra_items: &mut Vec<ModuleItem>,
3074    unresolved_ctxt: SyntaxContext,
3075) -> Ident {
3076    let cache_ident = private_ident!(Span::dummy_with_cmt(), cache_name.clone());
3077    let inner_fn_name: Atom = format!("{}_INNER", cache_name).into();
3078    let inner_fn_ident = private_ident!(Span::dummy_with_cmt(), inner_fn_name);
3079
3080    let wrapper_fn = Box::new(create_cache_wrapper(
3081        cache_kind,
3082        reference_id.clone(),
3083        bound_args_length,
3084        fn_ident.clone(),
3085        Expr::Ident(inner_fn_ident.clone()),
3086        original_span,
3087        Some(&params),
3088        unresolved_ctxt,
3089    ));
3090
3091    let inner_fn_expr = FnExpr {
3092        ident: fn_ident.clone(),
3093        function: Box::new(Function {
3094            params,
3095            body,
3096            span: original_span,
3097            is_async: true,
3098            ..Default::default()
3099        }),
3100    };
3101
3102    hoisted_extra_items.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
3103        span: original_span,
3104        kind: VarDeclKind::Const,
3105        decls: vec![VarDeclarator {
3106            span: original_span,
3107            name: Pat::Ident(BindingIdent {
3108                id: inner_fn_ident.clone(),
3109                type_ann: None,
3110            }),
3111            init: Some(Box::new(Expr::Fn(inner_fn_expr))),
3112            definite: false,
3113        }],
3114        ..Default::default()
3115    })))));
3116
3117    // For anonymous functions, set the name property to an empty string to
3118    // avoid leaking the internal variable name in stack traces.
3119    if fn_ident.is_none() {
3120        hoisted_extra_items.push(ModuleItem::Stmt(assign_name_to_ident(
3121            &inner_fn_ident,
3122            "",
3123            unresolved_ctxt,
3124        )));
3125    }
3126
3127    hoisted_extra_items.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
3128        span: DUMMY_SP,
3129        decl: VarDecl {
3130            kind: VarDeclKind::Var,
3131            decls: vec![VarDeclarator {
3132                span: original_span,
3133                name: Pat::Ident(cache_ident.clone().into()),
3134                init: Some(wrapper_fn),
3135                definite: false,
3136            }],
3137            ..Default::default()
3138        }
3139        .into(),
3140    })));
3141
3142    hoisted_extra_items.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt {
3143        span: DUMMY_SP,
3144        expr: Box::new(annotate_ident_as_server_reference(
3145            cache_ident.clone(),
3146            reference_id,
3147            original_span,
3148        )),
3149    })));
3150
3151    cache_ident
3152}
3153
3154fn assign_name_to_ident(ident: &Ident, name: &str, unresolved_ctxt: SyntaxContext) -> Stmt {
3155    // Assign a name with `Object.defineProperty($$ACTION_0, 'name', {value: 'default'})`
3156    quote!(
3157        // WORKAROUND for https://github.com/microsoft/TypeScript/issues/61165
3158        // This should just be
3159        //
3160        //   "Object.defineProperty($action, \"name\", { value: $name });"
3161        //
3162        // but due to the above typescript bug, `Object.defineProperty` calls are typechecked incorrectly
3163        // in js files, and it can cause false positives when typechecking our fixture files.
3164        "$object[\"defineProperty\"]($action, \"name\", { value: $name });"
3165            as Stmt,
3166        object = quote_ident!(unresolved_ctxt, "Object"),
3167        action: Ident = ident.clone(),
3168        name: Expr = name.into(),
3169    )
3170}
3171
3172fn annotate_ident_as_server_reference(ident: Ident, action_id: Atom, original_span: Span) -> Expr {
3173    // registerServerReference(reference, id, null)
3174    Expr::Call(CallExpr {
3175        span: original_span,
3176        callee: quote_ident!("registerServerReference").as_callee(),
3177        args: vec![
3178            ExprOrSpread {
3179                spread: None,
3180                expr: Box::new(Expr::Ident(ident)),
3181            },
3182            ExprOrSpread {
3183                spread: None,
3184                expr: Box::new(action_id.clone().into()),
3185            },
3186            ExprOrSpread {
3187                spread: None,
3188                expr: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))),
3189            },
3190        ],
3191        ..Default::default()
3192    })
3193}
3194
3195fn bind_args_to_ident(ident: Ident, bound: Vec<Option<ExprOrSpread>>, action_id: Atom) -> Expr {
3196    // ident.bind(null, [encryptActionBoundArgs("id", arg1, arg2, ...)])
3197    Expr::Call(CallExpr {
3198        span: DUMMY_SP,
3199        callee: Expr::Member(MemberExpr {
3200            span: DUMMY_SP,
3201            obj: Box::new(ident.into()),
3202            prop: MemberProp::Ident(quote_ident!("bind")),
3203        })
3204        .as_callee(),
3205        args: vec![
3206            ExprOrSpread {
3207                spread: None,
3208                expr: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))),
3209            },
3210            ExprOrSpread {
3211                spread: None,
3212                expr: Box::new(Expr::Call(CallExpr {
3213                    span: DUMMY_SP,
3214                    callee: quote_ident!("encryptActionBoundArgs").as_callee(),
3215                    args: std::iter::once(ExprOrSpread {
3216                        spread: None,
3217                        expr: Box::new(action_id.into()),
3218                    })
3219                    .chain(bound.into_iter().flatten())
3220                    .collect(),
3221                    ..Default::default()
3222                })),
3223            },
3224        ],
3225        ..Default::default()
3226    })
3227}
3228
3229// Detects if two strings are similar (but not the same).
3230// This implementation is fast and simple as it allows only one
3231// edit (add, remove, edit, swap), instead of using a N^2 Levenshtein algorithm.
3232//
3233// Example of similar strings of "use server":
3234// "use servers",
3235// "use-server",
3236// "use sevrer",
3237// "use srever",
3238// "use servre",
3239// "user server",
3240//
3241// This avoids accidental typos as there's currently no other static analysis
3242// tool to help when these mistakes happen.
3243fn detect_similar_strings(a: &str, b: &str) -> bool {
3244    let mut a = a.chars().collect::<Vec<char>>();
3245    let mut b = b.chars().collect::<Vec<char>>();
3246
3247    if a.len() < b.len() {
3248        (a, b) = (b, a);
3249    }
3250
3251    if a.len() == b.len() {
3252        // Same length, get the number of character differences.
3253        let mut diff = 0;
3254        for i in 0..a.len() {
3255            if a[i] != b[i] {
3256                diff += 1;
3257                if diff > 2 {
3258                    return false;
3259                }
3260            }
3261        }
3262
3263        // Should be 1 or 2, but not 0.
3264        diff != 0
3265    } else {
3266        if a.len() - b.len() > 1 {
3267            return false;
3268        }
3269
3270        // A has one more character than B.
3271        for i in 0..b.len() {
3272            if a[i] != b[i] {
3273                // This should be the only difference, a[i+1..] should be equal to b[i..].
3274                // Otherwise, they're not considered similar.
3275                // A: "use srerver"
3276                // B: "use server"
3277                //          ^
3278                return a[i + 1..] == b[i..];
3279            }
3280        }
3281
3282        // This happens when the last character of A is an extra character.
3283        true
3284    }
3285}
3286
3287// Check if the function or arrow function has any action or cache directives,
3288// without mutating the function body or erroring out.
3289// This is used to quickly determine if we need to use the module-level
3290// directives for this function or not.
3291fn has_body_directive(maybe_body: &Option<BlockStmt>) -> (bool, bool) {
3292    let mut is_action_fn = false;
3293    let mut is_cache_fn = false;
3294
3295    if let Some(body) = maybe_body {
3296        for stmt in body.stmts.iter() {
3297            match stmt {
3298                Stmt::Expr(ExprStmt {
3299                    expr: box Expr::Lit(Lit::Str(Str { value, .. })),
3300                    ..
3301                }) => {
3302                    if value == "use server" {
3303                        is_action_fn = true;
3304                        break;
3305                    } else if value == "use cache" || value.starts_with("use cache: ") {
3306                        is_cache_fn = true;
3307                        break;
3308                    }
3309                }
3310                _ => break,
3311            }
3312        }
3313    }
3314
3315    (is_action_fn, is_cache_fn)
3316}
3317
3318fn collect_idents_in_array_pat(elems: &[Option<Pat>], idents: &mut Vec<Ident>) {
3319    for elem in elems.iter().flatten() {
3320        match elem {
3321            Pat::Ident(ident) => {
3322                idents.push(ident.id.clone());
3323            }
3324            Pat::Array(array) => {
3325                collect_idents_in_array_pat(&array.elems, idents);
3326            }
3327            Pat::Object(object) => {
3328                collect_idents_in_object_pat(&object.props, idents);
3329            }
3330            Pat::Rest(rest) => {
3331                if let Pat::Ident(ident) = &*rest.arg {
3332                    idents.push(ident.id.clone());
3333                }
3334            }
3335            Pat::Assign(AssignPat { left, .. }) => {
3336                collect_idents_in_pat(left, idents);
3337            }
3338            Pat::Expr(..) | Pat::Invalid(..) => {}
3339        }
3340    }
3341}
3342
3343fn collect_idents_in_object_pat(props: &[ObjectPatProp], idents: &mut Vec<Ident>) {
3344    for prop in props {
3345        match prop {
3346            ObjectPatProp::KeyValue(KeyValuePatProp { value, .. }) => {
3347                // For { foo: bar }, only collect 'bar' (the local binding), not 'foo' (the property
3348                // key).
3349                match &**value {
3350                    Pat::Ident(ident) => {
3351                        idents.push(ident.id.clone());
3352                    }
3353                    Pat::Array(array) => {
3354                        collect_idents_in_array_pat(&array.elems, idents);
3355                    }
3356                    Pat::Object(object) => {
3357                        collect_idents_in_object_pat(&object.props, idents);
3358                    }
3359                    _ => {}
3360                }
3361            }
3362            ObjectPatProp::Assign(AssignPatProp { key, .. }) => {
3363                // For { foo }, 'foo' is both the property key and local binding.
3364                idents.push(key.id.clone());
3365            }
3366            ObjectPatProp::Rest(RestPat { arg, .. }) => {
3367                if let Pat::Ident(ident) = &**arg {
3368                    idents.push(ident.id.clone());
3369                }
3370            }
3371        }
3372    }
3373}
3374
3375fn collect_idents_in_var_decls(decls: &[VarDeclarator], idents: &mut Vec<Ident>) {
3376    for decl in decls {
3377        collect_idents_in_pat(&decl.name, idents);
3378    }
3379}
3380
3381fn collect_idents_in_pat(pat: &Pat, idents: &mut Vec<Ident>) {
3382    match pat {
3383        Pat::Ident(ident) => {
3384            idents.push(ident.id.clone());
3385        }
3386        Pat::Array(array) => {
3387            collect_idents_in_array_pat(&array.elems, idents);
3388        }
3389        Pat::Object(object) => {
3390            collect_idents_in_object_pat(&object.props, idents);
3391        }
3392        Pat::Assign(AssignPat { left, .. }) => {
3393            collect_idents_in_pat(left, idents);
3394        }
3395        Pat::Rest(RestPat { arg, .. }) => {
3396            if let Pat::Ident(ident) = &**arg {
3397                idents.push(ident.id.clone());
3398            }
3399        }
3400        Pat::Expr(..) | Pat::Invalid(..) => {}
3401    }
3402}
3403
3404fn collect_decl_idents_in_stmt(stmt: &Stmt, idents: &mut Vec<Ident>) {
3405    if let Stmt::Decl(decl) = stmt {
3406        match decl {
3407            Decl::Var(var) => {
3408                collect_idents_in_var_decls(&var.decls, idents);
3409            }
3410            Decl::Fn(fn_decl) => {
3411                idents.push(fn_decl.ident.clone());
3412            }
3413            _ => {}
3414        }
3415    }
3416}
3417
3418struct DirectiveVisitor<'a> {
3419    config: &'a Config,
3420    location: DirectiveLocation,
3421    directive: Option<Directive>,
3422    has_file_directive: bool,
3423    is_allowed_position: bool,
3424    use_cache_telemetry_tracker: Rc<RefCell<FxHashMap<String, usize>>>,
3425}
3426
3427impl DirectiveVisitor<'_> {
3428    /**
3429     * Returns `true` if the statement contains a server directive.
3430     * The found directive is assigned to `DirectiveVisitor::directive`.
3431     */
3432    fn visit_stmt(&mut self, stmt: &Stmt) -> bool {
3433        let in_fn_body = matches!(self.location, DirectiveLocation::FunctionBody);
3434        let allow_inline = self.config.is_react_server_layer || self.has_file_directive;
3435
3436        match stmt {
3437            Stmt::Expr(ExprStmt {
3438                expr: box Expr::Lit(Lit::Str(Str { value, span, .. })),
3439                ..
3440            }) => {
3441                if value == "use server" {
3442                    if in_fn_body && !allow_inline {
3443                        emit_error(ServerActionsErrorKind::InlineUseServerInClientComponent {
3444                            span: *span,
3445                        })
3446                    } else if let Some(Directive::UseCache { .. }) = self.directive {
3447                        emit_error(ServerActionsErrorKind::MultipleDirectives {
3448                            span: *span,
3449                            location: self.location.clone(),
3450                        });
3451                    } else if self.is_allowed_position {
3452                        self.directive = Some(Directive::UseServer);
3453
3454                        return true;
3455                    } else {
3456                        emit_error(ServerActionsErrorKind::MisplacedDirective {
3457                            span: *span,
3458                            directive: value.to_string_lossy().into_owned(),
3459                            location: self.location.clone(),
3460                        });
3461                    }
3462                } else if detect_similar_strings(&value.to_string_lossy(), "use server") {
3463                    // Detect typo of "use server"
3464                    emit_error(ServerActionsErrorKind::MisspelledDirective {
3465                        span: *span,
3466                        directive: value.to_string_lossy().into_owned(),
3467                        expected_directive: "use server".to_string(),
3468                    });
3469                } else if value == "use action" {
3470                    emit_error(ServerActionsErrorKind::MisspelledDirective {
3471                        span: *span,
3472                        directive: value.to_string_lossy().into_owned(),
3473                        expected_directive: "use server".to_string(),
3474                    });
3475                } else
3476                // `use cache` or `use cache: foo`
3477                if let Some(rest) = value.as_str().and_then(|s| s.strip_prefix("use cache"))
3478                {
3479                    // Increment telemetry counter tracking usage of "use cache" directives
3480
3481                    if in_fn_body && !allow_inline {
3482                        emit_error(ServerActionsErrorKind::InlineUseCacheInClientComponent {
3483                            span: *span,
3484                        })
3485                    } else if let Some(Directive::UseServer) = self.directive {
3486                        emit_error(ServerActionsErrorKind::MultipleDirectives {
3487                            span: *span,
3488                            location: self.location.clone(),
3489                        });
3490                    } else if self.is_allowed_position {
3491                        if !self.config.use_cache_enabled {
3492                            emit_error(ServerActionsErrorKind::UseCacheWithoutCacheComponents {
3493                                span: *span,
3494                                directive: value.to_string_lossy().into_owned(),
3495                            });
3496                        }
3497
3498                        if rest.is_empty() {
3499                            self.directive = Some(Directive::UseCache {
3500                                cache_kind: rcstr!("default"),
3501                            });
3502
3503                            self.increment_cache_usage_counter("default");
3504
3505                            return true;
3506                        }
3507
3508                        if rest.starts_with(": ") {
3509                            let cache_kind = RcStr::from(rest.split_at(": ".len()).1.to_string());
3510
3511                            if !cache_kind.is_empty() {
3512                                if !self.config.cache_kinds.contains(&cache_kind) {
3513                                    emit_error(ServerActionsErrorKind::UnknownCacheKind {
3514                                        span: *span,
3515                                        cache_kind: cache_kind.clone(),
3516                                    });
3517                                }
3518
3519                                self.increment_cache_usage_counter(&cache_kind);
3520                                self.directive = Some(Directive::UseCache { cache_kind });
3521
3522                                return true;
3523                            }
3524                        }
3525
3526                        // Emit helpful errors for variants like "use cache:<cache-kind>",
3527                        // "use cache : <cache-kind>", and "use cache <cache-kind>" etc.
3528                        let expected_directive = if let Some(colon_pos) = rest.find(':') {
3529                            let kind = rest[colon_pos + 1..].trim();
3530
3531                            if kind.is_empty() {
3532                                "use cache: <cache-kind>".to_string()
3533                            } else {
3534                                format!("use cache: {kind}")
3535                            }
3536                        } else {
3537                            let kind = rest.trim();
3538
3539                            if kind.is_empty() {
3540                                "use cache".to_string()
3541                            } else {
3542                                format!("use cache: {kind}")
3543                            }
3544                        };
3545
3546                        emit_error(ServerActionsErrorKind::MisspelledDirective {
3547                            span: *span,
3548                            directive: value.to_string_lossy().into_owned(),
3549                            expected_directive,
3550                        });
3551
3552                        return true;
3553                    } else {
3554                        emit_error(ServerActionsErrorKind::MisplacedDirective {
3555                            span: *span,
3556                            directive: value.to_string_lossy().into_owned(),
3557                            location: self.location.clone(),
3558                        });
3559                    }
3560                } else {
3561                    // Detect typo of "use cache"
3562                    if detect_similar_strings(&value.to_string_lossy(), "use cache") {
3563                        emit_error(ServerActionsErrorKind::MisspelledDirective {
3564                            span: *span,
3565                            directive: value.to_string_lossy().into_owned(),
3566                            expected_directive: "use cache".to_string(),
3567                        });
3568                    }
3569                }
3570            }
3571            Stmt::Expr(ExprStmt {
3572                expr:
3573                    box Expr::Paren(ParenExpr {
3574                        expr: box Expr::Lit(Lit::Str(Str { value, .. })),
3575                        ..
3576                    }),
3577                span,
3578                ..
3579            }) => {
3580                // Match `("use server")`.
3581                if value == "use server"
3582                    || detect_similar_strings(&value.to_string_lossy(), "use server")
3583                {
3584                    if self.is_allowed_position {
3585                        emit_error(ServerActionsErrorKind::WrappedDirective {
3586                            span: *span,
3587                            directive: "use server".to_string(),
3588                        });
3589                    } else {
3590                        emit_error(ServerActionsErrorKind::MisplacedWrappedDirective {
3591                            span: *span,
3592                            directive: "use server".to_string(),
3593                            location: self.location.clone(),
3594                        });
3595                    }
3596                } else if value == "use cache"
3597                    || detect_similar_strings(&value.to_string_lossy(), "use cache")
3598                {
3599                    if self.is_allowed_position {
3600                        emit_error(ServerActionsErrorKind::WrappedDirective {
3601                            span: *span,
3602                            directive: "use cache".to_string(),
3603                        });
3604                    } else {
3605                        emit_error(ServerActionsErrorKind::MisplacedWrappedDirective {
3606                            span: *span,
3607                            directive: "use cache".to_string(),
3608                            location: self.location.clone(),
3609                        });
3610                    }
3611                }
3612            }
3613            _ => {
3614                // Directives must not be placed after other statements.
3615                self.is_allowed_position = false;
3616            }
3617        };
3618
3619        false
3620    }
3621
3622    // Increment telemetry counter tracking usage of "use cache" directives
3623    fn increment_cache_usage_counter(&mut self, cache_kind: &str) {
3624        let mut tracker_map = RefCell::borrow_mut(&self.use_cache_telemetry_tracker);
3625        let entry = tracker_map.entry(cache_kind.to_string());
3626        match entry {
3627            hash_map::Entry::Occupied(mut occupied) => {
3628                *occupied.get_mut() += 1;
3629            }
3630            hash_map::Entry::Vacant(vacant) => {
3631                vacant.insert(1);
3632            }
3633        }
3634    }
3635}
3636
3637pub(crate) struct ClosureReplacer<'a> {
3638    used_ids: &'a [Name],
3639    private_ctxt: SyntaxContext,
3640}
3641
3642impl ClosureReplacer<'_> {
3643    fn index(&self, e: &Expr) -> Option<usize> {
3644        let name = Name::try_from(e).ok()?;
3645        self.used_ids.iter().position(|used_id| *used_id == name)
3646    }
3647}
3648
3649impl VisitMut for ClosureReplacer<'_> {
3650    fn visit_mut_expr(&mut self, e: &mut Expr) {
3651        e.visit_mut_children_with(self);
3652
3653        if let Some(index) = self.index(e) {
3654            *e = Expr::Ident(Ident::new(
3655                // $$ACTION_ARG_0
3656                format!("$$ACTION_ARG_{index}").into(),
3657                DUMMY_SP,
3658                self.private_ctxt,
3659            ));
3660        }
3661    }
3662
3663    fn visit_mut_prop_or_spread(&mut self, n: &mut PropOrSpread) {
3664        n.visit_mut_children_with(self);
3665
3666        if let PropOrSpread::Prop(box Prop::Shorthand(i)) = n {
3667            let name = Name::from(&*i);
3668            if let Some(index) = self.used_ids.iter().position(|used_id| *used_id == name) {
3669                *n = PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
3670                    key: PropName::Ident(i.clone().into()),
3671                    value: Box::new(Expr::Ident(Ident::new(
3672                        // $$ACTION_ARG_0
3673                        format!("$$ACTION_ARG_{index}").into(),
3674                        DUMMY_SP,
3675                        self.private_ctxt,
3676                    ))),
3677                })));
3678            }
3679        }
3680    }
3681
3682    noop_visit_mut_type!();
3683}
3684
3685#[derive(Debug, Clone, PartialEq, Eq)]
3686struct NamePart {
3687    prop: Atom,
3688    is_member: bool,
3689    optional: bool,
3690}
3691
3692#[derive(Debug, Clone, PartialEq, Eq)]
3693struct Name(Id, Vec<NamePart>);
3694
3695impl From<&'_ Ident> for Name {
3696    fn from(value: &Ident) -> Self {
3697        Name(value.to_id(), vec![])
3698    }
3699}
3700
3701impl TryFrom<&'_ Expr> for Name {
3702    type Error = ();
3703
3704    fn try_from(value: &Expr) -> Result<Self, Self::Error> {
3705        match value {
3706            Expr::Ident(i) => Ok(Name(i.to_id(), vec![])),
3707            Expr::Member(e) => e.try_into(),
3708            Expr::OptChain(e) => e.try_into(),
3709            _ => Err(()),
3710        }
3711    }
3712}
3713
3714impl TryFrom<&'_ MemberExpr> for Name {
3715    type Error = ();
3716
3717    fn try_from(value: &MemberExpr) -> Result<Self, Self::Error> {
3718        match &value.prop {
3719            MemberProp::Ident(prop) => {
3720                let mut obj: Name = value.obj.as_ref().try_into()?;
3721                obj.1.push(NamePart {
3722                    prop: prop.sym.clone(),
3723                    is_member: true,
3724                    optional: false,
3725                });
3726                Ok(obj)
3727            }
3728            _ => Err(()),
3729        }
3730    }
3731}
3732
3733impl TryFrom<&'_ OptChainExpr> for Name {
3734    type Error = ();
3735
3736    fn try_from(value: &OptChainExpr) -> Result<Self, Self::Error> {
3737        match &*value.base {
3738            OptChainBase::Member(m) => match &m.prop {
3739                MemberProp::Ident(prop) => {
3740                    let mut obj: Name = m.obj.as_ref().try_into()?;
3741                    obj.1.push(NamePart {
3742                        prop: prop.sym.clone(),
3743                        is_member: false,
3744                        optional: value.optional,
3745                    });
3746                    Ok(obj)
3747                }
3748                _ => Err(()),
3749            },
3750            OptChainBase::Call(_) => Err(()),
3751        }
3752    }
3753}
3754
3755impl From<Name> for Box<Expr> {
3756    fn from(value: Name) -> Self {
3757        let mut expr = Box::new(Expr::Ident(value.0.into()));
3758
3759        for NamePart {
3760            prop,
3761            is_member,
3762            optional,
3763        } in value.1.into_iter()
3764        {
3765            #[allow(clippy::replace_box)]
3766            if is_member {
3767                expr = Box::new(Expr::Member(MemberExpr {
3768                    span: DUMMY_SP,
3769                    obj: expr,
3770                    prop: MemberProp::Ident(IdentName::new(prop, DUMMY_SP)),
3771                }));
3772            } else {
3773                expr = Box::new(Expr::OptChain(OptChainExpr {
3774                    span: DUMMY_SP,
3775                    base: Box::new(OptChainBase::Member(MemberExpr {
3776                        span: DUMMY_SP,
3777                        obj: expr,
3778                        prop: MemberProp::Ident(IdentName::new(prop, DUMMY_SP)),
3779                    })),
3780                    optional,
3781                }));
3782            }
3783        }
3784
3785        expr
3786    }
3787}
3788
3789fn emit_error(error_kind: ServerActionsErrorKind) {
3790    let (span, msg) = match error_kind {
3791        ServerActionsErrorKind::ExportedSyncFunction {
3792            span,
3793            in_action_file,
3794        } => (
3795            span,
3796            formatdoc! {
3797                r#"
3798                    Only async functions are allowed to be exported in a {directive} file.
3799                "#,
3800                directive = if in_action_file {
3801                    "\"use server\""
3802                } else {
3803                    "\"use cache\""
3804                }
3805            },
3806        ),
3807        ServerActionsErrorKind::ForbiddenExpression {
3808            span,
3809            expr,
3810            directive,
3811        } => (
3812            span,
3813            formatdoc! {
3814                r#"
3815                    {subject} cannot use `{expr}`.
3816                "#,
3817                subject = if let Directive::UseServer = directive {
3818                    "Server Actions"
3819                } else {
3820                    "\"use cache\" functions"
3821                }
3822            },
3823        ),
3824        ServerActionsErrorKind::InlineUseCacheInClassInstanceMethod { span } => (
3825            span,
3826            formatdoc! {
3827                r#"
3828                    It is not allowed to define inline "use cache" annotated class instance methods.
3829                    To define cached functions, use functions, object method properties, or static class methods instead.
3830                "#
3831            },
3832        ),
3833        ServerActionsErrorKind::InlineUseCacheInClientComponent { span } => (
3834            span,
3835            formatdoc! {
3836                r#"
3837                    It is not allowed to define inline "use cache" annotated functions in Client Components.
3838                    To use "use cache" functions in a Client Component, you can either export them from a separate file with "use cache" or "use server" at the top, or pass them down through props from a Server Component.
3839                "#
3840            },
3841        ),
3842        ServerActionsErrorKind::InlineUseServerInClassInstanceMethod { span } => (
3843            span,
3844            formatdoc! {
3845                r#"
3846                    It is not allowed to define inline "use server" annotated class instance methods.
3847                    To define Server Actions, use functions, object method properties, or static class methods instead.
3848                "#
3849            },
3850        ),
3851        ServerActionsErrorKind::InlineUseServerInClientComponent { span } => (
3852            span,
3853            formatdoc! {
3854                r#"
3855                    It is not allowed to define inline "use server" annotated Server Actions in Client Components.
3856                    To use Server Actions in a Client Component, you can either export them from a separate file with "use server" at the top, or pass them down through props from a Server Component.
3857
3858                    Read more: https://nextjs.org/docs/app/api-reference/directives/use-server#using-server-functions-in-a-client-component
3859                "#
3860            },
3861        ),
3862        ServerActionsErrorKind::InlineSyncFunction { span, directive } => (
3863            span,
3864            formatdoc! {
3865                r#"
3866                    {subject} must be async functions.
3867                "#,
3868                subject = if let Directive::UseServer = directive {
3869                    "Server Actions"
3870                } else {
3871                    "\"use cache\" functions"
3872                }
3873            },
3874        ),
3875        ServerActionsErrorKind::MisplacedDirective {
3876            span,
3877            directive,
3878            location,
3879        } => (
3880            span,
3881            formatdoc! {
3882                r#"
3883                    The "{directive}" directive must be at the top of the {location}.
3884                "#,
3885                location = match location {
3886                    DirectiveLocation::Module => "file",
3887                    DirectiveLocation::FunctionBody => "function body",
3888                }
3889            },
3890        ),
3891        ServerActionsErrorKind::MisplacedWrappedDirective {
3892            span,
3893            directive,
3894            location,
3895        } => (
3896            span,
3897            formatdoc! {
3898                r#"
3899                    The "{directive}" directive must be at the top of the {location}, and cannot be wrapped in parentheses.
3900                "#,
3901                location = match location {
3902                    DirectiveLocation::Module => "file",
3903                    DirectiveLocation::FunctionBody => "function body",
3904                }
3905            },
3906        ),
3907        ServerActionsErrorKind::MisspelledDirective {
3908            span,
3909            directive,
3910            expected_directive,
3911        } => (
3912            span,
3913            formatdoc! {
3914                r#"
3915                    Did you mean "{expected_directive}"? "{directive}" is not a supported directive name."
3916                "#
3917            },
3918        ),
3919        ServerActionsErrorKind::MultipleDirectives { span, location } => (
3920            span,
3921            formatdoc! {
3922                r#"
3923                    Conflicting directives "use server" and "use cache" found in the same {location}. You cannot place both directives at the top of a {location}. Please remove one of them.
3924                "#,
3925                location = match location {
3926                    DirectiveLocation::Module => "file",
3927                    DirectiveLocation::FunctionBody => "function body",
3928                }
3929            },
3930        ),
3931        ServerActionsErrorKind::UnknownCacheKind { span, cache_kind } => (
3932            span,
3933            formatdoc! {
3934                r#"
3935                    Unknown cache kind "{cache_kind}". Please configure a cache handler for this kind in the `cacheHandlers` object in your Next.js config.
3936                "#
3937            },
3938        ),
3939        ServerActionsErrorKind::UseCacheWithoutCacheComponents { span, directive } => (
3940            span,
3941            formatdoc! {
3942                r#"
3943                    To use "{directive}", please enable the feature flag `cacheComponents` in your Next.js config.
3944
3945                    Read more: https://nextjs.org/docs/app/api-reference/directives/use-cache#usage
3946                "#
3947            },
3948        ),
3949        ServerActionsErrorKind::WrappedDirective { span, directive } => (
3950            span,
3951            formatdoc! {
3952                r#"
3953                    The "{directive}" directive cannot be wrapped in parentheses.
3954                "#
3955            },
3956        ),
3957    };
3958
3959    HANDLER.with(|handler| handler.struct_span_err(span, &msg).emit());
3960}
3961
3962/// Strips span information from a ModuleExportName, replacing all spans with DUMMY_SP.
3963/// Used in production builds to prevent leaking source code information in source maps to browsers.
3964fn strip_export_name_span(export_name: &ModuleExportName) -> ModuleExportName {
3965    match export_name {
3966        ModuleExportName::Ident(i) => {
3967            ModuleExportName::Ident(Ident::new(i.sym.clone(), DUMMY_SP, i.ctxt))
3968        }
3969        ModuleExportName::Str(s) => ModuleExportName::Str(Str {
3970            span: DUMMY_SP,
3971            value: s.value.clone(),
3972            raw: None,
3973        }),
3974    }
3975}
3976
3977fn program_to_data_url(
3978    file_name: &str,
3979    cm: &Arc<SourceMap>,
3980    body: Vec<ModuleItem>,
3981    prepend_comment: Comment,
3982) -> String {
3983    let module_span = Span::dummy_with_cmt();
3984    let comments = SingleThreadedComments::default();
3985    comments.add_leading(module_span.lo, prepend_comment);
3986
3987    let program = &Program::Module(Module {
3988        span: module_span,
3989        body,
3990        shebang: None,
3991    });
3992
3993    let mut output = vec![];
3994    let mut mappings = vec![];
3995    let mut emitter = Emitter {
3996        cfg: codegen::Config::default().with_minify(true),
3997        cm: cm.clone(),
3998        wr: Box::new(JsWriter::new(
3999            cm.clone(),
4000            " ",
4001            &mut output,
4002            Some(&mut mappings),
4003        )),
4004        comments: Some(&comments),
4005    };
4006
4007    emitter.emit_program(program).unwrap();
4008    drop(emitter);
4009
4010    pub struct InlineSourcesContentConfig<'a> {
4011        folder_path: Option<&'a Path>,
4012    }
4013    // This module will be placed at `some/path/to/data:28a9d2` where the original input file lives
4014    // at `some/path/to/actions.js`. So we need to generate a relative path, usually `./actions.js`
4015    impl SourceMapGenConfig for InlineSourcesContentConfig<'_> {
4016        fn file_name_to_source(&self, file: &FileName) -> String {
4017            let FileName::Custom(file) = file else {
4018                // Turbopack uses FileName::Custom for the `[project]/...` paths
4019                return file.to_string();
4020            };
4021            let Some(folder_path) = &self.folder_path else {
4022                return file.to_string();
4023            };
4024
4025            if let Some(rel_path) = diff_paths(file, folder_path) {
4026                format!("./{}", rel_path.display())
4027            } else {
4028                file.to_string()
4029            }
4030        }
4031
4032        fn inline_sources_content(&self, _f: &FileName) -> bool {
4033            true
4034        }
4035    }
4036
4037    let map = cm.build_source_map(
4038        &mappings,
4039        None,
4040        InlineSourcesContentConfig {
4041            folder_path: PathBuf::from(format!("[project]/{file_name}")).parent(),
4042        },
4043    );
4044    let map = {
4045        if map.get_token_count() > 0 {
4046            let mut buf = vec![];
4047            map.to_writer(&mut buf)
4048                .expect("failed to generate sourcemap");
4049            Some(buf)
4050        } else {
4051            None
4052        }
4053    };
4054
4055    let mut output = String::from_utf8(output).expect("codegen generated non-utf8 output");
4056    if let Some(map) = map {
4057        output.extend(
4058            format!(
4059                "\n//# sourceMappingURL=data:application/json;base64,{}",
4060                Base64Display::new(&map, &BASE64_STANDARD)
4061            )
4062            .chars(),
4063        );
4064    }
4065    format!("data:text/javascript,{}", urlencoding::encode(&output))
4066}