#![deny(clippy::all)] #![allow(clippy::boxed_local, clippy::borrowed_box, clippy::deprecated_cfg_attr)] #[macro_use] extern crate napi_derive; mod bundle; mod esbuild; mod swc_plugin_compat_post; mod swc_plugin_extract_str; mod swc_plugin_refresh; mod swc_plugin_transform_builtin_attribute_names; mod swc_plugin_worklet_post_process; use std::{ cell::{Cell, RefCell}, rc::Rc, vec, }; use napi::{bindgen_prelude::AsyncTask, Either, Env, Task}; use rustc_hash::FxBuildHasher; use swc_core::{ atoms::Atom, base::{ config::{GlobalPassOption, IsModule, SourceMapsConfig}, Compiler, PrintArgs, }, common::{ comments::SingleThreadedComments, errors::{DiagnosticBuilder, Emitter, Handler, HANDLER}, pass::Optional, sync::Lrc, FileName, FilePathMapping, Mark, SourceMap, DUMMY_SP, GLOBALS, }, ecma::{ ast::*, codegen, parser::{Syntax, TsSyntax}, transforms::{ base::{ fixer::fixer, helpers, hygiene::{hygiene_with_config, Config}, resolver, }, optimization::{simplifier, simplify}, react, typescript, }, visit::visit_mut_pass, }, }; // currently `use xxx as yyy` is not supported by napi-rs // So we have to use different name use swc_plugin_background_only::BackgroundOnlyVisitor; use swc_plugin_compat::napi::{CompatVisitor, CompatVisitorConfig}; use swc_plugin_compat_post::CompatPostVisitor; use swc_plugin_css_scope::napi::{CSSScopeVisitor, CSSScopeVisitorConfig}; use swc_plugin_define_dce::napi::DefineDCEVisitorConfig; use swc_plugin_directive_dce::napi::{DirectiveDCEVisitor, DirectiveDCEVisitorConfig}; use swc_plugin_dynamic_import::napi::{DynamicImportVisitor, DynamicImportVisitorConfig}; use swc_plugin_element_template::napi::{ ElementTemplateAsset, ElementTemplateTransformer, ElementTemplateTransformerConfig, }; use swc_plugin_element_template::ElementTemplateAsset as CoreElementTemplateAsset; use swc_plugin_inject::napi::{InjectVisitor, InjectVisitorConfig}; use swc_plugin_refresh::{RefreshVisitor, RefreshVisitorConfig}; use swc_plugin_shake::napi::{ShakeVisitor, ShakeVisitorConfig}; use swc_plugin_snapshot::{ napi::{ JSXTransformer as SnapshotJSXTransformer, JSXTransformerConfig as SnapshotJSXTransformerConfig, }, UISourceMapRecord as SnapshotCoreUISourceMapRecord, }; use swc_plugin_transform_builtin_attribute_names::TransformBuiltinAttributeNamesVisitor; pub use swc_plugin_transform_builtin_attribute_names::{ TransformBuiltinAttributeNamesMode, TransformBuiltinAttributeNamesOptions, }; use swc_plugin_worklet::napi::{WorkletVisitor, WorkletVisitorConfig}; use swc_plugins_shared::defines::{DefineKind, DefinesCollector}; use swc_plugins_shared::{ engine_version::is_engine_version_ge, transform_mode_napi::TransformMode, utils::{calc_hash, WEBPACK_VARS}, }; #[derive(Debug, Clone, Copy)] pub struct SyntaxConfig(Syntax); impl From for Syntax { fn from(value: SyntaxConfig) -> Self { value.0 } } impl Default for SyntaxConfig { fn default() -> Self { // override default Self(Syntax::Typescript(TsSyntax { tsx: true, decorators: true, ..Default::default() })) } } impl napi::bindgen_prelude::FromNapiValue for SyntaxConfig { unsafe fn from_napi_value( env: napi::sys::napi_env, napi_val: napi::sys::napi_value, ) -> napi::Result { Ok(SyntaxConfig( serde_json::from_str(<&str>::from_napi_value(env, napi_val)?).map_err(|err| { napi::bindgen_prelude::error!( napi::bindgen_prelude::Status::InvalidArg, "SyntaxConfig: {}", err, ) })?, )) } } impl napi::bindgen_prelude::ToNapiValue for SyntaxConfig { unsafe fn to_napi_value( env: napi::sys::napi_env, val: Self, ) -> napi::Result { <&str>::to_napi_value( env, &serde_json::to_string(&val.0).map_err(|err| { napi::bindgen_prelude::error!( napi::bindgen_prelude::Status::InvalidArg, "SyntaxConfig: {}", err, ) })?, ) } } #[derive(Debug, PartialEq, Clone, Copy, Default)] pub struct IsModuleConfig(IsModule); impl From for IsModule { fn from(value: IsModuleConfig) -> Self { value.0 } } impl napi::bindgen_prelude::FromNapiValue for IsModuleConfig { unsafe fn from_napi_value( env: napi::bindgen_prelude::sys::napi_env, napi_val: napi::bindgen_prelude::sys::napi_value, ) -> napi::bindgen_prelude::Result { let bool_val = ::from_napi_value(env, napi_val); if let Ok(bool_val) = bool_val { return Ok(IsModuleConfig(IsModule::Bool(bool_val))); } let str_val = <&str>::from_napi_value(env, napi_val); if let Ok(val) = str_val { match val { "unknown" => return Ok(IsModuleConfig(IsModule::Unknown)), "commonjs" => return Ok(IsModuleConfig(IsModule::CommonJS)), _ => { return Err(napi::bindgen_prelude::error!( napi::bindgen_prelude::Status::InvalidArg, "Invalid variant '{}' for enum IsModuleConfig", val )); } } } Err(napi::bindgen_prelude::error!( napi::bindgen_prelude::Status::InvalidArg, "value does not match any variant of enum `{}`", "IsModuleConfig" )) } } impl napi::bindgen_prelude::ToNapiValue for IsModuleConfig { unsafe fn to_napi_value( env: napi::bindgen_prelude::sys::napi_env, val: Self, ) -> napi::bindgen_prelude::Result { match val.0 { IsModule::Bool(v) => ::to_napi_value(env, v), IsModule::Unknown => <&str>::to_napi_value(env, "unknown"), IsModule::CommonJS => <&str>::to_napi_value(env, "commonjs"), } } } #[napi(object)] #[derive(Clone, Debug)] pub struct TransformNodiffOptions { /// @internal /// This is used internally to make sure the test output is consistent. #[napi(ts_type = "'production' | 'development' | 'test'")] pub mode: Option, pub plugin_name: String, pub filename: String, pub source_file_name: Option, pub sourcemap: Either, pub source_map_columns: Option, pub inline_sources_content: Option, /// @public /// This is swc syntax config in JSON format #[napi(ts_type = "string")] pub syntax_config: Option, #[napi(ts_type = "boolean | 'unknown'")] pub is_module: Option, pub css_scope: Either, pub snapshot: Option>, #[napi(js_name = "elementTemplate")] pub element_template: Option>, pub engine_version: Option, pub shake: Either, pub compat: Either, pub refresh: Either, #[napi(js_name = "defineDCE")] pub define_dce: Either, #[napi(js_name = "directiveDCE")] pub directive_dce: Either, pub worklet: Either, pub dynamic_import: Option>, /** * Transform attribute names on Lynx builtin elements. * * `true` applies the default rule: `onClick` becomes `bindtap`, * `onCatchTap` becomes `catchtap`, other `onXXX` names become `bindxxx`, * and remaining camelCase names become dash-case. An object provides * serializable custom rules. * Explicit JSX attributes are transformed during compilation. Attributes * supplied through JSX spreads are transformed by the runtime with the same * rules. * * @experimental */ #[napi( js_name = "experimental_transformBuiltinAttributeNames", ts_type = "boolean | TransformBuiltinAttributeNamesOptions" )] pub experimental_transform_builtin_attribute_names: Option>, /// @internal pub inject: Option>, pub input_source_map: Option, } impl Default for TransformNodiffOptions { fn default() -> Self { Self { mode: Some(TransformMode::Production), plugin_name: Default::default(), filename: Default::default(), source_file_name: Default::default(), sourcemap: Either::A(false), source_map_columns: None, inline_sources_content: None, syntax_config: None, is_module: Default::default(), css_scope: Either::B(Default::default()), snapshot: Default::default(), element_template: Default::default(), engine_version: None, shake: Either::A(false), compat: Either::A(false), refresh: Either::A(false), define_dce: Either::A(false), directive_dce: Either::A(false), worklet: Either::A(false), dynamic_import: Some(Either::A(true)), experimental_transform_builtin_attribute_names: None, inject: Some(Either::A(false)), input_source_map: None, } } } #[napi(object)] pub struct UiSourceMapRecord { pub ui_source_map: i32, pub filename: String, pub line_number: u32, pub column_number: u32, #[napi(js_name = "snapshotId")] pub snapshot_id: Option, } /// @internal #[napi(object)] pub struct Define { /// @internal pub id: String, /// @internal pub code: String, /// @internal pub unmergeable: Option, /// @internal pub runtime_requirements: Option, /// Imports needed when this definition moves to another module. /// @internal pub imports: Option>, } /// @internal #[napi(object)] pub struct DefineImport { /// @internal pub source: String, /// @internal pub imported: String, /// @internal pub local: String, /// @internal pub namespace: Option, } #[napi(object)] pub struct TransformRuntimeRequirements { /// @internal #[napi(js_name = "mainThreadProgrammability")] pub main_thread_programmability: bool, } #[napi(object)] pub struct TransformNodiffOutput { pub code: String, pub map: Option, // #[napi(ts_type = "Array")] pub errors: Vec, // #[napi(ts_type = "Array")] pub warnings: Vec, pub ui_source_map_records: Vec, /// @internal #[napi(js_name = "elementTemplates")] pub element_templates: Option>, /// @internal #[napi(js_name = "runtimeRequirements")] pub runtime_requirements: TransformRuntimeRequirements, /// @internal #[napi(js_name = "definesForSnapshot")] pub defines_for_snapshot: Option>, /// @internal #[napi(js_name = "definesForWorklet")] pub defines_for_worklet: Option>, } fn transform_runtime_requirements( main_thread_programmability: bool, ) -> TransformRuntimeRequirements { TransformRuntimeRequirements { main_thread_programmability, } } fn print_define( c: &Compiler, items: Vec, top_level_mark: Mark, comments: &SingleThreadedComments, filename: &str, ) -> Result<(String, Vec), String> { let mut module = match Program::Module(Module { span: DUMMY_SP, body: items, shebang: None, }) .apply(&mut ( hygiene_with_config(Config { top_level_mark, ..Default::default() }), fixer(Some(comments)), )) { Program::Module(m) => m, _ => return Err("hygiene produced a non-module program".into()), }; // Print imports and statements through the same hygiene pass before // separating them. The consumer must not guess bindings from generated code. let filename = filename.replace('\\', "/"); let mut imports = vec![]; let mut statements = vec![]; for item in module.body { if let ModuleItem::ModuleDecl(ModuleDecl::Import(import)) = item { let mut source = import.src.value.to_string_lossy().into_owned(); // std::path's absolute-path checks are unsupported on wasm. if source == "." || source == ".." || source.starts_with("./") || source.starts_with("../") { if let Some((directory, _)) = filename.rsplit_once('/') { source = format!("{directory}/{source}"); if !source.starts_with('/') && source.as_bytes().get(1) != Some(&b':') { source = format!("./{source}"); } } } for specifier in import.specifiers { let local = specifier.local().sym.to_string(); let namespace = matches!(specifier, ImportSpecifier::Namespace(_)).then_some(true); let imported = match specifier { ImportSpecifier::Default(_) => "default".into(), ImportSpecifier::Namespace(_) => "*".into(), ImportSpecifier::Named(named) => match named.imported { Some(ModuleExportName::Ident(ident)) => ident.sym.to_string(), Some(ModuleExportName::Str(value)) => value.value.to_string_lossy().into_owned(), None => named.local.sym.to_string(), }, #[allow(unreachable_patterns)] _ => return Err("unknown definition import specifier".into()), }; imports.push(DefineImport { source: source.clone(), imported, local, namespace, }); } } else { statements.push(item); } } module.body = statements; c.print( &Program::Module(module), PrintArgs { output: None, source_root: "".into(), source_file_name: None, source_map_url: None, source_map_ignore_list: None, output_path: None, inline_sources_content: true, source_map: SourceMapsConfig::Bool(false), source_map_names: &Default::default(), orig: None, comments: Some(comments), emit_source_map_columns: false, emit_source_map_scopes: false, preamble: "", codegen_config: codegen::Config::default() .with_target(EsVersion::latest()) .with_minify(false) .with_ascii_only(false), }, ) .map(|r| (r.code, imports)) .map_err(|err| err.to_string()) } type ElementTemplateCollector = Rc>>; fn take_element_templates( collector: Option, ) -> Option> { collector.map(|collector| { collector .borrow_mut() .drain(..) .map(|template| template.into()) .collect() }) } /// A multi emitter that forwards to multiple emitters. pub struct MultiEmitter { emitters: Vec>, } impl MultiEmitter { pub fn new(emitters: Vec>) -> Self { Self { emitters } } } impl Emitter for MultiEmitter { fn emit(&mut self, db: &mut DiagnosticBuilder<'_>) { for emitter in &mut self.emitters { emitter.emit(db); } } } fn clone_snapshot_ui_source_map_records( ui_source_map_records: &Rc>>, filename: &str, ) -> Vec { ui_source_map_records .borrow() .iter() .cloned() .map(|record| UiSourceMapRecord { ui_source_map: record.ui_source_map, filename: filename.to_string(), line_number: record.line_number, column_number: record.column_number, snapshot_id: Some(record.snapshot_id), }) .collect() } pub struct TransformTask { pub code: String, pub options: TransformNodiffOptions, } fn transform_react_lynx_inner( code: String, options: TransformNodiffOptions, ) -> TransformNodiffOutput { let content_hash = match options.mode { Some(TransformMode::Test) => "test".into(), _ => calc_hash(code.as_str()), }; let comments = SingleThreadedComments::default(); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let fm = cm.new_source_file(FileName::Real(options.filename.clone().into()).into(), code); let c = Compiler::new(cm.clone()); let (esbuild_emitter, errors, warnings) = esbuild::EsbuildEmitter::new(options.plugin_name.clone(), Some(c.cm.clone())); let esbuild_emitter = Box::new(esbuild_emitter); let emitter = Box::new(MultiEmitter::new(vec![esbuild_emitter])); let handler = Handler::with_emitter(true, false, emitter); let snapshot_ui_source_map_records: Rc>> = Rc::new(RefCell::new(vec![])); let main_thread_programmability = Rc::new(Cell::new(false)); let result = GLOBALS.set(&Default::default(), || { let program = c.parse_js( fm, &handler, EsVersion::latest(), options.syntax_config.unwrap_or_default().into(), options.is_module.unwrap_or_default().into(), Some(&comments), ); let program = match program { Ok(program) => program, Err(_) => { return TransformNodiffOutput { code: "".into(), map: None, errors: vec![], warnings: warnings.read().unwrap().clone(), ui_source_map_records: vec![], element_templates: None, runtime_requirements: transform_runtime_requirements(main_thread_programmability.get()), defines_for_snapshot: None, defines_for_worklet: None, }; } }; let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let top_retain = WEBPACK_VARS.iter().map(|&s| s.into()).collect::>(); let simplify_pass_1 = Optional::new( simplifier( top_level_mark, simplify::Config { dce: simplify::dce::Config { preserve_imports_with_side_effects: false, top_retain: top_retain.clone(), ..Default::default() }, ..Default::default() }, ), match &options.directive_dce { Either::A(config) => *config, Either::B(_) => true, } || match &options.define_dce { Either::A(config) => *config, Either::B(_) => true, }, ); let directive_dce_plugin = match options.directive_dce { Either::A(config) => Optional::new( visit_mut_pass(DirectiveDCEVisitor::new(Default::default())), config, ), Either::B(config) => Optional::new(visit_mut_pass(DirectiveDCEVisitor::new(config)), true), }; let define_dce_plugin = { let opts = GlobalPassOption { vars: match &options.define_dce { Either::A(_) => Default::default(), Either::B(config) => { let mut map = indexmap::IndexMap::<_, _, FxBuildHasher>::default(); for (key, value) in &config.define { map.insert(key.as_str().into(), value.as_str().into()); } map } }, envs: Default::default(), typeofs: Default::default(), }; Optional::new( opts.build(&cm, &handler), matches!(options.define_dce, Either::B(_)), ) }; let css_scope_plugin = match options.css_scope { Either::A(enabled) => Optional::new( visit_mut_pass(CSSScopeVisitor::new( CSSScopeVisitorConfig::default(), Some(&comments), )), enabled, ), Either::B(config) => Optional::new( visit_mut_pass(CSSScopeVisitor::new(config, Some(&comments))), true, ), }; let (snapshot_plugin_config, snapshot_enabled) = match options.snapshot.as_ref() { Some(Either::A(config)) => ( SnapshotJSXTransformerConfig { filename: options.filename.clone(), ..Default::default() }, *config, ), Some(Either::B(config)) => (config.clone(), true), None => ( SnapshotJSXTransformerConfig { filename: options.filename.clone(), ..Default::default() }, true, ), }; let (mut element_template_plugin_config, element_template_enabled) = match options.element_template.as_ref() { Some(Either::A(config)) => ( ElementTemplateTransformerConfig { filename: options.filename.clone(), ..Default::default() }, *config, ), Some(Either::B(config)) => (config.clone(), true), None => ( ElementTemplateTransformerConfig { filename: options.filename.clone(), ..Default::default() }, false, ), }; // `elementTemplate` chooses the ET backend directly. Once it is enabled, the // public transform entrypoint no longer consults Snapshot-specific ET flags. if options.snapshot.is_some() && options.element_template.is_some() && snapshot_enabled && element_template_enabled { warnings.write().unwrap().push(esbuild::PartialMessage { id: None, plugin_name: Some(options.plugin_name.clone()), text: Some( "`elementTemplate` takes precedence when both `snapshot` and `elementTemplate` are enabled; `snapshot` will be ignored.".into(), ), location: None, notes: None, detail: None, }); } let use_element_template_plugin = element_template_enabled; const BUILTIN_ET_RUNTIME_PKG: &str = "@lynx-js/react/element-template"; const BUILTIN_ET_INTERNAL_PKG: &str = "@lynx-js/react/element-template/internal"; const BUILTIN_ET_LAZY_IMPORT_PKG: &str = "@lynx-js/react/element-template/experimental/lazy/import"; if use_element_template_plugin && element_template_plugin_config.runtime_pkg == "@lynx-js/react" { element_template_plugin_config.runtime_pkg = BUILTIN_ET_RUNTIME_PKG.into(); } let et_runtime_entries = (use_element_template_plugin && matches!( element_template_plugin_config.runtime_pkg.as_str(), BUILTIN_ET_RUNTIME_PKG | BUILTIN_ET_INTERNAL_PKG )) .then(|| { ( BUILTIN_ET_INTERNAL_PKG.to_string(), BUILTIN_ET_LAZY_IMPORT_PKG.to_string(), ) }); let use_snapshot_plugin = snapshot_enabled && !use_element_template_plugin; let jsx_backend_enabled = use_snapshot_plugin || use_element_template_plugin; let active_jsx_import_source = if use_element_template_plugin { element_template_plugin_config.jsx_import_source.clone() } else { snapshot_plugin_config.jsx_import_source.clone() }; let preserve_jsx = if use_element_template_plugin { element_template_plugin_config.preserve_jsx } else { snapshot_plugin_config.preserve_jsx }; let enable_ui_source_map = !use_element_template_plugin && snapshot_plugin_config.enable_ui_source_map.unwrap_or(false); let background_only_plugin = Optional::new( visit_mut_pass(BackgroundOnlyVisitor::new()), jsx_backend_enabled, ); let react_transformer = Optional::new( react::react( cm.clone(), Some(&comments), react::Options { next: Some(false), runtime: Some(react::Runtime::Automatic), import_source: active_jsx_import_source.map(Atom::from), pragma: None, pragma_frag: None, // We may want `main-thread:foo={fooMainThreadFunc}` to work throw_if_namespace: Some(false), development: Some(matches!(options.mode, Some(TransformMode::Development))), refresh: None, ..Default::default() }, top_level_mark, unresolved_mark, ), jsx_backend_enabled && !preserve_jsx, ); let defines_collector: DefinesCollector = Rc::new(RefCell::new(vec![])); let snapshot_plugin = if use_snapshot_plugin { let transformer = SnapshotJSXTransformer::new( snapshot_plugin_config.clone(), Some(&comments), options.mode.unwrap_or(TransformMode::Production), Some(cm.clone()), ) .with_content_hash(content_hash.clone()); let transformer = if enable_ui_source_map { transformer.with_ui_source_map_records(snapshot_ui_source_map_records.clone()) } else { transformer }; let transformer = transformer.with_defines_collector(defines_collector.clone()); Optional::new(visit_mut_pass(transformer), true) } else { Optional::new( visit_mut_pass(SnapshotJSXTransformer::new( snapshot_plugin_config.clone(), Some(&comments), options.mode.unwrap_or(TransformMode::Production), Some(cm.clone()), )), false, ) }; let element_templates_collector = use_element_template_plugin.then(|| Rc::new(RefCell::new(vec![]))); let element_template_plugin = if use_element_template_plugin { // ET template assets are a build artifact, not runtime JS. Keep one // collector per transform invocation so the output contract stays stable. let transformer = ElementTemplateTransformer::new_with_element_templates( element_template_plugin_config.clone(), Some(&comments), options.mode.unwrap_or(TransformMode::Production), Some(cm.clone()), element_templates_collector.clone(), ) .with_content_hash(content_hash.clone()); Optional::new(visit_mut_pass(transformer), true) } else { Optional::new( visit_mut_pass(ElementTemplateTransformer::new( element_template_plugin_config.clone(), Some(&comments), options.mode.unwrap_or(TransformMode::Production), Some(cm.clone()), )), false, ) }; let legacy_slot = matches!(snapshot_plugin_config.legacy_slot, Some(true)); let list_plugin = Optional::new( visit_mut_pass(swc_plugin_list::ListVisitor::new(Some(&comments))), jsx_backend_enabled && !legacy_slot, ); let legacy_list_plugin = Optional::new( visit_mut_pass(swc_plugin_list::LegacyListVisitor::new(Some(&comments))), jsx_backend_enabled && legacy_slot, ); let is_ge_3_1: bool = is_engine_version_ge(&options.engine_version, "3.1"); let text_plugin = Optional::new( visit_mut_pass(swc_plugin_text::TextVisitor {}), jsx_backend_enabled && is_ge_3_1, ); let shake_plugin = match options.shake.clone() { Either::A(config) => Optional::new(visit_mut_pass(ShakeVisitor::default()), config), Either::B(config) => Optional::new(visit_mut_pass(ShakeVisitor::new(config)), true), }; let simplify_pass = simplifier( top_level_mark, simplify::Config { dce: simplify::dce::Config { preserve_imports_with_side_effects: false, top_retain: top_retain.clone(), ..Default::default() }, ..Default::default() }, ); let (compat_config, compat_enabled) = match options.compat.clone() { Either::A(enabled) => (CompatVisitorConfig::default(), enabled), Either::B(config) => (config, true), }; let use_et_compat_entry = use_element_template_plugin && compat_config.new_runtime_pkg == "@lynx-js/react"; let mut compat_visitor = CompatVisitor::new(compat_config, Some(&comments)); if use_et_compat_entry { if let Some((internal_pkg, lazy_import_pkg)) = &et_runtime_entries { compat_visitor = compat_visitor.with_runtime_entries(internal_pkg.clone(), lazy_import_pkg.clone()); } } let compat_plugin = Optional::new(visit_mut_pass(compat_visitor), compat_enabled); let transform_builtin_attribute_names = options .experimental_transform_builtin_attribute_names .clone(); let enable_transform_builtin_attribute_names = !matches!( transform_builtin_attribute_names, None | Some(Either::A(false)) ); let transform_builtin_attribute_names_visitor = match transform_builtin_attribute_names { Some(Either::B(options)) => TransformBuiltinAttributeNamesVisitor::new(options), None | Some(Either::A(_)) => TransformBuiltinAttributeNamesVisitor::default(), }; let transform_builtin_attribute_names_plugin = Optional::new( visit_mut_pass(transform_builtin_attribute_names_visitor), enable_transform_builtin_attribute_names, ); let compat_post_plugin = match options.compat { Either::A(config) => Optional::new( visit_mut_pass(CompatPostVisitor::new( Default::default(), unresolved_mark, top_level_mark, )), config, ), Either::B(config) => Optional::new( visit_mut_pass(CompatPostVisitor::new( config, unresolved_mark, top_level_mark, )), true, ), }; let refresh_plugin = match options.refresh { Either::A(config) => Optional::new( visit_mut_pass(RefreshVisitor::new( RefreshVisitorConfig::default(), content_hash.clone(), )), config, ), Either::B(config) => Optional::new( visit_mut_pass(RefreshVisitor::new(config, content_hash.clone())), true, ), }; let worklet_plugin = match options.worklet { Either::A(config) => { let visitor_config = match &et_runtime_entries { Some((internal_pkg, _)) => WorkletVisitorConfig { runtime_pkg: internal_pkg.clone(), ..Default::default() }, None => WorkletVisitorConfig::default(), }; let visitor = WorkletVisitor::new(visitor_config).with_content_hash(content_hash); let visitor = visitor .with_defines_collector(defines_collector.clone()) .with_main_thread_programmability(Rc::clone(&main_thread_programmability)); Optional::new(visit_mut_pass(visitor), config) } Either::B(mut config) => { if let Some((internal_pkg, _)) = &et_runtime_entries { if config.runtime_pkg == "@lynx-js/react/internal" { config.runtime_pkg = internal_pkg.clone(); } } let visitor = WorkletVisitor::new(config) .with_content_hash(content_hash); let visitor = visitor .with_defines_collector(defines_collector.clone()) .with_main_thread_programmability(Rc::clone(&main_thread_programmability)); Optional::new(visit_mut_pass(visitor), true) } }; let dynamic_import_plugin = match options.dynamic_import.unwrap_or(Either::A(true)) { Either::A(config) => { let visitor_config = match &et_runtime_entries { Some((internal_pkg, _)) => DynamicImportVisitorConfig { runtime_pkg: internal_pkg.clone(), ..Default::default() }, None => DynamicImportVisitorConfig::default(), }; Optional::new( visit_mut_pass(DynamicImportVisitor::new(visitor_config, Some(&comments))), config, ) } Either::B(mut config) => { if let Some((internal_pkg, _)) = &et_runtime_entries { if config.runtime_pkg == "@lynx-js/react/internal" { config.runtime_pkg = internal_pkg.clone(); } } Optional::new( visit_mut_pass(DynamicImportVisitor::new(config, Some(&comments))), true, ) } }; let inject_plugin = match options.inject.unwrap_or(Either::A(false)) { Either::A(config) => Optional::new( visit_mut_pass(InjectVisitor::new( Default::default(), unresolved_mark, top_level_mark, )), config, ), Either::B(config) => Optional::new( visit_mut_pass(InjectVisitor::new(config, unresolved_mark, top_level_mark)), true, ), }; let pass = ( &mut fixer(Some(&comments)), resolver(unresolved_mark, top_level_mark, true), typescript::typescript( typescript::Config { verbatim_module_syntax: false, import_not_used_as_values: typescript::ImportsNotUsedAsValues::Remove, ..Default::default() }, unresolved_mark, top_level_mark, ), (background_only_plugin, dynamic_import_plugin), refresh_plugin, (compat_plugin, transform_builtin_attribute_names_plugin), worklet_plugin, css_scope_plugin, ( text_plugin, list_plugin, legacy_list_plugin, snapshot_plugin, element_template_plugin, ), directive_dce_plugin, define_dce_plugin, simplify_pass_1, // do simplify after DCE above to make shake below works better ( shake_plugin, simplify_pass, react_transformer, // TODO(hongzhiyuan.hzy): if `ident` we added above is correctly marked, this pass will be unnecessary resolver(unresolved_mark, top_level_mark, true), compat_post_plugin, inject_plugin, hygiene_with_config(Config { top_level_mark, ..Default::default() }), &mut fixer(Some(&comments)), ), ); let program = helpers::HELPERS.set(&helpers::Helpers::new(true), || { HANDLER.set(&handler, || program.apply(pass)) }); let result = c.print( &program, PrintArgs { output: None, source_root: "".into(), // TODO: add root source_file_name: options.source_file_name.as_deref(), source_map_url: None, source_map_ignore_list: None, output_path: None, inline_sources_content: options.inline_sources_content.unwrap_or(true), source_map: match options.sourcemap { Either::A(b) => SourceMapsConfig::Bool(b), Either::B(s) => SourceMapsConfig::Str(s), }, source_map_names: &Default::default(), orig: match &options.input_source_map { Some(s) => { let bytes = s.as_bytes(); swc_sourcemap::SourceMap::from_reader(bytes).ok() } None => None, }, comments: Some(&comments), emit_source_map_columns: options.source_map_columns.unwrap_or(true), emit_source_map_scopes: false, preamble: "", codegen_config: codegen::Config::default() .with_target(EsVersion::latest()) .with_minify(false) .with_ascii_only(false), }, ); match result { Ok(result) => { // Drain after the whole SWC pass finishes: dynamic-component transforms // can discover multiple template assets while walking one module, and // the caller expects one stable array per transform invocation. let element_templates = take_element_templates(element_templates_collector); let mut define_errors: Vec = vec![]; let mut defines_for_snapshot: Vec = vec![]; let mut defines_for_worklet: Vec = vec![]; helpers::HELPERS.set(&helpers::Helpers::new(false), || { for define in defines_collector.borrow().iter() { let (code, imports) = match print_define(&c, define.items.clone(), top_level_mark, &comments, &options.filename) { Ok(printed) => printed, Err(err) => { define_errors.push(esbuild::PartialMessage { id: None, plugin_name: Some(options.plugin_name.clone()), text: Some(format!("failed to print the collected definition `{}`: {}", define.id, err)), location: None, notes: None, detail: None, }); (String::new(), vec![]) } }; let printed = Define { id: define.id.clone(), unmergeable: define.unmergeable.then_some(true), runtime_requirements: (define.kind == DefineKind::Worklet) .then(|| transform_runtime_requirements(true)), imports: (define.kind == DefineKind::Worklet).then_some(imports), code, }; match define.kind { DefineKind::Snapshot => defines_for_snapshot.push(printed), DefineKind::Worklet => defines_for_worklet.push(printed), } } }); TransformNodiffOutput { code: result.code, map: result.map, errors: define_errors, warnings: vec![], ui_source_map_records: if use_element_template_plugin { vec![] } else { clone_snapshot_ui_source_map_records(&snapshot_ui_source_map_records, &options.filename) }, element_templates, runtime_requirements: transform_runtime_requirements(main_thread_programmability.get()), defines_for_snapshot: Some(defines_for_snapshot), defines_for_worklet: Some(defines_for_worklet), } } Err(_) => { let element_templates = take_element_templates(element_templates_collector); return TransformNodiffOutput { code: "".into(), map: None, errors: vec![], warnings: warnings.read().unwrap().clone(), ui_source_map_records: if use_element_template_plugin { vec![] } else { clone_snapshot_ui_source_map_records(&snapshot_ui_source_map_records, &options.filename) }, element_templates, runtime_requirements: transform_runtime_requirements(main_thread_programmability.get()), defines_for_snapshot: None, defines_for_worklet: None, }; } } }); let mut transform_errors = errors.read().unwrap().clone(); transform_errors.extend(result.errors); let r = TransformNodiffOutput { code: result.code, map: result.map, errors: transform_errors, warnings: warnings.read().unwrap().clone(), ui_source_map_records: result.ui_source_map_records, // Preserve the element-template assets collected in the successful transform // path instead of dropping them in the final wrapper object. element_templates: result.element_templates, runtime_requirements: result.runtime_requirements, defines_for_snapshot: result.defines_for_snapshot, defines_for_worklet: result.defines_for_worklet, }; r } #[napi] pub fn transform_react_lynx_sync( _env: Env, code: String, options: Option, ) -> napi::Result { let out = transform_react_lynx_inner(code, options.unwrap_or_default()); napi::Result::Ok(out) } #[napi] impl Task for TransformTask { type Output = TransformNodiffOutput; type JsValue = TransformNodiffOutput; fn compute(&mut self) -> napi::Result { let out = transform_react_lynx_inner(self.code.clone(), self.options.clone()); Ok(out) } fn resolve(&mut self, _: napi::Env, output: Self::Output) -> napi::Result { napi::Result::Ok(output) } } #[napi] pub fn transform_react_lynx( _env: Env, code: String, options: Option, ) -> napi::Result> { Ok(AsyncTask::new(TransformTask { code, options: options.unwrap_or_default(), })) } pub struct BundleTransformTask { pub code: String, pub options: bundle::TransformNodiffBundleOptions, } #[napi] impl Task for BundleTransformTask { type Output = bundle::TransformNodiffBundleOutput; type JsValue = bundle::TransformNodiffBundleOutput; fn compute(&mut self) -> napi::Result { let out = bundle::transform_bundle_result_inner(self.code.clone(), self.options.clone()); Ok(out) } fn resolve(&mut self, _: napi::Env, output: Self::Output) -> napi::Result { napi::Result::Ok(output) } } #[napi] pub fn transform_bundle_result_sync( _env: Env, code: String, options: Option, ) -> napi::Result { let out = bundle::transform_bundle_result_inner(code, options.unwrap_or_default()); napi::Result::Ok(out) } #[napi] pub fn transform_bundle_result( _env: Env, code: String, options: Option, ) -> napi::Result> { Ok(AsyncTask::new(BundleTransformTask { code, options: options.unwrap_or_default(), })) } #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] mod wasm { use ::napi::{JsObject, NapiValue}; const fn max(a: usize, b: usize) -> usize { [a, b][(a < b) as usize] } const ALIGN: usize = max( 8, // wasm32 max_align_t max(std::mem::size_of::(), std::mem::align_of::()), ); #[no_mangle] pub unsafe extern "C" fn malloc(size: usize) -> *mut u8 { let layout = match std::alloc::Layout::from_size_align(size + ALIGN, ALIGN) { Ok(layout) => layout, Err(_) => return core::ptr::null_mut(), }; let ptr = std::alloc::alloc(layout); if ptr.is_null() { return core::ptr::null_mut(); } *(ptr as *mut usize) = size; ptr.offset(ALIGN as isize) } #[no_mangle] pub unsafe extern "C" fn free(ptr: *mut u8) { let ptr = ptr.offset(-(ALIGN as isize)); let size = *(ptr as *mut usize); let layout = std::alloc::Layout::from_size_align_unchecked(size + ALIGN, ALIGN); std::alloc::dealloc(ptr, layout); } #[no_mangle] pub unsafe extern "C" fn napi_register_wasm_v1( raw_env: napi::sys::napi_env, raw_exports: napi::sys::napi_value, ) { // let env = Env::from_raw(raw_env); let mut exports = JsObject::from_raw_unchecked(raw_env, raw_exports); #[cfg_attr(rustfmt, rustfmt_skip)] { let _ = exports.create_named_method("transformReactLynxSync", crate::__napi__transform_react_lynx_sync); let _ = exports.create_named_method("transformBundleResultSync", crate::__napi__transform_bundle_result_sync); let _ = exports.create_named_method("transformReactLynx", crate::__napi__transform_react_lynx); let _ = exports.create_named_method("transformBundleResult", crate::__napi__transform_bundle_result); } } } #[cfg(test)] mod tests { use super::*; fn assert_no_legacy_et_entries(code: &str) { assert!( code.contains("\"@lynx-js/react/element-template/internal\""), "{code}" ); assert!( code.contains("import \"@lynx-js/react/element-template/experimental/lazy/import\""), "{code}" ); assert!( code.contains( "import { loadLazyBundle } from \\\"@lynx-js/react/element-template/internal\\\";" ) || code .contains("import { loadLazyBundle } from \"@lynx-js/react/element-template/internal\";"), "{code}" ); assert!(!code.contains("\"@lynx-js/react/internal\""), "{code}"); assert!( !code.contains("\"@lynx-js/react/experimental/lazy/import\""), "{code}" ); } #[test] fn should_route_et_entries_across_bool_default_and_object_configs() { use swc_plugins_shared::target_napi::TransformTarget; let full_fixture = r#" export function App(Comp, props, url) { const onTap = () => { 'main thread'; return props.value; }; const loadRemote = () => import(url, { with: { type: 'component' } }); const loadLocal = () => import(/* webpackChunkName: "lazy" */ './lazy.tsx', { with: { type: 'component' } }); return ( {loadRemote} {loadLocal} ); } "#; let cases = [ // Explicit ET runtimePkg on both JS and LEPUS targets. TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), compat: Either::B(CompatVisitorConfig { add_component_element: Either::A(true), ..Default::default() }), worklet: Either::A(true), dynamic_import: Some(Either::A(true)), element_template: Some(Either::B(ElementTemplateTransformerConfig { target: TransformTarget::JS, filename: "test.jsx".into(), runtime_pkg: "@lynx-js/react/element-template".into(), ..Default::default() })), ..Default::default() }, TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), compat: Either::B(CompatVisitorConfig { add_component_element: Either::A(true), ..Default::default() }), worklet: Either::A(true), dynamic_import: Some(Either::A(true)), element_template: Some(Either::B(ElementTemplateTransformerConfig { target: TransformTarget::LEPUS, filename: "test.jsx".into(), runtime_pkg: "@lynx-js/react/element-template".into(), ..Default::default() })), ..Default::default() }, // Default `elementTemplate: true` with omitted `dynamic_import`. TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), compat: Either::B(CompatVisitorConfig { add_component_element: Either::A(true), ..Default::default() }), element_template: Some(Either::A(true)), ..Default::default() }, // Explicit legacy `@lynx-js/react` ET runtimePkg with omitted `dynamic_import`. TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), compat: Either::B(CompatVisitorConfig { add_component_element: Either::A(true), ..Default::default() }), element_template: Some(Either::B(ElementTemplateTransformerConfig { target: TransformTarget::LEPUS, filename: "test.jsx".into(), runtime_pkg: "@lynx-js/react".into(), ..Default::default() })), ..Default::default() }, ]; for options in cases { let result = transform_react_lynx_inner(full_fixture.into(), options); assert!(result.errors.is_empty(), "{:?}", result.errors); assert_no_legacy_et_entries(&result.code); } // Object configs with the legacy built-in `@lynx-js/react/internal` runtimePkg // normalize to ET (including worklet helper imports) while preserving `layer` and `target`. let obj_result = transform_react_lynx_inner( full_fixture.into(), TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), worklet: Either::B(WorkletVisitorConfig { target: TransformTarget::JS, runtime_pkg: "@lynx-js/react/internal".into(), ..Default::default() }), dynamic_import: Some(Either::B(DynamicImportVisitorConfig { layer: "react__background".into(), runtime_pkg: "@lynx-js/react/internal".into(), ..Default::default() })), element_template: Some(Either::A(true)), ..Default::default() }, ); assert!(obj_result.errors.is_empty(), "{:?}", obj_result.errors); assert_no_legacy_et_entries(&obj_result.code); assert!( obj_result.code.lines().any(|line| { line.contains("import ") && line.contains("captureMainThreadObject") && line.contains("\"@lynx-js/react/element-template/internal\"") }), "{}", obj_result.code ); assert!( obj_result.code.contains("lazy-react__background"), "{}", obj_result.code ); } #[test] fn should_preserve_worklet_init_and_custom_runtime_pkgs_in_et_builds() { use swc_plugins_shared::target_napi::TransformTarget; let worklet_src = "export function App() { const onTap = () => { 'main thread'; return 1; }; return ; }"; for (runtime_pkg, expected_init, enable_et) in [ ( "@lynx-js/react/element-template/internal", "@lynx-js/react/worklet-runtime/init", true, ), ( "@acme/element-template/internal", "@acme/element-template/worklet-runtime/init", false, ), ( "@my-org/react/element-template/internal", "@my-org/react/element-template/worklet-runtime/init", false, ), ] { let result = transform_react_lynx_inner( worklet_src.into(), TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), worklet: Either::B(WorkletVisitorConfig { target: TransformTarget::JS, runtime_pkg: runtime_pkg.into(), ..Default::default() }), element_template: enable_et.then(|| { Either::B(ElementTemplateTransformerConfig { target: TransformTarget::JS, filename: "test.jsx".into(), runtime_pkg: "@lynx-js/react/element-template".into(), ..Default::default() }) }), ..Default::default() }, ); assert!(result.errors.is_empty(), "{:?}", result.errors); if enable_et { assert!( result .code .contains("\"@lynx-js/react/element-template/internal\""), "{}", result.code ); } let defines = result.defines_for_worklet.unwrap(); assert_eq!(defines.len(), 1); let imports = defines[0].imports.as_ref().unwrap(); assert!( imports.iter().any(|imp| imp.source == expected_init), "expected {expected_init}, got {:?}", imports .iter() .map(|imp| imp.source.as_str()) .collect::>() ); } // Custom compat runtimePkg is preserved in ET builds. let custom_compat = transform_react_lynx_inner( "export function App(Comp, props, url) { return [, ]; }" .into(), TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), compat: Either::B(CompatVisitorConfig { new_runtime_pkg: "@my-org/react".into(), add_component_element: Either::A(true), ..Default::default() }), element_template: Some(Either::A(true)), ..Default::default() }, ); assert!( custom_compat.errors.is_empty(), "{:?}", custom_compat.errors ); assert!( custom_compat .code .contains("import * as ReactLynx from \"@my-org/react/internal\""), "{}", custom_compat.code ); assert!( custom_compat .code .contains("import \"@my-org/react/experimental/lazy/import\""), "{}", custom_compat.code ); // Custom dynamicImport runtimePkg strips only trailing `/internal` and keeps // synthetic `data:` bootstrap on `@lynx-js/react/internal`. let custom_di = transform_react_lynx_inner( "export function load(url) { return [import(url, { with: { type: 'component' } }), import('./lazy.tsx', { with: { type: 'component' } })]; }" .into(), TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), dynamic_import: Some(Either::B(DynamicImportVisitorConfig { runtime_pkg: "@acme/internal-react/internal".into(), ..Default::default() })), ..Default::default() }, ); assert!(custom_di.errors.is_empty(), "{:?}", custom_di.errors); assert!( custom_di .code .contains("import \"@acme/internal-react/experimental/lazy/import\""), "{}", custom_di.code ); assert!( custom_di .code .contains("import { loadLazyBundle } from \\\"@lynx-js/react/internal\\\";") || custom_di .code .contains("import { loadLazyBundle } from \"@lynx-js/react/internal\";"), "{}", custom_di.code ); // Relative file-path ET runtimePkg does not synthesize invalid helper subpaths. let custom_et = transform_react_lynx_inner( "export function App(url) { return ; }".into(), TransformNodiffOptions { filename: "test.jsx".into(), css_scope: Either::A(false), compat: Either::B(CompatVisitorConfig { add_component_element: Either::A(true), ..Default::default() }), element_template: Some(Either::B(ElementTemplateTransformerConfig { target: TransformTarget::JS, filename: "test.jsx".into(), runtime_pkg: "./runtime/internal.ts".into(), ..Default::default() })), ..Default::default() }, ); assert!(custom_et.errors.is_empty(), "{:?}", custom_et.errors); assert!( !custom_et .code .contains("./runtime/internal.ts/experimental/lazy/import"), "{}", custom_et.code ); } fn worklet_definition(source: &str, filename: &str) -> Define { let result = transform_react_lynx_inner( source.into(), TransformNodiffOptions { filename: filename.into(), worklet: Either::B(WorkletVisitorConfig { target: swc_plugins_shared::target_napi::TransformTarget::JS, custom_global_ident_names: Some(vec!["call".into(), "api".into(), "named".into()]), ..Default::default() }), css_scope: Either::A(false), ..Default::default() }, ); assert!(result.errors.is_empty(), "{:?}", result.errors); let mut definitions = result.defines_for_worklet.unwrap(); assert_eq!(definitions.len(), 1); definitions.remove(0) } #[test] fn should_collect_business_imports_for_background_only_worklets() { let definition = worklet_definition( r#" import { runOnBackground, useState } from '@lynx-js/react'; export const handler = () => { 'main thread'; runOnBackground(() => {})(); }; "#, "test.js", ); let imports = definition.imports.unwrap(); let dependency = imports .iter() .find(|item| item.imported == "runOnBackground") .unwrap(); assert_eq!(dependency.source, "@lynx-js/react"); assert!(definition .code .contains(&format!("{}(_jsFn1)()", dependency.local))); assert!(!imports.iter().any(|item| item.imported == "useState")); assert_eq!(imports.len(), 2); } #[test] fn should_preserve_import_forms_and_rebase_relative_definition_dependencies() { for (filename, expected) in [ ("/project/src/test.js", "/project/src/./bridge.js"), ("C:\\project\\src\\test.js", "C:/project/src/./bridge.js"), ("src/test.js", "./src/./bridge.js"), ("test.js", "./bridge.js"), ] { let definition = worklet_definition( r#" import call, * as api from './bridge.js'; import { original as named } from './bridge.js'; export const handler = () => { 'main thread'; return [call(), api.value, { named }]; }; "#, filename, ); let imports = definition.imports.unwrap(); let default = imports .iter() .find(|item| item.imported == "default") .unwrap(); assert_eq!(default.source, expected); assert_eq!(default.local, "call"); assert_eq!(default.namespace, None); let namespace = imports .iter() .find(|item| item.namespace == Some(true)) .unwrap(); assert_eq!(namespace.imported, "*"); assert_eq!(namespace.source, expected); let named = imports .iter() .find(|item| item.imported == "original") .unwrap(); assert_eq!(named.source, expected); assert!(definition.code.contains(&named.local)); } } #[test] fn should_rebase_only_relative_definition_imports() { for (source, expected) in [ (".", "/project/src/."), ("..", "/project/src/.."), ("./bridge.js", "/project/src/./bridge.js"), ("../bridge.js", "/project/src/../bridge.js"), (".hidden/x", ".hidden/x"), ("..hidden/x", "..hidden/x"), ("bridge", "bridge"), ] { let definition = worklet_definition( &format!( "import call from '{source}'; export const handler = () => {{ 'main thread'; return call(); }};" ), "/project/src/test.js", ); let imports = definition.imports.unwrap(); let dependency = imports .iter() .find(|item| item.imported == "default") .unwrap(); assert_eq!(dependency.source, expected); } } #[test] fn should_exclude_captured_and_shadowed_imports_from_worklet_dependencies() { for source in [ "import { value } from './values.js'; export const handler = () => { 'main thread'; return value; };", "import { runOnBackground } from './bridge.js'; export const handler = (runOnBackground) => { 'main thread'; runOnBackground(() => {})(); };", ] { let definition = worklet_definition(source, "test.js"); let imports = definition.imports.unwrap(); assert_eq!(imports.len(), 1); assert_eq!(imports[0].imported, "registerWorklet"); } } #[test] fn should_preserve_string_named_definition_imports() { let definition = worklet_definition( "import { 'string-name' as call } from 'bridge'; export const handler = () => { 'main thread'; return call(); };", "test.js", ); let imports = definition.imports.unwrap(); let dependency = imports .iter() .find(|item| item.imported == "string-name") .unwrap(); assert_eq!(dependency.source, "bridge"); assert!(definition.code.contains(&format!("{}()", dependency.local))); } #[test] fn test_syntax_serialize_and_deserialize() { use serde_json::json; let json = json!({ "syntax": "typescript", "tsx": true, }); let s: Syntax = serde_json::from_value(json).unwrap(); // println!("{:?}", serde_json::to_string(&s)); assert!(s.typescript()); assert!(!s.decorators()); // default to false } #[test] fn should_report_runtime_requirements_from_each_transformed_module() { let options = TransformNodiffOptions { worklet: Either::A(true), css_scope: Either::A(false), ..Default::default() }; let worklet = transform_react_lynx_inner( r#" import '@lynx-js/react/worklet-runtime/init'; export function handler() { 'main thread'; return 42; } "# .into(), options.clone(), ); assert!(worklet.errors.is_empty()); assert!(worklet.runtime_requirements.main_thread_programmability); assert!(worklet.code.contains("@lynx-js/react/worklet-runtime/init")); assert_eq!(worklet.code.matches("__registerWorklet(").count(), 1); assert!(!worklet.code.contains("loadWorkletRuntime")); let plain = transform_react_lynx_inner("export function handler() { return 42; }".into(), options); assert!(plain.errors.is_empty()); assert!(!plain.runtime_requirements.main_thread_programmability); assert!(!plain.code.contains("worklet-runtime/init")); assert!(!plain.code.contains("registerWorkletInternal")); } #[test] fn should_preserve_injected_worklet_requirements_without_retransforming_its_body() { let result = transform_react_lynx_inner( "export const handler = () => { 'main thread'; return 42; };".into(), TransformNodiffOptions { worklet: Either::B(WorkletVisitorConfig { target: swc_plugins_shared::target_napi::TransformTarget::JS, ..Default::default() }), css_scope: Either::A(false), ..Default::default() }, ); assert!(result.errors.is_empty()); assert!(!result.runtime_requirements.main_thread_programmability); assert!(!result.code.contains("worklet-runtime/init")); let definitions = result.defines_for_worklet.unwrap(); assert_eq!(definitions.len(), 1); let definition = &definitions[0]; assert!( definition .runtime_requirements .as_ref() .unwrap() .main_thread_programmability ); assert!(!definition.code.contains("loadWorkletRuntime")); let injected = transform_react_lynx_inner( format!( "import {{ {} as {} }} from {:?};\n{}", definition.imports.as_ref().unwrap()[0].imported, definition.imports.as_ref().unwrap()[0].local, definition.imports.as_ref().unwrap()[0].source, definition.code ), TransformNodiffOptions { worklet: Either::A(true), css_scope: Either::A(false), ..Default::default() }, ); assert!(injected.errors.is_empty()); assert!(injected.defines_for_worklet.unwrap().is_empty()); assert_eq!(injected.code.matches("__registerWorklet(").count(), 1); assert!(injected.code.contains("return 42")); } #[test] fn should_return_no_runtime_requirement_when_parsing_fails() { let result = transform_react_lynx_inner( "export function handler( {".into(), TransformNodiffOptions { worklet: Either::A(true), ..Default::default() }, ); assert!(!result.errors.is_empty()); assert!(result.code.is_empty()); assert!(!result.runtime_requirements.main_thread_programmability); assert!(result.defines_for_worklet.is_none()); } #[test] fn should_preserve_active_empty_element_template_collector() { let collector = Rc::new(RefCell::new(vec![])); assert_eq!( take_element_templates(Some(collector)).unwrap().len(), 0, "an active ET transform must return Some([]), not None" ); } #[test] fn should_drain_partial_element_templates() { let collector = Rc::new(RefCell::new(vec![CoreElementTemplateAsset { template_id: "_et_test".into(), compiled_template: serde_json::json!({ "kind": "element", "type": "view" }), source_file: "test.js".into(), }])); let templates = take_element_templates(Some(collector.clone())).unwrap(); assert_eq!(templates.len(), 1); assert_eq!(templates[0].template_id, "_et_test"); assert!( collector.borrow().is_empty(), "collector should be drained exactly once" ); } }