use anyhow::Result; use serde::{Deserialize, Serialize}; use swc_core::quote; use turbo_tasks::{NonLocalValue, TaskInput, Vc, debug::ValueDebugFormat, trace::TraceRawVcs}; use turbopack_core::{chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue}; use super::AstPath; use crate::{ code_gen::{CodeGen, CodeGeneration}, create_visitor, }; #[derive( Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue, TaskInput, )] pub struct ConstantValueCodeGen { value: CompileTimeDefineValue, path: AstPath, } impl ConstantValueCodeGen { pub fn new(value: CompileTimeDefineValue, path: AstPath) -> Self { ConstantValueCodeGen { value, path } } pub async fn code_generation( &self, _chunking_context: Vc>, ) -> Result { let value = self.value.clone(); let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { *expr = match value { CompileTimeDefineValue::Bool(true) => { quote!("(\"TURBOPACK compile-time value\", true)" as Expr) } CompileTimeDefineValue::Bool(false) => { quote!("(\"TURBOPACK compile-time value\", false)" as Expr) } CompileTimeDefineValue::String(ref s) => { quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into()) } CompileTimeDefineValue::JSON(ref s) => { quote!("(\"TURBOPACK compile-time value\", JSON.parse($e))" as Expr, e: Expr = s.to_string().into()) } // undefined can be re-bound, so use `void 0` to avoid any risks CompileTimeDefineValue::Undefined => { quote!("(\"TURBOPACK compile-time value\", void 0)" as Expr) } }; }); Ok(CodeGeneration::visitors(vec![visitor])) } } impl From for CodeGen { fn from(val: ConstantValueCodeGen) -> Self { CodeGen::ConstantValueCodeGen(val) } }