turbopack_ecmascript/references/
member.rs1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3use swc_core::{
4 atoms::atom,
5 base::SwcComments,
6 common::{
7 DUMMY_SP, Span,
8 comments::{Comment, CommentKind, Comments},
9 },
10 ecma::ast::{Expr, MemberExpr, MemberProp},
11 quote,
12};
13use turbo_rcstr::RcStr;
14use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs};
15use turbopack_core::chunk::ChunkingContext;
16
17use super::AstPath;
18use crate::{
19 code_gen::{CodeGen, CodeGeneration},
20 create_visitor,
21};
22
23#[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
24pub struct MemberReplacement {
25 key: RcStr,
26 value: RcStr,
27 path: AstPath,
28}
29
30impl MemberReplacement {
31 pub fn new(key: RcStr, value: RcStr, path: AstPath) -> Self {
32 MemberReplacement { key, value, path }
33 }
34
35 pub async fn code_generation(
36 &self,
37 _chunking_context: Vc<Box<dyn ChunkingContext>>,
38 ) -> Result<CodeGeneration> {
39 let comments = SwcComments::default();
40
41 let key = self.key.clone();
42 let value = self.value.clone();
43
44 let comments_clone = comments.clone();
45 let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
46 let span = Span::dummy_with_cmt();
47
48 comments_clone.add_leading(
49 span.lo,
50 Comment {
51 kind: CommentKind::Block,
52 span: DUMMY_SP,
53 text: atom!("TURBOPACK member replacement"),
54 },
55 );
56 let member = Expr::Member(MemberExpr {
57 span,
58 obj: Box::new(Expr::Ident((&*key).into())),
59 prop: MemberProp::Ident((&*value).into()),
60 });
61 *expr = quote!("$e" as Expr, e: Expr = member);
62 });
63
64 Ok(CodeGeneration::visitors_with_comments(
65 vec![visitor],
66 comments,
67 ))
68 }
69}
70
71impl From<MemberReplacement> for CodeGen {
72 fn from(val: MemberReplacement) -> Self {
73 CodeGen::MemberReplacement(val)
74 }
75}