@ 261027.7

261020.1 · 1d7e0126f3e601103d93586a6f872144f2789dad

chore: self-maintain Node.js features

reading declarations

Changes to deps/swc/bindings/. All files

deps/swc/bindings/.gitignore

deleted file mode 100644@@ -1 +0,0 @@-node_modules/\ No newline at end of file

deps/swc/bindings/README.md

deleted file mode 100644@@ -1,6 +0,0 @@-## SWC bindings--This folder contains actual bindings binary SWC will build for the supported platforms (`@swc/core`, `swc_cli`, `@swc/wasm`).--All the bindings binary uses publicly published `swc_core` SDK to build deterministic host binary for the specific changes, in result Cargo's workspace gets confused to select dependency versions if it belongs to the workspace contains unpublished packages. To avoid those problems, these bindings are not being built as part of the workspace.-

deps/swc/bindings/binding_core_node/Cargo.toml

deleted file mode 100644@@ -1,66 +0,0 @@-[package]-authors = ["강동윤 <kdy1997.dev@gmail.com>"]-build   = "build.rs"-edition = "2021"-exclude = ["artifacts.json", "index.node"]-license = "Apache-2.0"-name    = "binding_core_node"-publish = false-version = "0.2.0"--[lib]-bench      = false-crate-type = ["cdylib"]--[features]-default = ["swc_v1", "plugin"]-plugin = [-  "swc_core/plugin_backend_wasmer",-  "swc_core/plugin_transform_host_native",-  "swc_core/plugin_transform_host_native_filesystem_cache",-]-swc_v1 = ["swc_core/bundler_node_v1"]-swc_v2 = ["swc_core/bundler_node_v2"]--# Internal flag for testing purpose only.-__plugin_transform_vtest = [-  # We know what we're doing - enable internal features for testing fixture setup.-  "swc_core/__plugin_transform_host",-  "swc_core/__plugin_transform_host_schema_vtest",-  "swc_core/__plugin_transform_env_native",-]--[build-dependencies]-napi-build = { workspace = true }--[dependencies]-anyhow             = { workspace = true }-backtrace          = { workspace = true }-napi               = { workspace = true, features = ["napi3", "serde-json"] }-napi-derive        = { workspace = true, features = ["type-def"] }-par-core           = { workspace = true, features = ["chili"] }-path-clean         = { workspace = true }-rustc-hash         = { workspace = true }-serde              = { workspace = true, features = ["derive"] }-serde_json         = { workspace = true, features = ["unbounded_depth"] }-tracing            = { workspace = true, features = ["release_max_level_info"] }--swc_core = { path = "../../crates/swc_core", features = [-  "allocator_node",-  "ecma_ast",-  "ecma_minifier",-  "ecma_codegen",-  "ecma_ast_serde",-  "common_concurrent",-  "bundler",-  "ecma_loader",-  "ecma_helpers_inline",-  "ecma_transforms",-  "ecma_visit",-  "base_node",-  "base_concurrent",-  "base_flow",-  "base_module",-  "base_react_compiler",-] }-swc_malloc = { path = "../../crates/swc_malloc" }

deps/swc/bindings/binding_core_node/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.\ No newline at end of file

deps/swc/bindings/binding_core_node/build.rs

deleted file mode 100644@@ -1,29 +0,0 @@-use std::{-    env,-    fs::File,-    io::{BufWriter, Write},-    path::Path,-};--extern crate napi_build;--#[cfg(all(not(feature = "swc_v1"), not(feature = "swc_v2")))]-compile_error!("Please enable swc_v1 or swc_v2 feature");--#[cfg(all(feature = "swc_v1", feature = "swc_v2"))]-compile_error!("Features swc_v1 and swc_v2 are incompatible");--fn main() {-    let out_dir = env::var("OUT_DIR").expect("Outdir should exist");-    let dest_path = Path::new(&out_dir).join("triple.txt");-    let mut f =-        BufWriter::new(File::create(dest_path).expect("Failed to create target triple text"));-    write!(-        f,-        "{}",-        env::var("TARGET").expect("Target should be specified")-    )-    .expect("Failed to write target triple text");--    napi_build::setup();-}

deps/swc/bindings/binding_core_node/src/analyze.rs

deleted file mode 100644@@ -1,66 +0,0 @@-use std::sync::Arc;--use napi::{-    bindgen_prelude::{AbortSignal, AsyncTask, Buffer},-    Env, Task,-};-use swc_core::{-    base::{wasm_analysis::WasmAnalysisOptions, Compiler},-    common::{comments::SingleThreadedComments, FileName},-    node::MapErr,-};--use crate::{get_fresh_compiler, util::try_with};--pub struct AnalyzeTask {-    pub c: Arc<Compiler>,-    pub input: Option<String>,-    pub options: Buffer,-}--#[napi]-impl Task for AnalyzeTask {-    type JsValue = String;-    type Output = String;--    #[cfg_attr(debug_assertions, tracing::instrument(level = "trace", skip_all))]-    fn compute(&mut self) -> napi::Result<Self::Output> {-        let options: WasmAnalysisOptions = serde_json::from_slice(self.options.as_ref())?;--        try_with(self.c.cm.clone(), false, options.error_format, |handler| {-            let comments = SingleThreadedComments::default();--            let fm = self.c.cm.new_source_file(-                if let Some(filename) = options.filename.as_deref() {-                    FileName::Real(filename.into()).into()-                } else {-                    FileName::Anon.into()-                },-                self.input.take().unwrap(),-            );--            self.c.run_wasm_analysis(fm, handler, &options, &comments)-        })-        .convert_err()-    }--    fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(result)-    }-}--#[napi]-pub fn analyze(-    src: String,-    options: Buffer,-    signal: Option<AbortSignal>,-) -> napi::Result<AsyncTask<AnalyzeTask>> {-    crate::util::init_default_trace_subscriber();--    let task = AnalyzeTask {-        c: get_fresh_compiler(),-        input: Some(src),-        options,-    };-    Ok(AsyncTask::with_optional_signal(task, signal))-}

deps/swc/bindings/binding_core_node/src/ast_context.rs

deleted file mode 100644@@ -1,233 +0,0 @@-use anyhow::{bail, Context, Error};-use serde::{Deserialize, Serialize};-use swc_core::{-    base::Compiler,-    common::{BytePos, FileName, SourceFile, Span, DUMMY_SP},-    ecma::{-        ast::Program,-        visit::{VisitMut, VisitMutWith},-    },-    node::deserialize_json,-};--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct ProgramSourceContext {-    real_filename: Option<String>,-    source: String,-    start_pos: u32,-    end_pos: u32,-}--#[derive(Debug, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct ProgramEnvelope {-    program: Program,-    source_context: Option<ProgramSourceContext>,-}--#[derive(Debug)]-pub enum ProgramInput {-    Raw(Program),-    WithContext {-        program: Program,-        source_context: ProgramSourceContext,-    },-}--pub fn source_context_from_file(fm: &SourceFile) -> ProgramSourceContext {-    ProgramSourceContext {-        real_filename: match &*fm.name {-            FileName::Real(path) => Some(path.display().to_string()),-            _ => None,-        },-        source: fm.src.as_str().to_owned(),-        start_pos: fm.start_pos.0,-        end_pos: fm.end_pos.0,-    }-}--pub fn serialize_program(program: Program, fm: &SourceFile) -> Result<String, serde_json::Error> {-    serde_json::to_string(&ProgramEnvelope {-        program,-        source_context: Some(source_context_from_file(fm)),-    })-}--pub fn deserialize_program_input(json: &str) -> Result<ProgramInput, serde_json::Error> {-    if let Ok(envelope) = deserialize_json::<ProgramEnvelope>(json) {-        if let Some(source_context) = envelope.source_context {-            return Ok(ProgramInput::WithContext {-                program: envelope.program,-                source_context,-            });-        }--        return Ok(ProgramInput::Raw(envelope.program));-    }--    deserialize_json(json).map(ProgramInput::Raw)-}--pub fn prepare_program_with_context(-    c: &Compiler,-    mut program: Program,-    source_context: ProgramSourceContext,-) -> Result<(swc_core::common::sync::Lrc<SourceFile>, Program), Error> {-    let fm = c.cm.new_source_file(-        source_context.file_name().into(),-        source_context.source.clone(),-    );--    let expected_len = source_context-        .end_pos-        .checked_sub(source_context.start_pos)-        .context("invalid source context byte range")?;--    if fm.byte_length() != expected_len {-        bail!(-            "failed to restore source context because the source length changed while passing AST \-             between JavaScript and native code"-        );-    }--    rebase_program_spans(&mut program, &source_context, &fm)-        .context("failed to rebase AST spans to restored source context")?;--    Ok((fm, program))-}--fn rebase_program_spans(-    program: &mut Program,-    source_context: &ProgramSourceContext,-    fm: &SourceFile,-) -> Result<(), Error> {-    let old_start = source_context.start_pos;-    let old_end = source_context.end_pos;-    let new_start = fm.start_pos.0;-    let new_end = fm.end_pos.0;--    if old_start > old_end {-        bail!("invalid source context byte range: {old_start}..{old_end}");-    }--    program.visit_mut_with(&mut SpanRebaser {-        old_start,-        old_end,-        new_start,-        new_end,-    });--    Ok(())-}--impl ProgramSourceContext {-    fn file_name(&self) -> FileName {-        match &self.real_filename {-            Some(filename) => FileName::Real(filename.into()),-            None => FileName::Anon,-        }-    }-}--struct SpanRebaser {-    old_start: u32,-    old_end: u32,-    new_start: u32,-    new_end: u32,-}--impl SpanRebaser {-    fn rebase_pos(&self, pos: BytePos) -> Option<BytePos> {-        if pos.is_dummy() || pos.is_reserved_for_comments() || pos == BytePos::SYNTHESIZED {-            return Some(pos);-        }--        if pos.0 < self.old_start || pos.0 > self.old_end {-            return None;-        }--        let rebased = self.new_start.checked_add(pos.0 - self.old_start)?;-        if rebased > self.new_end {-            return None;-        }--        Some(BytePos(rebased))-    }--    fn rebase_span(&self, span: Span) -> Span {-        if span.is_dummy() {-            return span;-        }--        let Some(lo) = self.rebase_pos(span.lo) else {-            return DUMMY_SP;-        };-        let Some(hi) = self.rebase_pos(span.hi) else {-            return DUMMY_SP;-        };--        if lo.is_dummy() || hi.is_dummy() {-            return DUMMY_SP;-        }--        Span::new_with_checked(lo, hi)-    }-}--impl VisitMut for SpanRebaser {-    fn visit_mut_span(&mut self, span: &mut Span) {-        *span = self.rebase_span(*span);-    }-}--#[cfg(test)]-mod tests {-    use super::*;--    #[test]-    fn rebase_span_into_new_source_range() {-        let rebaser = SpanRebaser {-            old_start: 100,-            old_end: 140,-            new_start: 1,-            new_end: 41,-        };--        let span = rebaser.rebase_span(Span::new(BytePos(110), BytePos(125)));--        assert_eq!(span.lo, BytePos(11));-        assert_eq!(span.hi, BytePos(26));-    }--    #[test]-    fn drops_out_of_range_span() {-        let rebaser = SpanRebaser {-            old_start: 100,-            old_end: 140,-            new_start: 1,-            new_end: 41,-        };--        assert_eq!(-            rebaser.rebase_span(Span::new(BytePos(90), BytePos(125))),-            DUMMY_SP-        );-    }--    #[test]-    fn preserves_dummy_and_reserved_spans() {-        let rebaser = SpanRebaser {-            old_start: 100,-            old_end: 140,-            new_start: 1,-            new_end: 41,-        };--        assert_eq!(rebaser.rebase_span(DUMMY_SP), DUMMY_SP);-        assert_eq!(-            rebaser.rebase_span(Span::new(BytePos::PURE, BytePos::PURE)),-            Span::new(BytePos::PURE, BytePos::PURE)-        );-    }-}

deps/swc/bindings/binding_core_node/src/bundle.rs

deleted file mode 100644@@ -1,303 +0,0 @@-use std::{-    panic::{catch_unwind, AssertUnwindSafe},-    sync::Arc,-};--use anyhow::{bail, Error};-use napi::{-    bindgen_prelude::{AbortSignal, AsyncTask, Buffer},-    Env, Status, Task,-};-use rustc_hash::FxHashMap;-use serde::Deserialize;-use swc_core::{-    atoms::Atom,-    base::{-        config::SourceMapsConfig,-        resolver::{environment_resolver, paths_resolver},-        Compiler, PrintArgs, TransformOutput,-    },-    bundler::{BundleKind, Bundler, Load, ModuleRecord, Resolve},-    common::{Globals, Span, GLOBALS},-    ecma::{-        ast::{-            Bool, Expr, IdentName, KeyValueProp, Lit, MemberExpr, MemberProp, MetaPropExpr,-            MetaPropKind, PropName, Str,-        },-        loader::{TargetEnv, NODE_BUILTINS},-    },-    node::{get_deserialized, MapErr},-};--use crate::get_compiler;--struct ConfigItem {-    loader: Box<dyn Load>,-    resolver: Box<dyn Resolve>,-    static_items: StaticConfigItem,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-struct StaticConfigItem {-    #[cfg(feature = "swc_v1")]-    #[serde(flatten)]-    config: swc_core::bundler::node::v1::Config,-}--pub(crate) struct BundleTask {-    swc: Arc<swc_core::base::Compiler>,-    config: ConfigItem,-}--#[cfg(feature = "swc_v1")]-#[napi]-impl Task for BundleTask {-    type JsValue = FxHashMap<String, TransformOutput>;-    type Output = FxHashMap<String, TransformOutput>;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        let builtins = if let TargetEnv::Node = self.config.static_items.config.target {-            NODE_BUILTINS-                .iter()-                .copied()-                .map(Atom::from)-                .collect::<Vec<_>>()-        } else {-            Vec::new()-        };--        // Defaults to es3-        let codegen_target = self-            .config-            .static_items-            .config-            .codegen_target()-            .unwrap_or_default();--        let globals = Globals::default();-        GLOBALS.set(&globals, || {-            let res = catch_unwind(AssertUnwindSafe(|| {-                let mut bundler = Bundler::new(-                    &globals,-                    self.swc.cm.clone(),-                    &self.config.loader,-                    &self.config.resolver,-                    swc_core::bundler::Config {-                        require: true,-                        external_modules: builtins-                            .into_iter()-                            .chain(-                                self.config-                                    .static_items-                                    .config-                                    .external_modules-                                    .iter()-                                    .cloned(),-                            )-                            .collect(),-                        ..Default::default()-                    },-                    Box::new(Hook),-                );--                let result = bundler-                    .bundle(self.config.static_items.config.entry.clone().into())-                    .convert_err()?;--                let result = result-                    .into_iter()-                    .map(|bundle| match bundle.kind {-                        BundleKind::Named { name } | BundleKind::Lib { name } => {-                            Ok((name, bundle.module))-                        }-                        BundleKind::Dynamic => bail!("unimplemented: dynamic code splitting"),-                    })-                    .map(|res| {-                        res.and_then(|(k, m)| {-                            // TODO: Source map-                            let minify = self-                                .config-                                .static_items-                                .config-                                .options-                                .as_ref()-                                .map(|v| v.config.minify.into_bool())-                                .unwrap_or(false);--                            let output = self.swc.print(-                                &m,-                                PrintArgs {-                                    inline_sources_content: true,-                                    source_map: SourceMapsConfig::Bool(true),-                                    emit_source_map_columns: true,-                                    codegen_config: swc_core::ecma::codegen::Config::default()-                                        .with_target(codegen_target)-                                        .with_minify(minify),-                                    ..Default::default()-                                },-                            )?;--                            Ok((k, output))-                        })-                    })-                    .collect::<Result<_, _>>()-                    .convert_err()?;--                Ok(result)-            }));--            let err = match res {-                Ok(v) => return v,-                Err(err) => err,-            };--            if let Some(s) = err.downcast_ref::<String>() {-                return Err(napi::Error::new(-                    Status::GenericFailure,-                    format!("panic detected: {s}"),-                ));-            }--            Err(napi::Error::new(-                Status::GenericFailure,-                "panic detected".to_string(),-            ))-        })-    }--    fn resolve(&mut self, _env: Env, output: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(output)-    }-}--#[cfg(feature = "swc_v2")]-impl Task for BundleTask {-    type JsValue = FxHashMap<String, TransformOutput>;-    type Output = FxHashMap<String, TransformOutput>;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        todo!()-    }--    fn resolve(&mut self, env: Env, output: Self::Output) -> napi::Result<Self::JsValue> {-        todo!()-    }-}--#[cfg(feature = "swc_v1")]-#[napi(ts_return_type = "Promise<{ [index: string]: { code: string, map?: string } }>")]-pub(crate) fn bundle(-    conf_items: Buffer,-    signal: Option<AbortSignal>,-) -> napi::Result<AsyncTask<BundleTask>> {-    crate::util::init_default_trace_subscriber();--    let c: Arc<Compiler> = get_compiler();--    let static_items: StaticConfigItem = get_deserialized(&conf_items)?;--    let loader = Box::new(swc_core::bundler::node::loaders::swc::SwcLoader::new(-        c.clone(),-        static_items-            .config-            .options-            .as_ref()-            .cloned()-            .unwrap_or_else(|| {-                serde_json::from_value(serde_json::Value::Object(Default::default())).unwrap()-            }),-    ));--    let target_env = static_items.config.target;--    let paths = static_items.config.options.as_ref().map(|options| {-        let paths: Vec<(String, Vec<String>)> = options-            .config-            .jsc-            .paths-            .iter()-            .map(|(k, v)| (k.clone(), v.clone()))-            .collect();-        (options.config.jsc.base_url.clone(), paths)-    });--    let alias = static_items-        .config-        .alias-        .get(&target_env)-        .cloned()-        .unwrap_or_default();--    let resolver: Box<dyn Resolve> = if let Some((base_url, paths)) = paths {-        Box::new(paths_resolver(-            target_env,-            alias,-            base_url,-            paths,-            static_items.config.preserve_symlinks,-        ))-    } else {-        Box::new(environment_resolver(-            target_env,-            alias,-            static_items.config.preserve_symlinks,-        ))-    };--    Ok(AsyncTask::with_optional_signal(-        BundleTask {-            swc: c,-            config: ConfigItem {-                loader,-                resolver,-                static_items,-            },-        },-        signal,-    ))-}--#[cfg(feature = "swc_v2")]-#[napi]-pub(crate) fn bundle() -> napi::Result<AsyncTask<BundleTask>> {-    todo!()-}--struct Hook;--impl swc_core::bundler::Hook for Hook {-    fn get_import_meta_props(-        &self,-        span: Span,-        module_record: &ModuleRecord,-    ) -> Result<Vec<KeyValueProp>, Error> {-        let file_name = module_record.file_name.to_string();--        Ok(vec![-            KeyValueProp {-                key: PropName::Ident(IdentName::new("url".into(), span)),-                value: Box::new(Expr::Lit(Lit::Str(Str {-                    span,-                    raw: None,-                    value: file_name.into(),-                }))),-            },-            KeyValueProp {-                key: PropName::Ident(IdentName::new("main".into(), span)),-                value: Box::new(if module_record.is_entry {-                    Expr::Member(MemberExpr {-                        span,-                        obj: Box::new(Expr::MetaProp(MetaPropExpr {-                            span,-                            kind: MetaPropKind::ImportMeta,-                        })),-                        prop: MemberProp::Ident(IdentName::new("main".into(), span)),-                    })-                } else {-                    Expr::Lit(Lit::Bool(Bool { span, value: false }))-                }),-            },-        ])-    }-}

deps/swc/bindings/binding_core_node/src/lib.rs

deleted file mode 100644@@ -1,77 +0,0 @@-#![recursion_limit = "2048"]-#![allow(dead_code)]--#[macro_use]-extern crate napi_derive;--extern crate swc_malloc;--use std::{env, panic::set_hook, sync::Arc};--use backtrace::Backtrace;-use swc_core::{-    base::Compiler,-    common::{sync::Lazy, FilePathMapping, SourceMap},-};--#[cfg(feature = "plugin")]-mod analyze;-mod ast_context;-mod bundle;-mod minify;-mod parse;-mod print;-mod transform;-mod util;--static COMPILER: Lazy<Arc<Compiler>> = Lazy::new(|| {-    let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));--    Arc::new(Compiler::new(cm))-});--#[napi_derive::module_init]-fn init() {-    if cfg!(debug_assertions) || env::var("SWC_DEBUG").unwrap_or_default() == "1" {-        set_hook(Box::new(|panic_info| {-            let backtrace = Backtrace::new();-            println!("Panic: {panic_info:?}\nBacktrace: {backtrace:?}");-        }));-    }-}--fn get_compiler() -> Arc<Compiler> {-    COMPILER.clone()-}--fn get_fresh_compiler() -> Arc<Compiler> {-    let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));--    Arc::new(Compiler::new(cm))-}--#[napi(js_name = "Compiler")]-pub struct JsCompiler {-    _compiler: Arc<Compiler>,-}--#[napi]-impl JsCompiler {-    #[napi(constructor)]-    #[allow(clippy::new_without_default)]-    #[cfg_attr(debug_assertions, tracing::instrument(level = "info", skip_all))]-    pub fn new() -> Self {-        Self {-            _compiler: COMPILER.clone(),-        }-    }-}--pub type ArcCompiler = Arc<Compiler>;--/// Hack for `Type Generation`-#[napi(object)]-pub struct TransformOutput {-    pub code: String,-    pub map: Option<String>,-}

deps/swc/bindings/binding_core_node/src/minify.rs

deleted file mode 100644@@ -1,151 +0,0 @@-use std::sync::Arc;--use napi::{-    bindgen_prelude::{AbortSignal, AsyncTask, Buffer, External},-    Task,-};-use rustc_hash::FxHashMap;-use swc_core::{-    base::{-        config::{ErrorFormat, JsMinifyOptions},-        JsMinifyExtras, TransformOutput,-    },-    common::{sync::Lrc, FileName, SourceFile, SourceMap},-    ecma::minifier::option::{MangleCache, SimpleMangleCache},-    node::{deserialize_json, get_deserialized, MapErr},-};--use crate::{get_fresh_compiler, util::try_with};--#[napi(object, object_to_js = false)]-pub struct NapiMinifyExtra {-    #[napi(ts_type = "object")]-    pub mangle_name_cache: Option<&'static NameMangleCache>,-}--struct MinifyTask {-    c: Arc<swc_core::base::Compiler>,-    input: Option<MinifyTarget>,-    options: String,-    extras: JsMinifyExtras,-}--enum MinifyTarget {-    /// Code to minify.-    Single(String),-    /// `FxHashMap<String, String>`-    Json(String),-}--impl MinifyTarget {-    fn to_file(&self, cm: Lrc<SourceMap>) -> Lrc<SourceFile> {-        match self {-            MinifyTarget::Single(code) => cm.new_source_file(FileName::Anon.into(), code.clone()),-            MinifyTarget::Json(json) => {-                let codes: FxHashMap<String, String> =-                    serde_json::from_str(json).expect("Invalid JSON");-                assert_eq!(-                    codes.len(),-                    1,-                    "swc.minify does not support concatting multiple files yet"-                );--                let (filename, code) = codes.iter().next().unwrap();--                cm.new_source_file(FileName::Real(filename.clone().into()).into(), code.clone())-            }-        }-    }-}--#[napi]-impl Task for MinifyTask {-    type JsValue = TransformOutput;-    type Output = TransformOutput;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        let input = self.input.take().unwrap();-        let options: JsMinifyOptions = deserialize_json(&self.options)?;--        try_with(self.c.cm.clone(), false, ErrorFormat::Normal, |handler| {-            let fm = input.to_file(self.c.cm.clone());--            self.c.minify(fm, handler, &options, self.extras.clone())-        })-        .convert_err()-    }--    fn resolve(&mut self, _env: napi::Env, output: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(output)-    }-}--type NameMangleCache = External<Arc<dyn MangleCache>>;--#[napi(ts_return_type = "object")]-fn new_mangle_name_cache() -> NameMangleCache {-    let cache = Arc::new(SimpleMangleCache::default());-    External::new(cache)-}--#[napi]-fn minify(-    code: Buffer,-    opts: Buffer,-    is_json: bool,-    extras: NapiMinifyExtra,-    signal: Option<AbortSignal>,-) -> AsyncTask<MinifyTask> {-    crate::util::init_default_trace_subscriber();-    let code = String::from_utf8_lossy(code.as_ref()).into_owned();-    let options = String::from_utf8_lossy(opts.as_ref()).into_owned();-    let extras = JsMinifyExtras::default()-        .with_mangle_name_cache(extras.mangle_name_cache.map(|s| (*s).clone()));--    let c = get_fresh_compiler();--    let task = MinifyTask {-        c,-        input: Some(if is_json {-            MinifyTarget::Json(code)-        } else {-            MinifyTarget::Single(code)-        }),-        options,-        extras,-    };--    AsyncTask::with_optional_signal(task, signal)-}--#[napi]-pub fn minify_sync(-    code: Buffer,-    opts: Buffer,-    is_json: bool,-    extras: NapiMinifyExtra,-) -> napi::Result<TransformOutput> {-    crate::util::init_default_trace_subscriber();-    let code = String::from_utf8_lossy(code.as_ref()).into_owned();-    let input = if is_json {-        MinifyTarget::Json(code)-    } else {-        MinifyTarget::Single(code)-    };-    let opts = get_deserialized(opts)?;-    let extras = JsMinifyExtras::default()-        .with_mangle_name_cache(extras.mangle_name_cache.map(|s| (*s).clone()));--    let c = get_fresh_compiler();--    let fm = input.to_file(c.cm.clone());--    try_with(-        c.cm.clone(),-        false,-        // TODO(kdy1): Maybe make this configurable?-        ErrorFormat::Normal,-        |handler| c.minify(fm, handler, &opts, extras),-    )-    .convert_err()-}

deps/swc/bindings/binding_core_node/src/parse.rs

deleted file mode 100644@@ -1,281 +0,0 @@-use std::{-    path::{Path, PathBuf},-    sync::Arc,-};--use anyhow::Context as _;-use napi::{-    bindgen_prelude::{AbortSignal, AsyncTask, Buffer},-    Either, Env, Task,-};-use swc_core::{-    base::{-        config::{ErrorFormat, ParseOptions},-        Compiler, SwcComments,-    },-    common::{comments::Comments, FileName, Mark},-    ecma::{transforms::base::resolver, visit::VisitMutWith},-    node::{deserialize_json, get_deserialized, MapErr},-};--use crate::{ast_context::serialize_program, get_fresh_compiler, util::try_with};--// ----- Parsing -------pub struct ParseTask {-    pub c: Arc<Compiler>,-    pub filename: FileName,-    pub src: String,-    pub options: String,-}--pub struct ParseFileTask {-    pub c: Arc<Compiler>,-    pub path: PathBuf,-    pub options: String,-}--#[napi]-impl Task for ParseTask {-    type JsValue = String;-    type Output = String;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        let options: ParseOptions = deserialize_json(&self.options)?;-        let fm = self-            .c-            .cm-            .new_source_file(self.filename.clone().into(), self.src.clone());--        let local_comments = SwcComments::default();-        let comments = if options.comments {-            Some(&local_comments as &dyn Comments)-        } else {-            None-        };--        let program = try_with(self.c.cm.clone(), false, ErrorFormat::Normal, |handler| {-            let mut p = self.c.parse_js(-                fm.clone(),-                handler,-                options.target,-                options.syntax,-                options.is_module,-                comments,-            )?;--            p.visit_mut_with(&mut resolver(-                Mark::new(),-                Mark::new(),-                options.syntax.typescript(),-            ));--            Ok(p)-        })-        .convert_err()?;--        let ast_json = serialize_program(program, &fm)?;--        Ok(ast_json)-    }--    fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(result)-    }-}--#[napi]-impl Task for ParseFileTask {-    type JsValue = String;-    type Output = String;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        let (program, fm) = try_with(self.c.cm.clone(), false, ErrorFormat::Normal, |handler| {-            self.c.run(|| {-                let options: ParseOptions = deserialize_json(&self.options)?;--                let fm = self-                    .c-                    .cm-                    .load_file(&self.path)-                    .context("failed to read module")?;--                let local_comments = SwcComments::default();-                let comments = if options.comments {-                    Some(&local_comments as &dyn Comments)-                } else {-                    None-                };--                let mut p = self.c.parse_js(-                    fm.clone(),-                    handler,-                    options.target,-                    options.syntax,-                    options.is_module,-                    comments,-                )?;--                p.visit_mut_with(&mut resolver(-                    Mark::new(),-                    Mark::new(),-                    options.syntax.typescript(),-                ));--                Ok((p, fm))-            })-        })-        .convert_err()?;--        let ast_json = serialize_program(program, &fm)?;--        Ok(ast_json)-    }--    fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(result)-    }-}--fn stringify(src: Either<Buffer, String>) -> String {-    match src {-        Either::A(src) => String::from_utf8_lossy(src.as_ref()).into_owned(),-        Either::B(src) => src,-    }-}--#[napi]-pub fn parse(-    src: Either<Buffer, String>,-    options: Buffer,-    filename: Option<String>,-    signal: Option<AbortSignal>,-) -> AsyncTask<ParseTask> {-    crate::util::init_default_trace_subscriber();--    let c = get_fresh_compiler();-    let src = stringify(src);-    let options = String::from_utf8_lossy(options.as_ref()).into_owned();-    let filename = if let Some(value) = filename {-        FileName::Real(value.into())-    } else {-        FileName::Anon-    };--    AsyncTask::with_optional_signal(-        ParseTask {-            c,-            filename,-            src,-            options,-        },-        signal,-    )-}--#[napi]-pub fn parse_sync(-    src: Either<Buffer, String>,-    opts: Buffer,-    filename: Option<String>,-) -> napi::Result<String> {-    crate::util::init_default_trace_subscriber();--    let c = get_fresh_compiler();-    let src = stringify(src);-    let options: ParseOptions = get_deserialized(&opts)?;-    let filename = if let Some(value) = filename {-        FileName::Real(value.into())-    } else {-        FileName::Anon-    };--    let (program, fm) = try_with(c.cm.clone(), false, ErrorFormat::Normal, |handler| {-        c.run(|| {-            let fm = c.cm.new_source_file(filename.into(), src);--            let local_comments = SwcComments::default();-            let comments = if options.comments {-                Some(&local_comments as &dyn Comments)-            } else {-                None-            };--            let mut p = c.parse_js(-                fm.clone(),-                handler,-                options.target,-                options.syntax,-                options.is_module,-                comments,-            )?;--            p.visit_mut_with(&mut resolver(-                Mark::new(),-                Mark::new(),-                options.syntax.typescript(),-            ));--            Ok((p, fm))-        })-    })-    .convert_err()?;--    Ok(serialize_program(program, &fm)?)-}--#[napi]-pub fn parse_file_sync(path: String, opts: Buffer) -> napi::Result<String> {-    crate::util::init_default_trace_subscriber();-    let c = get_fresh_compiler();-    let options: ParseOptions = get_deserialized(&opts)?;--    let (program, fm) = {-        try_with(c.cm.clone(), false, ErrorFormat::Normal, |handler| {-            let fm =-                c.cm.load_file(Path::new(path.as_str()))-                    .context("failed to read program file")?;--            let local_comments = SwcComments::default();-            let comments = if options.comments {-                Some(&local_comments as &dyn Comments)-            } else {-                None-            };--            let mut p = c.parse_js(-                fm.clone(),-                handler,-                options.target,-                options.syntax,-                options.is_module,-                comments,-            )?;-            p.visit_mut_with(&mut resolver(-                Mark::new(),-                Mark::new(),-                options.syntax.typescript(),-            ));--            Ok((p, fm))-        })-    }-    .convert_err()?;--    Ok(serialize_program(program, &fm)?)-}--#[napi]-pub fn parse_file(-    path: String,-    options: Buffer,-    signal: Option<AbortSignal>,-) -> AsyncTask<ParseFileTask> {-    crate::util::init_default_trace_subscriber();--    let c = get_fresh_compiler();-    let path = PathBuf::from(&path);-    let options = String::from_utf8_lossy(options.as_ref()).into_owned();--    AsyncTask::with_optional_signal(ParseFileTask { c, path, options }, signal)-}

deps/swc/bindings/binding_core_node/src/print.rs

deleted file mode 100644@@ -1,145 +0,0 @@-use std::sync::Arc;--use anyhow::Error;-use napi::{-    bindgen_prelude::{AbortSignal, AsyncTask, Buffer},-    Env, Task,-};-use swc_core::{-    base::{-        config::{Options, SourceMapsConfig},-        Compiler, PrintArgs, TransformOutput,-    },-    common::GLOBALS,-    ecma::ast::{EsVersion, Program},-    node::{deserialize_json, get_deserialized, MapErr},-};--use crate::{-    ast_context::{deserialize_program_input, prepare_program_with_context, ProgramInput},-    get_compiler, get_fresh_compiler,-};--// ----- Printing -------pub struct PrintTask {-    pub c: Arc<Compiler>,-    pub program_json: String,-    pub options: String,-}--fn compiler_for_program_input(-    program_input: &ProgramInput,-    fallback: Arc<Compiler>,-) -> Arc<Compiler> {-    match program_input {-        ProgramInput::WithContext { .. } => get_fresh_compiler(),-        ProgramInput::Raw(_) => fallback,-    }-}--fn prepare_program_for_print(c: &Compiler, program_input: ProgramInput) -> Result<Program, Error> {-    match program_input {-        ProgramInput::WithContext {-            program,-            source_context,-        } => prepare_program_with_context(c, program, source_context).map(|(_, program)| program),-        ProgramInput::Raw(program) => Ok(program),-    }-}--#[napi]-impl Task for PrintTask {-    type JsValue = TransformOutput;-    type Output = TransformOutput;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        let program_input = deserialize_program_input(&self.program_json)?;-        let options: Options = deserialize_json(&self.options)?;-        let c = compiler_for_program_input(&program_input, self.c.clone());-        let program = prepare_program_for_print(&c, program_input).convert_err()?;--        GLOBALS.set(&Default::default(), || {-            c.print(-                &program,-                PrintArgs {-                    output_path: options.output_path.clone(),-                    inline_sources_content: true,-                    source_map: options-                        .source_maps-                        .clone()-                        .unwrap_or(SourceMapsConfig::Bool(false)),-                    emit_source_map_columns: options.config.emit_source_map_columns.into_bool(),-                    codegen_config: swc_core::ecma::codegen::Config::default()-                        .with_target(options.config.jsc.target.unwrap_or(EsVersion::Es2020))-                        .with_minify(options.config.minify.into_bool()),-                    source_file_name: Some(&options.filename),-                    ..Default::default()-                },-            )-            .convert_err()-        })-    }--    fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(result)-    }-}--#[napi]-pub fn print(-    program_json: String,-    options: Buffer,-    signal: Option<AbortSignal>,-) -> napi::Result<AsyncTask<PrintTask>> {-    crate::util::init_default_trace_subscriber();--    let c = get_compiler();-    let options = String::from_utf8_lossy(&options).into_owned();--    Ok(AsyncTask::with_optional_signal(-        PrintTask {-            c,-            program_json,-            options,-        },-        signal,-    ))-}--#[napi]-pub fn print_sync(program: String, options: Buffer) -> napi::Result<TransformOutput> {-    crate::util::init_default_trace_subscriber();--    let c = get_compiler();--    let program_input = deserialize_program_input(program.as_str())?;--    let options: Options = get_deserialized(&options)?;-    let c = compiler_for_program_input(&program_input, c);-    let program = prepare_program_for_print(&c, program_input).convert_err()?;--    // Defaults to es3-    let codegen_target = options.codegen_target().unwrap_or_default();--    GLOBALS.set(&Default::default(), || {-        c.print(-            &program,-            PrintArgs {-                output_path: options.output_path,-                inline_sources_content: true,-                source_map: options-                    .source_maps-                    .clone()-                    .unwrap_or(SourceMapsConfig::Bool(false)),-                emit_source_map_columns: options.config.emit_source_map_columns.into_bool(),-                codegen_config: swc_core::ecma::codegen::Config::default()-                    .with_target(codegen_target)-                    .with_minify(options.config.minify.into_bool()),-                source_file_name: Some(&options.filename),-                ..Default::default()-            },-        )-        .convert_err()-    })-}

deps/swc/bindings/binding_core_node/src/transform.rs

deleted file mode 100644@@ -1,279 +0,0 @@-use std::{-    path::{Path, PathBuf},-    sync::Arc,-};--use anyhow::{Context as _, Error};-use napi::{-    bindgen_prelude::{AbortSignal, AsyncTask, Buffer},-    Env, Task,-};-use path_clean::clean;-use swc_core::{-    base::{config::Options, Compiler, TransformOutput},-    common::{comments::SingleThreadedComments, errors::Handler, FileName},-    ecma::ast::noop_pass,-    node::{get_deserialized, MapErr},-};--use crate::{-    ast_context::{deserialize_program_input, prepare_program_with_context, ProgramInput},-    get_compiler, get_fresh_compiler,-    util::try_with,-};--/// Input to transform-#[derive(Debug)]-pub enum Input {-    /// json string-    Program(String),-    /// Raw source code.-    Source { src: String },-    /// File-    File(PathBuf),-}--pub struct TransformTask {-    pub c: Arc<Compiler>,-    pub input: Input,-    pub options: Buffer,-}--fn compiler_for_program_input(-    program_input: &ProgramInput,-    fallback: Arc<Compiler>,-) -> Arc<Compiler> {-    match program_input {-        ProgramInput::WithContext { .. } => get_fresh_compiler(),-        ProgramInput::Raw(_) => fallback,-    }-}--fn process_program_input(-    c: &Compiler,-    handler: &Handler,-    program_input: ProgramInput,-    options: &Options,-) -> Result<TransformOutput, Error> {-    match program_input {-        ProgramInput::WithContext {-            program,-            source_context,-        } => {-            let (fm, program) = prepare_program_with_context(c, program, source_context)?;--            c.process_js_with_custom_pass(-                fm,-                Some(program),-                handler,-                options,-                SingleThreadedComments::default(),-                |_| noop_pass(),-                |_| noop_pass(),-            )-        }-        ProgramInput::Raw(program) => c.process_js(handler, program, options),-    }-}--#[napi]-impl Task for TransformTask {-    type JsValue = TransformOutput;-    type Output = TransformOutput;--    #[cfg_attr(debug_assertions, tracing::instrument(level = "trace", skip_all))]-    fn compute(&mut self) -> napi::Result<Self::Output> {-        let mut options: Options = serde_json::from_slice(self.options.as_ref())?;-        if !options.filename.is_empty() {-            options.config.adjust(Path::new(&options.filename));-        }--        let error_format = options.experimental.error_format.unwrap_or_default();--        match &self.input {-            Input::Program(s) => {-                let program_input = deserialize_program_input(s)?;-                let c = compiler_for_program_input(&program_input, self.c.clone());--                try_with(-                    c.cm.clone(),-                    !options.config.error.filename.into_bool(),-                    error_format,-                    |handler| c.run(|| process_program_input(&c, handler, program_input, &options)),-                )-                .convert_err()-            }--            _ => try_with(-                self.c.cm.clone(),-                !options.config.error.filename.into_bool(),-                error_format,-                |handler| {-                    self.c.run(|| match &self.input {-                        Input::Program(_) => unreachable!("Program input is handled above"),--                        Input::File(ref path) => {-                            let fm = self.c.cm.load_file(path).context("failed to load file")?;-                            self.c.process_js_file(fm, handler, &options)-                        }--                        Input::Source { src } => {-                            let fm = self.c.cm.new_source_file(-                                if options.filename.is_empty() {-                                    FileName::Anon.into()-                                } else {-                                    FileName::Real(options.filename.clone().into()).into()-                                },-                                src.clone(),-                            );--                            self.c.process_js_file(fm, handler, &options)-                        }-                    })-                },-            )-            .convert_err(),-        }-    }--    fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(result)-    }-}--#[napi]-#[cfg_attr(debug_assertions, tracing::instrument(level = "trace", skip_all))]-pub fn transform(-    src: String,-    is_module: bool,-    options: Buffer,-    signal: Option<AbortSignal>,-) -> napi::Result<AsyncTask<TransformTask>> {-    crate::util::init_default_trace_subscriber();--    let (input, c) = if is_module {-        (Input::Program(src), get_compiler())-    } else {-        (Input::Source { src }, get_fresh_compiler())-    };--    let task = TransformTask { c, input, options };-    Ok(AsyncTask::with_optional_signal(task, signal))-}--#[napi]-#[cfg_attr(debug_assertions, tracing::instrument(level = "trace", skip_all))]-pub fn transform_sync(s: String, is_module: bool, opts: Buffer) -> napi::Result<TransformOutput> {-    crate::util::init_default_trace_subscriber();--    let mut options: Options = get_deserialized(&opts)?;--    if !options.filename.is_empty() {-        options.config.adjust(Path::new(&options.filename));-    }--    let error_format = options.experimental.error_format.unwrap_or_default();--    if is_module {-        let program_input = deserialize_program_input(s.as_str())?;-        let c = compiler_for_program_input(&program_input, get_compiler());--        try_with(-            c.cm.clone(),-            !options.config.error.filename.into_bool(),-            error_format,-            |handler| c.run(|| process_program_input(&c, handler, program_input, &options)),-        )-        .convert_err()-    } else {-        let c = get_fresh_compiler();--        try_with(-            c.cm.clone(),-            !options.config.error.filename.into_bool(),-            error_format,-            |handler| {-                c.run(|| {-                    let fm = c.cm.new_source_file(-                        if options.filename.is_empty() {-                            FileName::Anon.into()-                        } else {-                            FileName::Real(options.filename.clone().into()).into()-                        },-                        s,-                    );-                    c.process_js_file(fm, handler, &options)-                })-            },-        )-        .convert_err()-    }-}--#[napi]-#[cfg_attr(debug_assertions, tracing::instrument(level = "trace", skip_all))]-pub fn transform_file(-    src: String,-    _is_module: bool,-    options: Buffer,-    signal: Option<AbortSignal>,-) -> napi::Result<AsyncTask<TransformTask>> {-    crate::util::init_default_trace_subscriber();--    let c = get_fresh_compiler();--    let path = clean(&src);-    let task = TransformTask {-        c,-        input: Input::File(path),-        options,-    };-    Ok(AsyncTask::with_optional_signal(task, signal))-}--#[napi]-pub fn transform_file_sync(-    s: String,-    is_module: bool,-    opts: Buffer,-) -> napi::Result<TransformOutput> {-    crate::util::init_default_trace_subscriber();--    let mut options: Options = get_deserialized(&opts)?;--    if !options.filename.is_empty() {-        options.config.adjust(Path::new(&options.filename));-    }--    let error_format = options.experimental.error_format.unwrap_or_default();--    if is_module {-        let program_input = deserialize_program_input(s.as_str())?;-        let c = compiler_for_program_input(&program_input, get_compiler());--        try_with(-            c.cm.clone(),-            !options.config.error.filename.into_bool(),-            error_format,-            |handler| c.run(|| process_program_input(&c, handler, program_input, &options)),-        )-        .convert_err()-    } else {-        let c = get_fresh_compiler();--        try_with(-            c.cm.clone(),-            !options.config.error.filename.into_bool(),-            error_format,-            |handler| {-                c.run(|| {-                    let fm =-                        c.cm.load_file(Path::new(&s))-                            .context("failed to load file")?;-                    c.process_js_file(fm, handler, &options)-                })-            },-        )-        .convert_err()-    }-}

deps/swc/bindings/binding_core_node/src/util.rs

deleted file mode 100644@@ -1,72 +0,0 @@-#![deny(warnings)]--use std::panic::{catch_unwind, AssertUnwindSafe};--use anyhow::{anyhow, Error};-use napi::Env;-use swc_core::{-    base::{config::ErrorFormat, try_with_handler},-    common::{errors::Handler, sync::Lrc, SourceMap, GLOBALS},-};--static TARGET_TRIPLE: &str = include_str!(concat!(env!("OUT_DIR"), "/triple.txt"));--#[napi]-pub fn get_target_triple() -> napi::Result<String> {-    Ok(TARGET_TRIPLE.to_string())-}--#[napi]-pub fn init_custom_trace_subscriber(-    _env: Env,-    _trace_out_file_path: Option<String>,-) -> napi::Result<()> {-    Ok(())-}--#[cfg_attr(debug_assertions, tracing::instrument(level = "trace", skip_all))]-pub fn try_with<F, Ret>(-    cm: Lrc<SourceMap>,-    skip_filename: bool,-    _error_format: ErrorFormat,-    op: F,-) -> Result<Ret, Error>-where-    F: FnOnce(&Handler) -> Result<Ret, Error>,-{-    GLOBALS-        .set(&Default::default(), || {-            try_with_handler(-                cm,-                swc_core::base::HandlerOpts {-                    skip_filename,-                    ..Default::default()-                },-                |handler| {-                    //-                    let result = catch_unwind(AssertUnwindSafe(|| op(handler)));--                    let p = match result {-                        Ok(v) => return v,-                        Err(v) => v,-                    };--                    if let Some(s) = p.downcast_ref::<String>() {-                        Err(anyhow!("failed to handle: {s}"))-                    } else if let Some(s) = p.downcast_ref::<&str>() {-                        Err(anyhow!("failed to handle: {s}"))-                    } else {-                        Err(anyhow!("failed to handle with unknown panic message"))-                    }-                },-            )-        })-        .map_err(|e| e.to_pretty_error())-}--// This was originally under swc_nodejs_common, but this is not a public-// interface for the custom binary - they should choose own trace initialization-// instead. Will keep as hidden for now until there's proper usecase.--/// Deprecated no-op kept for compatibility with existing binding entrypoints.-pub fn init_default_trace_subscriber() {}

deps/swc/bindings/binding_core_wasm/Cargo.toml

deleted file mode 100644@@ -1,58 +0,0 @@-[package]-authors     = ["강동윤 <kdy1997.dev@gmail.com>"]-description = "wasm module for swc"-edition     = { workspace = true }-license     = { workspace = true }-name        = "binding_core_wasm"-publish     = false-repository  = { workspace = true }-version     = "1.16.18"--[lib]-bench      = false-crate-type = ["cdylib"]--[features]-__plugin = []-default  = ["swc_v1"]-swc_v1   = []-swc_v2   = []-# This feature exists to allow cargo operations-# [TODO]: this is disabled due to signature mismatch between host_native and host_js,-# which causes build errors like-# .call(&mut self.store, ptr.0, ptr.1)-#   |                  ^^^^ the trait `NativeWasmTypeInto` is not implemented for `u32`-#   |-#   = help: the following other types implement trait `NativeWasmTypeInto`:-#             f32-#             f64-#             i32-#             i64-#             u128-plugin = []--[dependencies]-anyhow = { workspace = true }-getrandom = { workspace = true, features = ["wasm_js"] }-serde = { workspace = true, features = ["derive"] }-serde-wasm-bindgen = { workspace = true }-swc_core = { path = "../../crates/swc_core", features = [-  "ecma_ast_serde",-  "ecma_codegen",-  "binding_macro_wasm",-  "ecma_transforms",-  "ecma_visit",-  "ecma_helpers_inline",-  "ecma_lints",-  "base_module",-  "base_react_compiler",-] }-tracing = { workspace = true, features = ["max_level_off"] }-wasm-bindgen = { workspace = true, features = ["enable-interning"] }--[package.metadata.wasm-pack.profile.release]-wasm-opt = false--[package.metadata.cargo-shear]-# ignored, as they are only used to enable features-ignored = ["getrandom", "anyhow", "serde-wasm-bindgen"]

deps/swc/bindings/binding_core_wasm/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.\ No newline at end of file

deps/swc/bindings/binding_core_wasm/example/.gitignore

deleted file mode 100644@@ -1 +0,0 @@-node_modules

deps/swc/bindings/binding_core_wasm/example/index.js

deleted file mode 100644@@ -1,47 +0,0 @@-let settings = {-    jsc: {-        target: "es2016",-        parser: {-            syntax: "ecmascript",-            jsx: true,-            dynamicImport: false,-            numericSeparator: false,-            privateMethod: false,-            functionBind: false,-            exportDefaultFrom: false,-            exportNamespaceFrom: false,-            decorators: false,-            decoratorsBeforeExport: false,-            topLevelAwait: false,-            importMeta: false,-        },-    },-};--let code = `-let a = 1;-let b = {-    c: {-        d: 1-    }--};-console.log(b?.c?.d);--let MyComponent = () => {-    return (<div a={10}>-        <p>Hello World!</p>-    </div>);-}-`;--const swc = import("./pkg/wasm.js");-swc.then((swc) => {-    console.log("SWC Loaded", swc);-    let result = swc.transformSync(code, settings);-    console.log("result from transformSync", result);-    console.log(result.code);-    document.getElementById("result").innerHTML =-        "<xmp>" + result.code + "</xmp>";-    document.getElementById("source").innerHTML = "<xmp>" + code + "</xmp>";-});

deps/swc/bindings/binding_core_wasm/example/package.json

deleted file mode 100644@@ -1,14 +0,0 @@-{-    "scripts": {-        "copy-files": "copyfiles ../pkg/* ./pkg",-        "dev-server": "webpack-dev-server",-        "serve": "run-s copy-files dev-server"-    },-    "devDependencies": {-        "copyfiles": "^2.3.0",-        "npm-run-all2": "^5.0.0",-        "webpack": "^4.25.1",-        "webpack-cli": "^3.1.2",-        "webpack-dev-server": "^3.1.10"-    }-}

deps/swc/bindings/binding_core_wasm/example/readme.txt

deleted file mode 100644@@ -1,21 +0,0 @@-To run this example, you first need to build swc for the web:--cd swc/wasm-./scripts/build_web_release.sh--Then run npm install:--cd swc/wasm/example-npm install--Finally, start the webpack-dev-server:--cd swc/wasm/example-npm run serve--Browse to http://localhost:8080-----

deps/swc/bindings/binding_core_wasm/example/webpack.config.js

deleted file mode 100644@@ -1,10 +0,0 @@-const path = require("path");--module.exports = {-    entry: "./index.js",-    output: {-        path: path.resolve(__dirname, "dist"),-        filename: "index.js",-    },-    mode: "development",-};

deps/swc/bindings/binding_core_wasm/package.json

deleted file mode 100644@@ -1,5 +0,0 @@-{-    "devDependencies": {-        "@rstest/core": "0.7.9"-    }-}

deps/swc/bindings/binding_core_wasm/rstest.config.mjs

deleted file mode 100644@@ -1,4 +0,0 @@-export default {-    include: ["__tests__/**/*.{js,jsx,ts,tsx}"],-    globals: true,-};

deps/swc/bindings/binding_core_wasm/scripts/test.sh

deleted file mode 100755@@ -1,6 +0,0 @@-#!/usr/bin/env bash--set -eu--wasm-pack build --out-name wasm --release --scope=swc --target nodejs-npx rstest $@\ No newline at end of file

deps/swc/bindings/binding_core_wasm/src/lib.rs

deleted file mode 100644@@ -1,54 +0,0 @@-use swc_core::binding_macros::{-    build_minify, build_minify_sync, build_parse, build_parse_sync, build_print, build_print_sync,-    build_transform, build_transform_sync,-};-use wasm_bindgen::prelude::*;-mod types;--/// Custom interface definitions for the @swc/wasm's public interface instead of-/// auto generated one, which is not reflecting most of types in detail.-#[wasm_bindgen(typescript_custom_section)]-const INTERFACE_DEFINITIONS: &'static str = r#"-export function minify(src: string, opts?: JsMinifyOptions): Promise<Output>;-export function minifySync(code: string, opts?: JsMinifyOptions): Output;--export function parse(src: string, options: ParseOptions & {-    isModule: false | "commonjs";-}): Promise<Script>;-export function parse(src: string, options?: ParseOptions): Promise<Module>;-export function parseSync(src: string, options: ParseOptions & {-    isModule: false | "commonjs";-}): Script;-export function parseSync(src: string, options?: ParseOptions): Module;--export function print(m: Program, options?: Options): Promise<Output>;-export function printSync(m: Program, options?: Options): Output--/**- * Note: this interface currently does not do _actual_ async work, only provides- * a corresponding async interfaces to the `@swc/core`'s interface.- */-export function transform(-    code: string | Program,-    options?: Options,-    experimental_plugin_bytes_resolver?: any-): Promise<Output>;-/**- * @param {string} code- * @param {Options} opts- * @param {Record<string, ArrayBuffer>} experimental_plugin_bytes_resolver An object contains bytes array for the plugin- * specified in config. Key of record represents the name of the plugin specified in config. Note this is an experimental- * interface, likely will change.- * @returns {Output}- */-export function transformSync(code: string | Program, opts?: Options, experimental_plugin_bytes_resolver?: any): Output;-"#;--build_minify_sync!(#[wasm_bindgen(js_name = "minifySync", skip_typescript)]);-build_minify!(#[wasm_bindgen(js_name = "minify", skip_typescript)]);-build_parse_sync!(#[wasm_bindgen(js_name = "parseSync", skip_typescript)]);-build_parse!(#[wasm_bindgen(js_name = "parse", skip_typescript)]);-build_print_sync!(#[wasm_bindgen(js_name = "printSync", skip_typescript)]);-build_print!(#[wasm_bindgen(js_name = "print", skip_typescript)]);-build_transform_sync!(#[wasm_bindgen(js_name = "transformSync", skip_typescript)]);-build_transform!(#[wasm_bindgen(js_name = "transform", skip_typescript)]);

deps/swc/bindings/binding_core_wasm/src/types.rs

deleted file mode 100644@@ -1,3016 +0,0 @@-use wasm_bindgen::prelude::wasm_bindgen;--/// This is direct copy-paste from `node-swc/src/types` to support typed-/// interfaces for @swc/wasm as same as @swc/core.-///-/// While this is redundant, wasm-bindgen does not support to import these types-/// effeciently (https://github.com/rustwasm/wasm-bindgen/issues/2417). Once there is an upstream support this'll-/// be removed.-///-/// Note while these options being accepted by `@swc/wasm`, this doesn't mean-/// all of runtime feature parity is gauranteed. There will be some improvement-/// to handle those differences.-#[wasm_bindgen(typescript_custom_section)]-const SWC_TYPES_DEFINITION: &'static str = r#"-export interface Plugin {-  (module: Program): Program;-}--// TODO:-export type ParseOptions = ParserConfig & {-  comments?: boolean;-  script?: boolean;-  /**-   * Defaults to es3.-   */-  target?: JscTarget;-};--export type TerserEcmaVersion = 5 | 2015 | 2016 | string | number;--export interface JsMinifyOptions {-  compress?: TerserCompressOptions | boolean,--  format?: JsFormatOptions & ToSnakeCaseProperties<JsFormatOptions>,--  mangle?: TerserMangleOptions | boolean,--  ecma?: TerserEcmaVersion,--  keep_classnames?: boolean,--  keep_fnames?: boolean,--  module?: boolean,--  safari10?: boolean--  toplevel?: boolean--  sourceMap?: boolean--  /**-   * Serializable subset of terser-webpack-plugin's `extractComments`.-   * `true` behaves like `'some'`.-   */-  extractComments?: boolean | "some" | "all" | { regex: string }--  outputPath?: string--  inlineSourcesContent?: boolean-}--/**- * @example ToSnakeCase<'indentLevel'> == 'indent_level'- */-type ToSnakeCase<T extends string> = T extends `${infer A}${infer B}`-  ? `${A extends Lowercase<A> ? A : `_${Lowercase<A>}`}${ToSnakeCase<B>}`-  : T--/**- * @example ToSnakeCaseProperties<{indentLevel: 3}> == {indent_level: 3}- */-type ToSnakeCaseProperties<T> = {-  [K in keyof T as (K extends string ? ToSnakeCase<K> : K)]: T[K]-}--/**- * These properties are mostly not implemented yet,- * but it exists to support passing terser config to swc minify- * without modification.- */-export interface JsFormatOptions {-  /**-   * Currently noop.-   * @default false-   * @alias ascii_only-   */-  asciiOnly?: boolean--  /**-   * Currently noop.-   * @default false-   */-  beautify?: boolean--  /**-   * Currently noop.-   * @default false-   */-  braces?: boolean--  /**-   * - `false`: removes all comments-   * - `'some'`: preserves some comments-   * - `'all'`: preserves all comments-   * - `{ regex: string }`: preserves comments that match the regex-   * @default false-   */-  comments?: false | "some" | "all" | { regex: string };--  /**-   * Currently noop.-   * @default 5-   */-  ecma?: TerserEcmaVersion--  /**-   * Currently noop.-   * @alias indent_level-   */-  indentLevel?: number--  /**-   * Currently noop.-   * @alias indent_start-   */-  indentStart?: number--  /**-   * Currently noop.-   * @alias inline_script-   */-  inlineScript?: number--  /**-   * Currently noop.-   * @alias keep_numbers-   */-  keepNumbers?: number--  /**-   * Currently noop.-   * @alias keep_quoted_props-   */-  keepQuotedProps?: boolean--  /**-   * Currently noop.-   * @alias max_line_len-   */-  maxLineLen?: number | false--  /**-   * Currently noop.-   */-  preamble?: string--  /**-   * Currently noop.-   * @alias quote_keys-   */-  quoteKeys?: boolean--  /**-   * Currently noop.-   * @alias quote_style-   */-  quoteStyle?: boolean--  /**-   * Currently noop.-   * @alias preserve_annotations-   */-  preserveAnnotations?: boolean--  /**-   * Currently noop.-   */-  safari10?: boolean--  /**-   * Currently noop.-   */-  semicolons?: boolean--  /**-   * Currently noop.-   */-  shebang?: boolean--  /**-   * Currently noop.-   */-  webkit?: boolean--  /**-   * Currently noop.-   * @alias wrap_iife-   */-  wrapIife?: boolean--  /**-   * Currently noop.-   * @alias wrap_func_args-   */-  wrapFuncArgs?: boolean-}--export interface TerserCompressOptions {-  arguments?: boolean,-  arrows?: boolean,---  booleans?: boolean,---  booleans_as_integers?: boolean,---  collapse_vars?: boolean,---  comparisons?: boolean,---  computed_props?: boolean,---  conditionals?: boolean,---  dead_code?: boolean,--  defaults?: boolean,---  directives?: boolean,---  drop_console?: boolean,---  drop_debugger?: boolean,--  ecma?: TerserEcmaVersion,---  evaluate?: boolean,---  expression?: boolean,---  global_defs?: any,---  hoist_funs?: boolean,---  hoist_props?: boolean,---  hoist_vars?: boolean,---  ie8?: boolean,---  if_return?: boolean,---  inline?: 0 | 1 | 2 | 3---  join_vars?: boolean,---  keep_classnames?: boolean,---  keep_fargs?: boolean,---  keep_fnames?: boolean,---  keep_infinity?: boolean,---  loops?: boolean,-  // module        : false,--  negate_iife?: boolean,---  passes?: number,---  properties?: boolean,---  pure_getters?: any,---  pure_funcs?: string[],---  reduce_funcs?: boolean,---  reduce_vars?: boolean,---  sequences?: any,---  side_effects?: boolean,---  switches?: boolean,---  top_retain?: any,---  toplevel?: any,---  typeofs?: boolean,---  unsafe?: boolean,---  unsafe_passes?: boolean,---  unsafe_arrows?: boolean,---  unsafe_comps?: boolean,---  unsafe_function?: boolean,---  unsafe_math?: boolean,---  unsafe_symbols?: boolean,---  unsafe_methods?: boolean,---  unsafe_proto?: boolean,---  unsafe_regexp?: boolean,---  unsafe_undefined?: boolean,---  unused?: boolean,---  module?: boolean,-}--export interface TerserMangleOptions {-  props?: TerserManglePropertiesOptions,--  toplevel?: boolean,--  keep_classnames?: boolean,--  keep_fnames?: boolean,--  keep_private_props?: boolean,--  ie8?: boolean,--  safari10?: boolean,--  reserved?: string[],-}--export interface TerserManglePropertiesOptions {--}---/**- * Programmatic options.- */-export interface Options extends Config {-  /**-   * If true, a file is parsed as a script instead of module.-   */-  script?: boolean;--  /**-   * The working directory that all paths in the programmatic-   * options will be resolved relative to.-   *-   * Defaults to `process.cwd()`.-   */-  cwd?: string;-  caller?: CallerOptions;-  /** The filename associated with the code currently being compiled,-   * if there is one. The filename is optional, but not all of Swc's-   * functionality is available when the filename is unknown, because a-   * subset of options rely on the filename for their functionality.-   *-   * The three primary cases users could run into are:-   *-   * - The filename is exposed to plugins. Some plugins may require the-   * presence of the filename.-   * - Options like "test", "exclude", and "ignore" require the filename-   * for string/RegExp matching.-   * - .swcrc files are loaded relative to the file being compiled.-   * If this option is omitted, Swc will behave as if swcrc: false has been set.-   */-  filename?: string;--  /**-   * The initial path that will be processed based on the "rootMode" to-   * determine the conceptual root folder for the current Swc project.-   * This is used in two primary cases:-   *-   * - The base directory when checking for the default "configFile" value-   * - The default value for "swcrcRoots".-   *-   * Defaults to `opts.cwd`-   */-  root?: string;--  /**-   * This option, combined with the "root" value, defines how Swc chooses-   * its project root. The different modes define different ways that Swc-   * can process the "root" value to get the final project root.-   *-   * "root" - Passes the "root" value through as unchanged.-   * "upward" - Walks upward from the "root" directory, looking for a directory-   * containing a .swcrc file, and throws an error if a .swcrc-   * is not found.-   * "upward-optional" - Walk upward from the "root" directory, looking for-   * a directory containing a .swcrc file, and falls back to "root"-   *  if a .swcrc is not found.-   *-   *-   * "root" is the default mode because it avoids the risk that Swc-   * will accidentally load a .swcrc that is entirely outside-   * of the current project folder. If you use "upward-optional",-   * be aware that it will walk up the directory structure all the-   * way to the filesystem root, and it is always possible that someone-   * will have a forgotten .swcrc in their home directory,-   * which could cause unexpected errors in your builds.-   *-   *-   * Users with monorepo project structures that run builds/tests on a-   * per-package basis may well want to use "upward" since monorepos-   * often have a .swcrc in the project root. Running Swc-   * in a monorepo subdirectory without "upward", will cause Swc-   * to skip loading any .swcrc files in the project root,-   * which can lead to unexpected errors and compilation failure.-   */-  rootMode?: "root" | "upward" | "upward-optional";--  /**-   * The current active environment used during configuration loading.-   * This value is used as the key when resolving "env" configs,-   * and is also available inside configuration functions, plugins,-   * and presets, via the api.env() function.-   *-   * Defaults to `process.env.SWC_ENV || process.env.NODE_ENV || "development"`-   */-  envName?: string;--  /**-   * Defaults to searching for a default `.swcrc` file, but can-   * be passed the path of any JS or JSON5 config file.-   *-   *-   * NOTE: This option does not affect loading of .swcrc files,-   * so while it may be tempting to do configFile: "./foo/.swcrc",-   * it is not recommended. If the given .swcrc is loaded via the-   * standard file-relative logic, you'll end up loading the same-   * config file twice, merging it with itself. If you are linking-   * a specific config file, it is recommended to stick with a-   * naming scheme that is independent of the "swcrc" name.-   *-   * Defaults to `path.resolve(opts.root, ".swcrc")`-   */-  configFile?: string | boolean;--  /**-   * true will enable searching for configuration files relative to the "filename" provided to Swc.-   *-   * A swcrc value passed in the programmatic options will override one set within a configuration file.-   *-   * Note: .swcrc files are only loaded if the current "filename" is inside of-   *  a package that matches one of the "swcrcRoots" packages.-   *-   *-   * Defaults to true as long as the filename option has been specified-   */-  swcrc?: boolean;--  /**-   * By default, Babel will only search for .babelrc files within the "root" package-   *  because otherwise Babel cannot know if a given .babelrc is meant to be loaded,-   *  or if it's "plugins" and "presets" have even been installed, since the file-   *  being compiled could be inside node_modules, or have been symlinked into the project.-   *-   *-   * This option allows users to provide a list of other packages that should be-   * considered "root" packages when considering whether to load .babelrc files.-   *-   *-   * For example, a monorepo setup that wishes to allow individual packages-   * to have their own configs might want to do-   *-   *-   *-   * Defaults to `opts.root`-   */-  swcrcRoots?: boolean | MatchPattern | MatchPattern[];--  /**-   * `true` will attempt to load an input sourcemap from the file itself, if it-   * contains a //# sourceMappingURL=... comment. If no map is found, or the-   * map fails to load and parse, it will be silently discarded.-   *-   *  If an object is provided, it will be treated as the source map object itself.-   *-   * Defaults to `true`.-   */-  inputSourceMap?: boolean | string;--  /**-   * The name to use for the file inside the source map object.-   *-   * Defaults to `path.basename(opts.filenameRelative)` when available, or `"unknown"`.-   */-  sourceFileName?: string;--  /**-   * The sourceRoot fields to set in the generated source map, if one is desired.-   */-  sourceRoot?: string;--  plugin?: Plugin;--  isModule?: boolean | 'unknown' | 'commonjs';--  /**-   * Destination path. Note that this value is used only to fix source path-   * of source map files and swc does not write output to this path.-   */-  outputPath?: string-}--export interface CallerOptions {-  name: string;-  [key: string]: any;-}--export type Swcrc = Config | Config[];--/**- * .swcrc- */-export interface Config {-  /**-   * Note: The type is string because it follows rust's regex syntax.-   */-  test?: string | string[];-  /**-   * Note: The type is string because it follows rust's regex syntax.-   */-  exclude?: string | string[];-  env?: EnvConfig;-  jsc?: JscConfig;-  module?: ModuleConfig;-  minify?: boolean;--  /**-   * - true to generate a sourcemap for the code and include it in the result object.-   * - "inline" to generate a sourcemap and append it as a data URL to the end of the code, but not include it in the result object.-   *-   * `swc-cli` overloads some of these to also affect how maps are written to disk:-   *-   * - true will write the map to a .map file on disk-   * - "inline" will write the file directly, so it will have a data: containing the map-   * - Note: These options are bit weird, so it may make the most sense to just use true-   *  and handle the rest in your own code, depending on your use case.-   */-  sourceMaps?: boolean | "inline";--  inlineSourcesContent?: boolean-}--/**- * Configuration ported from babel-preset-env- */-export interface EnvConfig {-  mode?: "usage" | "entry";-  debug?: boolean;-  dynamicImport?: boolean;--  loose?: boolean;--  /// Skipped es features.-  ///-  /// e.g.)-  ///  - `core-js/modules/foo`-  skip?: string[];--  include?: string[];--  exclude?: string[];--  /**-   * The version of the used core js.-   *-   */-  coreJs?: string;--  targets?: any;--  path?: string;--  shippedProposals?: boolean;--  /**-   * Enable all transforms-   */-  forceAllTransforms?: boolean;-}--export interface JscConfig {-  loose?: boolean;--  /**-   * Defaults to EsParserConfig-   */-  parser?: ParserConfig;-  transform?: TransformConfig;-  /**-   * Use `@swc/helpers` instead of inline helpers.-   */-  externalHelpers?: boolean;--  /**-   * Defaults to `es3` (which enabled **all** pass).-   */-  target?: JscTarget;--  /**-   * Keep class names.-   */-  keepClassNames?: boolean--  experimental?: {-    optimizeHygiene?: boolean,-    keepImportAssertions?: boolean,-    /**-     * Specify the location where SWC stores its intermediate cache files.-     * Currently only transform plugin uses this. If not specified, SWC will-     * create `.swc` directories.-     */-    cacheRoot?: string;-    /**-     * List of custom transform plugins written in WebAssembly.-     * First parameter of tuple indicates the name of the plugin - it can be either-     * a name of the npm package can be resolved, or absolute path to .wasm binary.-     *-     * Second parameter of tuple is JSON based configuration for the plugin.-     */-    plugins?: Array<[string, Record<string, any>]>-  },--  baseUrl?: string--  paths?: {-    [from: string]: string[]-  }--  minify?: JsMinifyOptions;--  preserveAllComments?: boolean;--  output?: {-    /**-     * This can be used to keep the output ascii-only.-     * If this option is set, `minify.format.asciiOnly` will be ignored.-     * @default 'utf8'-     */-    charset?: 'utf8' | 'ascii';-  }-}--export type JscTarget =-  | "es3"-  | "es5"-  | "es2015"-  | "es2016"-  | "es2017"-  | "es2018"-  | "es2019"-  | "es2020"-  | "es2021"-  | "es2022";--export type ParserConfig = TsParserConfig | EsParserConfig | FlowParserConfig;-export interface TsParserConfig {-  syntax: "typescript";-  /**-   * Defaults to `false`.-   */-  tsx?: boolean;-  /**-   * Defaults to `false`.-   */-  decorators?: boolean;-  /**-   * Defaults to `false`-   */-  dynamicImport?: boolean;-}--export interface FlowParserConfig {-  syntax: "flow";-  /**-   * Defaults to `false`.-   */-  jsx?: boolean;-  /**-   * Defaults to `false`.-   */-  all?: boolean;-  /**-   * Defaults to `false`.-   */-  requireDirective?: boolean;-  /**-   * Defaults to `false`.-   */-  enums?: boolean;-  /**-   * Defaults to `false`.-   */-  decorators?: boolean;-  /**-   * Defaults to `false`.-   */-  components?: boolean;-  /**-   * Defaults to `false`.-   */-  patternMatching?: boolean;-}--export interface EsParserConfig {-  syntax: "ecmascript";-  /**-   * Defaults to false.-   */-  jsx?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  numericSeparator?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  classPrivateProperty?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  privateMethod?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  classProperty?: boolean;-  /**-   * Defaults to `false`-   */-  functionBind?: boolean;-  /**-   * Defaults to `false`-   */-  decorators?: boolean;-  /**-   * Defaults to `false`-   */-  decoratorsBeforeExport?: boolean;-  /**-   * Defaults to `false`-   */-  exportDefaultFrom?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  exportNamespaceFrom?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  dynamicImport?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  nullishCoalescing?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  optionalChaining?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  importMeta?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  topLevelAwait?: boolean;-  /**-   * Defaults to `false`-   */-  importAssertions?: boolean;-}--/**- * Options for transform.- */-export interface TransformConfig {-  /**-   * Effective only if `syntax` supports ƒ.-   */-  react?: ReactConfig;--  reactCompiler?: boolean | ReactCompilerOptions;--  constModules?: ConstModulesConfig;--  /**-   * Defaults to null, which skips optimizer pass.-   */-  optimizer?: OptimizerConfig;--  /**-   * https://swc.rs/docs/configuring-swc.html#jsctransformlegacydecorator-   */-  legacyDecorator?: boolean;--  /**-   * https://swc.rs/docs/configuring-swc.html#jsctransformdecoratormetadata-   */-  decoratorMetadata?: boolean;--  treatConstEnumAsEnum?: boolean;--  useDefineForClassFields?: boolean;-}--export interface ReactCompilerOptions {-  /**-   * Which functions to compile.-   *-   * Defaults to `"infer"`.-   */-  compilationMode?: "infer" | "syntax" | "annotation" | "all";--  /**-   * What to do when a function cannot be compiled.-   *-   * Defaults to `"none"`.-   */-  panicThreshold?: "none" | "critical_errors" | "all_errors";--  /**-   * React runtime version target.-   *-   * Defaults to `"19"`.-   */-  target?: "17" | "18" | "19";--  /**-   * Analyze and report diagnostics only; emit no transformed code.-   *-   * Defaults to `false`.-   */-  noEmit?: boolean;--  /**-   * Defaults to `"client"`.-   */-  outputMode?: "client" | "ssr" | "lint";--  /**-   * Compile even functions marked with opt-out directives.-   *-   * Defaults to `false`.-   */-  ignoreUseNoForget?: boolean;--  /**-   * Treat Flow suppression comments as opt-outs.-   *-   * Defaults to `true`.-   */-  flowSuppressions?: boolean;--  /**-   * Enable react-native-reanimated support.-   *-   * Defaults to `false`.-   */-  enableReanimated?: boolean;--  /**-   * Development mode.-   *-   * Defaults to `false`.-   */-  isDev?: boolean;--  /**-   * ESLint rules whose suppressions opt a function out of compilation.-   */-  eslintSuppressionRules?: string[];--  /**-   * Extra directives that opt a function out of compilation.-   */-  customOptOutDirectives?: string[];--  /**-   * Emit a gated version of each compiled function.-   */-  gating?: ReactCompilerGatingConfig;--  /**-   * Dynamically-gated compilation.-   */-  dynamicGating?: ReactCompilerDynamicGatingConfig;-}--export interface ReactCompilerGatingConfig {-  /**-   * Module the gating import comes from.-   */-  source: string;--  /**-   * Imported specifier used as the gate.-   */-  importSpecifierName: string;-}--export interface ReactCompilerDynamicGatingConfig {-  /**-   * Module the gating import comes from.-   */-  source: string;-}--export interface ReactConfig {-  /**-   * Replace the function used when compiling JSX expressions.-   *-   * Defaults to `React.createElement`.-   */-  pragma?: string;-  /**-   * Replace the component used when compiling JSX fragments.-   *-   * Defaults to `React.Fragment`-   */-  pragmaFrag?: string;-  /**-   * Toggles whether or not to throw an error if a XML namespaced tag name is used. For example:-   * `<f:image />`-   *-   * Though the JSX spec allows this, it is disabled by default since React's-   * JSX does not currently have support for it.-   *-   */-  throwIfNamespace?: boolean;-  /**-   * Toggles plugins that aid in development, such as @swc/plugin-transform-react-jsx-self-   * and @swc/plugin-transform-react-jsx-source.-   *-   * Defaults to `false`,-   *-   */-  development?: boolean;-  /**-   * Use `Object.assign()` instead of `_extends`. Defaults to false.-   * @deprecated-   */-  useBuiltins?: boolean;--  /**-   * Enable fast refresh feature for React app-   */-  refresh?:-    | boolean-    | {-          /**-           * Identifier for the `react-refresh` register function.-           *-           * Defaults to `$RefreshReg$`-           */-          refreshReg?: string;-          /**-           * Identifier for the `react-refresh` signature function.-           *-           * Defaults to `$RefreshSig$`-           */-          refreshSig?: string;-          /**-           * Flag to emit full signatures.-           *-           * Defaults to `false`-           */-          emitFullSignatures?: boolean;-      };--  /**-   * Decides which runtime to use when transforming JSX.-   * - `"automatic"` - Automatically imports the functions that JSX transpiles to.-   * This is the modern approach introduced in React 17+ that eliminates the need to-   * manually import React in every file that uses JSX.-   * - `"classic"` - Uses the traditional JSX transform that relies on `React.createElement`-   * calls. Requires React to be in scope, which was the standard behavior before React 17.-   * - `"preserve"` - Leaves JSX syntax unchanged without transforming it.-   * @default "classic"-   */-  runtime?: "automatic" | "classic" | "preserve";--  /**-   * Declares the module specifier to be used for importing the `jsx` and `jsxs` factory-   * functions when using `runtime` 'automatic'-   * @default "react"-   */-  importSource?: string;-}-/**- *  - `import { DEBUG } from '@ember/env-flags';`- *  - `import { FEATURE_A, FEATURE_B } from '@ember/features';`- *- * See: https://github.com/swc-project/swc/issues/18#issuecomment-466272558- */-export interface ConstModulesConfig {-  globals?: {-    [module: string]: {-      [name: string]: string;-    };-  };-}--/// https://swc.rs/docs/configuring-swc.html#jsctransformoptimizerjsonify-export interface OptimizerConfig {-  /// https://swc.rs/docs/configuration/compilation#jsctransformoptimizersimplify-  simplify?: boolean;-  /// https://swc.rs/docs/configuring-swc.html#jsctransformoptimizerglobals-  globals?: GlobalPassOption;-  /// https://swc.rs/docs/configuring-swc.html#jsctransformoptimizerjsonify-  jsonify?: { minCost: number };-}--/**- * Options for inline-global pass.- */-export interface GlobalPassOption {-  /**-   * Global variables.-   *-   * e.g. `{ __DEBUG__: true }`-   */-  vars?: { [key: string]: string };--  /**-   * Name of environment variables to inline.-   *-   * Defaults to `[]`-   */-  envs?: string[] | Record<string, string>;-}--export type ModuleConfig = Es6Config | CommonJsConfig | UmdConfig | AmdConfig | NodeNextConfig | SystemjsConfig;--export interface BaseModuleConfig {-  /**-   * By default, when using exports with babel a non-enumerable `__esModule`-   * property is exported. In some cases this property is used to determine-   * if the import is the default export or if it contains the default export.-   *-   * In order to prevent the __esModule property from being exported, you-   *  can set the strict option to true.-   *-   * Defaults to `false`.-   */-  strict?: boolean;--  /**-   * Emits 'use strict' directive.-   *-   * Defaults to `true`.-   */-  strictMode?: boolean;--  /**-   * Changes Babel's compiled import statements to be lazily evaluated when their imported bindings are used for the first time.-   *-   * This can improve initial load time of your module because evaluating dependencies up-   *  front is sometimes entirely un-necessary. This is especially the case when implementing-   *  a library module.-   *-   *-   * The value of `lazy` has a few possible effects:-   *-   *  - `false` - No lazy initialization of any imported module.-   *  - `true` - Do not lazy-initialize local `./foo` imports, but lazy-init `foo` dependencies.-   *-   * Local paths are much more likely to have circular dependencies, which may break if loaded lazily,-   * so they are not lazy by default, whereas dependencies between independent modules are rarely cyclical.-   *-   *  - `Array<string>` - Lazy-initialize all imports with source matching one of the given strings.-   *-   * ------   *-   * The two cases where imports can never be lazy are:-   *-   *  - `import "foo";`-   *-   * Side-effect imports are automatically non-lazy since their very existence means-   *  that there is no binding to later kick off initialization.-   *-   *  - `export * from "foo"`-   *-   * Re-exporting all names requires up-front execution because otherwise there is no-   * way to know what names need to be exported.-   *-   * Defaults to `false`.-   */-  lazy?: boolean | string[];-  /**-   * @deprecated  Use the `importInterop` option instead.-   *-   * By default, when using exports with swc a non-enumerable __esModule property is exported.-   * This property is then used to determine if the import is the default export or if-   *  it contains the default export.-   *-   * In cases where the auto-unwrapping of default is not needed, you can set the noInterop option-   *  to true to avoid the usage of the interopRequireDefault helper (shown in inline form above).-   *-   * Defaults to `false`.-   */-  noInterop?: boolean;-  /**-   * Defaults to `swc`.-   *-   * CommonJS modules and ECMAScript modules are not fully compatible.-   * However, compilers, bundlers and JavaScript runtimes developed different strategies-   * to make them work together as well as possible.-   *-   * - `swc` (alias: `babel`)-   *-   * When using exports with `swc` a non-enumerable `__esModule` property is exported-   * This property is then used to determine if the import is the default export-   * or if it contains the default export.-   *-   * ```javascript-   * import foo from "foo";-   * import { bar } from "bar";-   * foo;-   * bar;-   *-   * // Is compiled to ...-   *-   * "use strict";-   *-   * function _interop_require_default(obj) {-   *   return obj && obj.__esModule ? obj : { default: obj };-   * }-   *-   * var _foo = _interop_require_default(require("foo"));-   * var _bar = require("bar");-   *-   * _foo.default;-   * _bar.bar;-   * ```-   *-   * When this import interop is used, if both the imported and the importer module are compiled-   * with swc they behave as if none of them was compiled.-   *-   * This is the default behavior.-   *-   * - `node`-   *-   * When importing CommonJS files (either directly written in CommonJS, or generated with a compiler)-   * Node.js always binds the `default` export to the value of `module.exports`.-   *-   * ```javascript-   * import foo from "foo";-   * import { bar } from "bar";-   * foo;-   * bar;-   *-   * // Is compiled to ...-   *-   * "use strict";-   *-   * var _foo = require("foo");-   * var _bar = require("bar");-   *-   * _foo;-   * _bar.bar;-   * ```-   * This is not exactly the same as what Node.js does since swc allows accessing any property of `module.exports`-   * as a named export, while Node.js only allows importing statically analyzable properties of `module.exports`.-   * However, any import working in Node.js will also work when compiled with swc using `importInterop: "node"`.-   *-   * - `none`-   *-   * If you know that the imported file has been transformed with a compiler that stores the `default` export on-   * `exports.default` (such as swc or Babel), you can safely omit the `_interop_require_default` helper.-   *-   * ```javascript-   * import foo from "foo";-   * import { bar } from "bar";-   * foo;-   * bar;-   *-   * // Is compiled to ...-   *-   * "use strict";-   *-   * var _foo = require("foo");-   * var _bar = require("bar");-   *-   * _foo.default;-   * _bar.bar;-   * ```-   */-  importInterop?: "swc" | "babel" | "node" | "none";-  /**-   * Output extension for generated files.-   *-   * Defaults to `js`.-  */-  outFileExtension?: "js" | "mjs" | "cjs";-  /**-   * Emits `cjs-module-lexer` annotation-   * `cjs-module-lexer` is used in Node.js core for detecting the named exports available when importing a CJS module into ESM.-   * swc will emit `cjs-module-lexer` detectable annotation with this option enabled.-   *-   * Defaults to `true` if import_interop is Node, else `false`-   */-  exportInteropAnnotation?: boolean;-  /**-   * If set to true, dynamic imports will be preserved.-   */-  ignoreDynamic?: boolean;-  allowTopLevelThis?: boolean;-  preserveImportMeta?: boolean;-  /**-   * If set to true, This will resolve top .mjs-   */-  resolveFully?: boolean;-}--export interface Es6Config extends BaseModuleConfig {-  type: "es6";-}--export interface NodeNextConfig extends BaseModuleConfig {-  type: "nodenext";-}--export interface CommonJsConfig extends BaseModuleConfig {-  type: "commonjs";-}--export interface UmdConfig extends BaseModuleConfig {-  type: "umd";-  globals?: { [key: string]: string };-}--export interface AmdConfig extends BaseModuleConfig {-  type: "amd";-  moduleId?: string;-  moduleRoot?: string;-}-export interface SystemjsConfig {-  type: "systemjs";-  allowTopLevelThis?: boolean;-}-export interface Output {-  /**-   * Transformed code-   */-  code: string;-  /**-   * Sourcemap (**not** base64 encoded)-   */-  map?: string;-  /**-   * Extracted comments collected during minification.-   */-  extractedComments?: string[];-}--export interface MatchPattern { }--// --------------------------------// ---------- Ast nodes -----------// ---------------------------------export interface Span {-  start: number;-  end: number;-  ctxt: number;-}--export interface Node {-  type: string;-}--export interface HasSpan {-  span: Span;-}--export interface HasDecorator {-  decorators?: Decorator[];-}--export interface Class extends HasSpan, HasDecorator {-  body: ClassMember[];--  superClass?: Expression;--  isAbstract: boolean;--  typeParams?: TsTypeParameterDeclaration;--  superTypeParams?: TsTypeParameterInstantiation;--  implements: TsExpressionWithTypeArguments[];-}--export type ClassMember =-  | Constructor-  | ClassMethod-  | PrivateMethod-  | ClassProperty-  | PrivateProperty-  | TsIndexSignature-  | EmptyStatement-  | StaticBlock;--export interface ClassPropertyBase extends Node, HasSpan, HasDecorator {-  value?: Expression;--  typeAnnotation?: TsTypeAnnotation;--  isStatic: boolean;--  accessibility?: Accessibility;--  isOptional: boolean;--  isOverride: boolean;--  readonly: boolean;--  definite: boolean;-}--export interface ClassProperty extends ClassPropertyBase {-  type: "ClassProperty";--  key: PropertyName;--  isAbstract: boolean;--  declare: boolean;-}--export interface PrivateProperty extends ClassPropertyBase {-  type: "PrivateProperty";--  key: PrivateName;-}--export interface Param extends Node, HasSpan, HasDecorator {-  type: "Parameter";-  pat: Pattern;-}--export interface Constructor extends Node, HasSpan {-  type: "Constructor";--  key: PropertyName;--  params: (TsParameterProperty | Param)[];--  body?: FunctionBody;--  accessibility?: Accessibility;--  isOptional: boolean;-}--export interface ClassMethodBase extends Node, HasSpan {-  function: Fn;--  kind: MethodKind;--  isStatic: boolean;--  accessibility?: Accessibility;--  isAbstract: boolean;--  isOptional: boolean;--  isOverride: boolean;-}--export interface ClassMethod extends ClassMethodBase {-  type: "ClassMethod";--  key: PropertyName;-}--export interface PrivateMethod extends ClassMethodBase {-  type: "PrivateMethod";--  key: PrivateName;-}--export interface StaticBlock extends Node, HasSpan {-  type: "StaticBlock";--  body: BlockStatement;-}--export interface Decorator extends Node, HasSpan {-  type: "Decorator";--  expression: Expression;-}--export type MethodKind = "method" | "getter" | "setter";--export type Declaration =-  | ClassDeclaration-  | FunctionDeclaration-  | VariableDeclaration-  | TsInterfaceDeclaration-  | TsTypeAliasDeclaration-  | TsEnumDeclaration-  | TsModuleDeclaration;--export interface FunctionDeclaration extends Fn {-  type: "FunctionDeclaration";--  identifier: Identifier;--  declare: boolean;-}--export interface ClassDeclaration extends Class, Node {-  type: "ClassDeclaration";--  identifier: Identifier;--  declare: boolean;-}--export interface VariableDeclaration extends Node, HasSpan {-  type: "VariableDeclaration";--  kind: VariableDeclarationKind;--  declare: boolean;--  declarations: VariableDeclarator[];-}--export type VariableDeclarationKind = "var" | "let" | "const";--export interface VariableDeclarator extends Node, HasSpan {-  type: "VariableDeclarator";--  id: Pattern;--  /// Initialization expression.-  init?: Expression;--  /// Typescript only-  definite: boolean;-}--export type Expression =-  | ThisExpression-  | ArrayExpression-  | ObjectExpression-  | FunctionExpression-  | UnaryExpression-  | UpdateExpression-  | BinaryExpression-  | AssignmentExpression-  | MemberExpression-  | SuperPropExpression-  | ConditionalExpression-  | CallExpression-  | NewExpression-  | SequenceExpression-  | Identifier-  | Literal-  | TemplateLiteral-  | TaggedTemplateExpression-  | ArrowFunctionExpression-  | ClassExpression-  | YieldExpression-  | MetaProperty-  | AwaitExpression-  | ParenthesisExpression-  | JSXMemberExpression-  | JSXNamespacedName-  | JSXEmptyExpression-  | JSXElement-  | JSXFragment-  | TsTypeAssertion-  | TsConstAssertion-  | TsNonNullExpression-  | TsAsExpression-  | TsInstantiation-  | PrivateName-  | OptionalChainingExpression-  | Invalid;--interface ExpressionBase extends Node, HasSpan { }--export interface Identifier extends ExpressionBase {-  type: "Identifier";--  value: string;--  /// TypeScript only. Used in case of an optional parameter.-  optional: boolean;-}--export interface OptionalChainingExpression extends ExpressionBase {-  type: "OptionalChainingExpression";-  questionDotToken: Span;-  /**-   * Call expression or member expression.-   */-  base: MemberExpression | OptionalChainingCall;-}--export interface OptionalChainingCall extends ExpressionBase {-  type: "CallExpression";-  callee: Expression;-  arguments: ExprOrSpread[];-  typeArguments?: TsTypeParameterInstantiation;-}--export interface ThisExpression extends ExpressionBase {-  type: "ThisExpression";-}--export interface ArrayExpression extends ExpressionBase {-  type: "ArrayExpression";--  elements: (ExprOrSpread | undefined)[];-}--export interface ExprOrSpread {-  spread?: Span;-  expression: Expression;-}--export interface ObjectExpression extends ExpressionBase {-  type: "ObjectExpression";--  properties: (SpreadElement | Property)[];-}--export interface Argument {-  spread?: Span;-  expression: Expression;-}--export interface SpreadElement extends Node {-  type: "SpreadElement";--  spread: Span;--  arguments: Expression;-}--export interface UnaryExpression extends ExpressionBase {-  type: "UnaryExpression";--  operator: UnaryOperator;--  argument: Expression;-}--export interface UpdateExpression extends ExpressionBase {-  type: "UpdateExpression";--  operator: UpdateOperator;--  prefix: boolean;--  argument: Expression;-}--export interface BinaryExpression extends ExpressionBase {-  type: "BinaryExpression";--  operator: BinaryOperator;--  left: Expression;--  right: Expression;-}--export interface FunctionExpression extends Fn, ExpressionBase {-  type: "FunctionExpression";--  identifier?: Identifier;-}--export interface ClassExpression extends Class, ExpressionBase {-  type: "ClassExpression";--  identifier?: Identifier;-}--export interface AssignmentExpression extends ExpressionBase {-  type: "AssignmentExpression";--  operator: AssignmentOperator;--  left: Expression | Pattern;--  right: Expression;-}--export interface MemberExpression extends ExpressionBase {-  type: "MemberExpression";--  object: Expression;--  property: Identifier | PrivateName | ComputedPropName;-}--export interface SuperPropExpression extends ExpressionBase {-  type: "SuperPropExpression";--  obj: Super;--  property: Identifier | ComputedPropName;-}--export interface ConditionalExpression extends ExpressionBase {-  type: "ConditionalExpression";--  test: Expression;--  consequent: Expression;--  alternate: Expression;-}--export interface Super extends Node, HasSpan {-  type: "Super";-}--export interface Import extends Node, HasSpan {-  type: "Import";-}--export interface CallExpression extends ExpressionBase {-  type: "CallExpression";--  callee: Super | Import | Expression;--  arguments: Argument[];--  typeArguments?: TsTypeParameterInstantiation;-}--export interface NewExpression extends ExpressionBase {-  type: "NewExpression";--  callee: Expression;--  arguments?: Argument[];--  typeArguments?: TsTypeParameterInstantiation;-}--export interface SequenceExpression extends ExpressionBase {-  type: "SequenceExpression";--  expressions: Expression[];-}--export interface ArrowFunctionExpression extends ExpressionBase {-  type: "ArrowFunctionExpression";--  params: Pattern[];--  body: FunctionBody | Expression;--  async: boolean;--  generator: boolean;--  typeParameters?: TsTypeParameterDeclaration;--  returnType?: TsTypeAnnotation;-}--export interface YieldExpression extends ExpressionBase {-  type: "YieldExpression";--  argument?: Expression;--  delegate: boolean;-}--export interface MetaProperty extends Node, HasSpan {-  type: "MetaProperty";--  kind: "new.target" | "import.meta";-}--export interface AwaitExpression extends ExpressionBase {-  type: "AwaitExpression";--  argument: Expression;-}--export interface TemplateLiteral extends ExpressionBase {-  type: "TemplateLiteral";--  expressions: Expression[];--  quasis: TemplateElement[];-}--export interface TaggedTemplateExpression extends ExpressionBase {-  type: "TaggedTemplateExpression";--  tag: Expression;--  typeParameters?: TsTypeParameterInstantiation;--  template: TemplateLiteral;-}--export interface TemplateElement extends ExpressionBase {-  type: "TemplateElement";--  tail: boolean;-  cooked?: string;-  raw: string;-}--export interface ParenthesisExpression extends ExpressionBase {-  type: "ParenthesisExpression";--  expression: Expression;-}--export interface Fn extends HasSpan, HasDecorator {-  thisParam?: TsThisParameter;--  params: Param[];--  body?: FunctionBody;--  generator: boolean;--  async: boolean;--  typeParameters?: TsTypeParameterDeclaration;--  returnType?: TsTypeAnnotation;-}--interface PatternBase extends Node, HasSpan {-  typeAnnotation?: TsTypeAnnotation;-}--export interface PrivateName extends ExpressionBase {-  type: "PrivateName";--  id: Identifier;-}--export type JSXObject = JSXMemberExpression | Identifier;--export interface JSXMemberExpression extends Node {-  type: "JSXMemberExpression";--  object: JSXObject;-  property: Identifier;-}--/**- * XML-based namespace syntax:- */-export interface JSXNamespacedName extends Node {-  type: "JSXNamespacedName";--  namespace: Identifier;-  name: Identifier;-}--export interface JSXEmptyExpression extends Node, HasSpan {-  type: "JSXEmptyExpression";-}--export interface JSXExpressionContainer extends Node, HasSpan {-  type: "JSXExpressionContainer";--  expression: JSXExpression;-}--export type JSXExpression = JSXEmptyExpression | Expression;--export interface JSXSpreadChild extends Node, HasSpan {-  type: "JSXSpreadChild";--  expression: Expression;-}--export type JSXElementName =-  | Identifier-  | JSXMemberExpression-  | JSXNamespacedName;--export interface JSXOpeningElement extends Node, HasSpan {-  type: "JSXOpeningElement";--  name: JSXElementName;--  attributes: JSXAttributeOrSpread[];--  selfClosing: boolean;--  typeArguments?: TsTypeParameterInstantiation;-}--export type JSXAttributeOrSpread = JSXAttribute | SpreadElement;--export interface JSXClosingElement extends Node, HasSpan {-  type: "JSXClosingElement";--  name: JSXElementName;-}--export interface JSXAttribute extends Node, HasSpan {-  type: "JSXAttribute";--  name: JSXAttributeName;--  value?: JSXAttrValue;-}--export type JSXAttributeName = Identifier | JSXNamespacedName;--export type JSXAttrValue =-  | StringLiteral-  | JSXExpressionContainer-  | JSXElement-  | JSXFragment;--export interface JSXText extends Node, HasSpan {-  type: "JSXText";--  value: string;-  raw: string;-}--export interface JSXElement extends Node, HasSpan {-  type: "JSXElement";--  opening: JSXOpeningElement;-  children: JSXElementChild[];-  closing?: JSXClosingElement;-}--export type JSXElementChild =-  | JSXText-  | JSXExpressionContainer-  | JSXSpreadChild-  | JSXElement-  | JSXFragment;--export interface JSXFragment extends Node, HasSpan {-  type: "JSXFragment";--  opening: JSXOpeningFragment;--  children: JSXElementChild[];--  closing: JSXClosingFragment;-}--export interface JSXOpeningFragment extends Node, HasSpan {-  type: "JSXOpeningFragment";-}--export interface JSXClosingFragment extends Node, HasSpan {-  type: "JSXClosingFragment";-}--export type Literal =-  | StringLiteral-  | BooleanLiteral-  | NullLiteral-  | NumericLiteral-  | BigIntLiteral-  | RegExpLiteral-  | JSXText;--export interface StringLiteral extends Node, HasSpan {-  type: "StringLiteral";--  value: string;--  raw?: string;-}--export interface BooleanLiteral extends Node, HasSpan {-  type: "BooleanLiteral";--  value: boolean;-}--export interface NullLiteral extends Node, HasSpan {-  type: "NullLiteral";-}--export interface RegExpLiteral extends Node, HasSpan {-  type: "RegExpLiteral";--  pattern: string;-  flags: string;-}--export interface NumericLiteral extends Node, HasSpan {-  type: "NumericLiteral";--  value: number;--  raw?: string;-}--export interface BigIntLiteral extends Node, HasSpan {-  type: "BigIntLiteral";--  value: bigint;--  raw?: string;-}--export type ModuleDeclaration =-  | ImportDeclaration-  | ExportDeclaration-  | ExportNamedDeclaration-  | ExportDefaultDeclaration-  | ExportDefaultExpression-  | ExportAllDeclaration-  | TsImportEqualsDeclaration-  | TsExportAssignment-  | TsNamespaceExportDeclaration;--export interface ExportDefaultExpression extends Node, HasSpan {-  type: "ExportDefaultExpression";--  expression: Expression;-}--export interface ExportDeclaration extends Node, HasSpan {-  type: "ExportDeclaration";--  declaration: Declaration;-}--export interface ImportDeclaration extends Node, HasSpan {-  type: "ImportDeclaration";--  specifiers: ImportSpecifier[];--  source: StringLiteral;--  typeOnly: boolean;--  asserts?: ObjectExpression;-}--export interface ExportAllDeclaration extends Node, HasSpan {-  type: "ExportAllDeclaration";--  source: StringLiteral;--  asserts?: ObjectExpression;-}--/**- * - `export { foo } from 'mod'`- * - `export { foo as bar } from 'mod'`- */-export interface ExportNamedDeclaration extends Node, HasSpan {-  type: "ExportNamedDeclaration";--  specifiers: ExportSpecifier[];--  source?: StringLiteral;--  typeOnly: boolean;--  asserts?: ObjectExpression;-}--export interface ExportDefaultDeclaration extends Node, HasSpan {-  type: "ExportDefaultDeclaration";--  decl: DefaultDecl;-}--export type DefaultDecl =-  | ClassExpression-  | FunctionExpression-  | TsInterfaceDeclaration;--export type ImportSpecifier =-  | NamedImportSpecifier-  | ImportDefaultSpecifier-  | ImportNamespaceSpecifier;--/**- * e.g. `import foo from 'mod.js'`- */-export interface ImportDefaultSpecifier extends Node, HasSpan {-  type: "ImportDefaultSpecifier";-  local: Identifier;-}--/**- * e.g. `import * as foo from 'mod.js'`.- */-export interface ImportNamespaceSpecifier extends Node, HasSpan {-  type: "ImportNamespaceSpecifier";--  local: Identifier;-}--/**- * e.g. - `import { foo } from 'mod.js'`- *- * local = foo, imported = None- *- * e.g. `import { foo as bar } from 'mod.js'`- *- * local = bar, imported = Some(foo) for- */-export interface NamedImportSpecifier extends Node, HasSpan {-  type: "ImportSpecifier";-  local: Identifier;-  imported?: ModuleExportName;-  isTypeOnly: boolean;-}--export type ModuleExportName = Identifier | StringLiteral;--export type ExportSpecifier =-  | ExportNamespaceSpecifier-  | ExportDefaultSpecifier-  | NamedExportSpecifier;--/**- * `export * as foo from 'src';`- */-export interface ExportNamespaceSpecifier extends Node, HasSpan {-  type: "ExportNamespaceSpecifier";--  name: ModuleExportName;-}--export interface ExportDefaultSpecifier extends Node, HasSpan {-  type: "ExportDefaultSpecifier";--  exported: Identifier;-}--export interface NamedExportSpecifier extends Node, HasSpan {-  type: "ExportSpecifier";--  orig: ModuleExportName;-  /**-   * `Some(bar)` in `export { foo as bar }`-   */-  exported?: ModuleExportName;-  isTypeOnly: boolean;-}--interface HasInterpreter {-  /**-   * e.g. `/usr/bin/node` for `#!/usr/bin/node`-   */-  interpreter: string;-}--export type Program = Module | Script;--export interface Module extends Node, HasSpan, HasInterpreter {-  type: "Module";--  body: ModuleItem[];-}--export interface Script extends Node, HasSpan, HasInterpreter {-  type: "Script";--  body: Statement[];-}--export type ModuleItem = ModuleDeclaration | Statement;--export type BinaryOperator =-  | "=="-  | "!="-  | "==="-  | "!=="-  | "<"-  | "<="-  | ">"-  | ">="-  | "<<"-  | ">>"-  | ">>>"-  | "+"-  | "-"-  | "*"-  | "/"-  | "%"-  | "|"-  | "^"-  | "&"-  | "||"-  | "&&"-  | "in"-  | "instanceof"-  | "**"-  | "??";--export type AssignmentOperator =-  | "="-  | "+="-  | "-="-  | "*="-  | "/="-  | "%="-  | "<<="-  | ">>="-  | ">>>="-  | "|="-  | "^="-  | "&="-  | "**="-  | "&&="-  | "||="-  | "??=";--export type UpdateOperator = "++" | "--";--export type UnaryOperator =-  | "-"-  | "+"-  | "!"-  | "~"-  | "typeof"-  | "void"-  | "delete";--export type Pattern =-  | BindingIdentifier-  | ArrayPattern-  | RestElement-  | ObjectPattern-  | AssignmentPattern-  | Invalid-  | Expression;--export interface BindingIdentifier extends PatternBase {-  type: "Identifier";-  value: string;-  optional: boolean;-}--export interface ArrayPattern extends PatternBase {-  type: "ArrayPattern";--  elements: (Pattern | undefined)[];--  optional: boolean;-}--export interface ObjectPattern extends PatternBase {-  type: "ObjectPattern";--  properties: ObjectPatternProperty[];--  optional: boolean;-}--export interface AssignmentPattern extends PatternBase {-  type: "AssignmentPattern";--  left: Pattern;-  right: Expression;-}--export interface RestElement extends PatternBase {-  type: "RestElement";--  rest: Span;--  argument: Pattern;-}--export type ObjectPatternProperty =-  | KeyValuePatternProperty-  | AssignmentPatternProperty-  | RestElement;--/**- * `{key: value}`- */-export interface KeyValuePatternProperty extends Node {-  type: "KeyValuePatternProperty";--  key: PropertyName;-  value: Pattern;-}--/**- * `{key}` or `{key = value}`- */-export interface AssignmentPatternProperty extends Node, HasSpan {-  type: "AssignmentPatternProperty";--  key: Identifier;-  value?: Expression;-}--/** Identifier is `a` in `{ a, }` */-export type Property =-  | Identifier-  | KeyValueProperty-  | AssignmentProperty-  | GetterProperty-  | SetterProperty-  | MethodProperty;--interface PropBase extends Node {-  key: PropertyName;-}--export interface KeyValueProperty extends PropBase {-  type: "KeyValueProperty";--  value: Expression;-}--export interface AssignmentProperty extends Node {-  type: "AssignmentProperty";--  key: Identifier;-  value: Expression;-}--export interface GetterProperty extends PropBase, HasSpan {-  type: "GetterProperty";--  function: Fn;-}--export interface SetterProperty extends PropBase, HasSpan {-  type: "SetterProperty";--  function: Fn;-}--export interface MethodProperty extends PropBase, Fn {-  type: "MethodProperty";-}--export type PropertyName =-  | Identifier-  | StringLiteral-  | NumericLiteral-  | ComputedPropName-  | BigIntLiteral;--export interface ComputedPropName extends Node, HasSpan {-  type: "Computed";-  expression: Expression;-}--export interface BlockStatement extends Node, HasSpan {-  type: "BlockStatement";--  stmts: Statement[];-}--export interface FunctionBody extends Node, HasSpan {-  type: "FunctionBody";--  stmts: Statement[];-}--export interface ExpressionStatement extends Node, HasSpan {-  type: "ExpressionStatement";-  expression: Expression;-}--export type Statement =-  | BlockStatement-  | EmptyStatement-  | DebuggerStatement-  | WithStatement-  | ReturnStatement-  | LabeledStatement-  | BreakStatement-  | ContinueStatement-  | IfStatement-  | SwitchStatement-  | ThrowStatement-  | TryStatement-  | WhileStatement-  | DoWhileStatement-  | ForStatement-  | ForInStatement-  | ForOfStatement-  | Declaration-  | ExpressionStatement;--export interface EmptyStatement extends Node, HasSpan {-  type: "EmptyStatement";-}--export interface DebuggerStatement extends Node, HasSpan {-  type: "DebuggerStatement";-}--export interface WithStatement extends Node, HasSpan {-  type: "WithStatement";--  object: Expression;-  body: Statement;-}--export interface ReturnStatement extends Node, HasSpan {-  type: "ReturnStatement";--  argument?: Expression;-}--export interface LabeledStatement extends Node, HasSpan {-  type: "LabeledStatement";--  label: Identifier;-  body: Statement;-}--export interface BreakStatement extends Node, HasSpan {-  type: "BreakStatement";--  label?: Identifier;-}--export interface ContinueStatement extends Node, HasSpan {-  type: "ContinueStatement";--  label?: Identifier;-}--export interface IfStatement extends Node, HasSpan {-  type: "IfStatement";--  test: Expression;-  consequent: Statement;-  alternate?: Statement;-}--export interface SwitchStatement extends Node, HasSpan {-  type: "SwitchStatement";--  discriminant: Expression;-  cases: SwitchCase[];-}--export interface ThrowStatement extends Node, HasSpan {-  type: "ThrowStatement";--  argument: Expression;-}--export interface TryStatement extends Node, HasSpan {-  type: "TryStatement";--  block: BlockStatement;-  handler?: CatchClause;-  finalizer?: BlockStatement;-}--export interface WhileStatement extends Node, HasSpan {-  type: "WhileStatement";--  test: Expression;-  body: Statement;-}--export interface DoWhileStatement extends Node, HasSpan {-  type: "DoWhileStatement";--  test: Expression;-  body: Statement;-}--export interface ForStatement extends Node, HasSpan {-  type: "ForStatement";--  init?: VariableDeclaration | Expression;-  test?: Expression;-  update?: Expression;-  body: Statement;-}--export interface ForInStatement extends Node, HasSpan {-  type: "ForInStatement";--  left: VariableDeclaration | Pattern;-  right: Expression;-  body: Statement;-}--export interface ForOfStatement extends Node, HasSpan {-  type: "ForOfStatement";--  /**-   *  Span of the await token.-   *-   *  es2018 for-await-of statements, e.g., `for await (const x of xs) {`-   */-  await?: Span;-  left: VariableDeclaration | Pattern;-  right: Expression;-  body: Statement;-}--export interface SwitchCase extends Node, HasSpan {-  type: "SwitchCase";--  /**-   * Undefined for default case-   */-  test?: Expression;-  consequent: Statement[];-}--export interface CatchClause extends Node, HasSpan {-  type: "CatchClause";--  /**-   * The param is `undefined` if the catch binding is omitted. E.g., `try { foo() } catch {}`-   */-  param?: Pattern;-  body: BlockStatement;-}--export interface TsTypeAnnotation extends Node, HasSpan {-  type: "TsTypeAnnotation";--  typeAnnotation: TsType;-}--export interface TsTypeParameterDeclaration extends Node, HasSpan {-  type: "TsTypeParameterDeclaration";--  parameters: TsTypeParameter[];-}--export interface TsTypeParameter extends Node, HasSpan {-  type: "TsTypeParameter";--  name: Identifier;-  in: boolean;-  out: boolean;-  constraint?: TsType;-  default?: TsType;-}--export interface TsTypeParameterInstantiation extends Node, HasSpan {-  type: "TsTypeParameterInstantiation";--  params: TsType[];-}--export interface TsParameterProperty extends Node, HasSpan, HasDecorator {-  type: "TsParameterProperty";--  accessibility?: Accessibility;-  override: boolean;-  readonly: boolean;-  param: TsParameterPropertyParameter;-}--export type TsParameterPropertyParameter =-  | BindingIdentifier-  | AssignmentPattern;--export interface TsQualifiedName extends Node {-  type: "TsQualifiedName";--  left: TsEntityName;-  right: Identifier;-}--export type TsEntityName = TsQualifiedName | Identifier;--export type TsTypeElement =-  | TsCallSignatureDeclaration-  | TsConstructSignatureDeclaration-  | TsPropertySignature-  | TsGetterSignature-  | TsSetterSignature-  | TsMethodSignature-  | TsIndexSignature;--export interface TsCallSignatureDeclaration extends Node, HasSpan {-  type: "TsCallSignatureDeclaration";--  params: TsFnParameter[];-  typeAnnotation?: TsTypeAnnotation;-  typeParams?: TsTypeParameterDeclaration;-}--export interface TsConstructSignatureDeclaration extends Node, HasSpan {-  type: "TsConstructSignatureDeclaration";--  params: TsFnParameter[];-  typeAnnotation?: TsTypeAnnotation;-  typeParams?: TsTypeParameterDeclaration;-}--export interface TsPropertySignature extends Node, HasSpan {-  type: "TsPropertySignature";--  readonly: boolean;-  key: Expression;-  computed: boolean;-  optional: boolean;--  typeAnnotation?: TsTypeAnnotation;-}--export interface TsGetterSignature extends Node, HasSpan {-  type: "TsGetterSignature";--  key: Expression;-  computed: boolean;-  typeAnnotation?: TsTypeAnnotation;-}--export interface TsSetterSignature extends Node, HasSpan {-  type: "TsSetterSignature";--  key: Expression;-  computed: boolean;-  param: TsFnParameter;-}--export interface TsMethodSignature extends Node, HasSpan {-  type: "TsMethodSignature";--  key: Expression;-  computed: boolean;-  optional: boolean;-  params: TsFnParameter[];--  typeAnn?: TsTypeAnnotation;-  typeParams?: TsTypeParameterDeclaration;-}--export interface TsIndexSignature extends Node, HasSpan {-  type: "TsIndexSignature";--  params: TsFnParameter[];--  typeAnnotation?: TsTypeAnnotation;--  readonly: boolean;-  static: boolean;-}--export type TsType =-  | TsKeywordType-  | TsThisType-  | TsFnOrConstructorType-  | TsTypeReference-  | TsTypeQuery-  | TsTypeLiteral-  | TsArrayType-  | TsTupleType-  | TsOptionalType-  | TsRestType-  | TsUnionOrIntersectionType-  | TsConditionalType-  | TsInferType-  | TsParenthesizedType-  | TsTypeOperator-  | TsIndexedAccessType-  | TsMappedType-  | TsLiteralType-  | TsTypePredicate-  | TsImportType;--export type TsFnOrConstructorType = TsFunctionType | TsConstructorType;--export interface TsKeywordType extends Node, HasSpan {-  type: "TsKeywordType";--  kind: TsKeywordTypeKind;-}--export type TsKeywordTypeKind =-  | "any"-  | "unknown"-  | "number"-  | "object"-  | "boolean"-  | "bigint"-  | "string"-  | "symbol"-  | "void"-  | "undefined"-  | "null"-  | "never"-  | "intrinsic";--export interface TsThisType extends Node, HasSpan {-  type: "TsThisType";-}--export interface TsThisParameter extends Node, HasSpan {-  type: "TsThisParameter";--  thisSpan: Span;--  typeAnnotation?: TsTypeAnnotation;-}--export type TsFnParameter =-  | BindingIdentifier-  | ArrayPattern-  | RestElement-  | ObjectPattern;--export interface TsFunctionType extends Node, HasSpan {-  type: "TsFunctionType";--  params: TsFnParameter[];--  typeParams?: TsTypeParameterDeclaration;-  typeAnnotation: TsTypeAnnotation;-}--export interface TsConstructorType extends Node, HasSpan {-  type: "TsConstructorType";--  params: TsFnParameter[];--  typeParams?: TsTypeParameterDeclaration;-  typeAnnotation: TsTypeAnnotation;-  isAbstract: boolean;-}--export interface TsTypeReference extends Node, HasSpan {-  type: "TsTypeReference";--  typeName: TsEntityName;-  typeParams?: TsTypeParameterInstantiation;-}--export interface TsTypePredicate extends Node, HasSpan {-  type: "TsTypePredicate";--  asserts: boolean;--  paramName: TsThisTypeOrIdent;-  typeAnnotation?: TsTypeAnnotation;-}--export type TsThisTypeOrIdent = TsThisType | Identifier;--export interface TsImportType extends Node, HasSpan {-  type: "TsImportType";--  argument: StringLiteral;-  qualifier?: TsEntityName;-  typeArguments?: TsTypeParameterInstantiation;-}--/**- * `typeof` operator- */-export interface TsTypeQuery extends Node, HasSpan {-  type: "TsTypeQuery";--  exprName: TsTypeQueryExpr;-  typeArguments?: TsTypeParameterInstantiation;-}--export type TsTypeQueryExpr = TsEntityName | TsImportType;--export interface TsTypeLiteral extends Node, HasSpan {-  type: "TsTypeLiteral";--  members: TsTypeElement[];-}--export interface TsArrayType extends Node, HasSpan {-  type: "TsArrayType";--  elemType: TsType;-}--export interface TsTupleType extends Node, HasSpan {-  type: "TsTupleType";--  elemTypes: TsTupleElement[];-}--export interface TsTupleElement extends Node, HasSpan {-  type: "TsTupleElement";--  label?: Pattern;-  ty: TsType;-}--export interface TsOptionalType extends Node, HasSpan {-  type: "TsOptionalType";--  typeAnnotation: TsType;-}--export interface TsRestType extends Node, HasSpan {-  type: "TsRestType";--  typeAnnotation: TsType;-}--export type TsUnionOrIntersectionType = TsUnionType | TsIntersectionType;--export interface TsUnionType extends Node, HasSpan {-  type: "TsUnionType";--  types: TsType[];-}--export interface TsIntersectionType extends Node, HasSpan {-  type: "TsIntersectionType";--  types: TsType[];-}--export interface TsConditionalType extends Node, HasSpan {-  type: "TsConditionalType";--  checkType: TsType;-  extendsType: TsType;-  trueType: TsType;-  falseType: TsType;-}--export interface TsInferType extends Node, HasSpan {-  type: "TsInferType";--  typeParam: TsTypeParameter;-}--export interface TsParenthesizedType extends Node, HasSpan {-  type: "TsParenthesizedType";--  typeAnnotation: TsType;-}--export interface TsTypeOperator extends Node, HasSpan {-  type: "TsTypeOperator";--  op: TsTypeOperatorOp;-  typeAnnotation: TsType;-}--export type TsTypeOperatorOp = "keyof" | "unique" | "readonly";--export interface TsIndexedAccessType extends Node, HasSpan {-  type: "TsIndexedAccessType";--  readonly: boolean;-  objectType: TsType;-  indexType: TsType;-}--export type TruePlusMinus = true | "+" | "-";--export interface TsMappedType extends Node, HasSpan {-  type: "TsMappedType";--  readonly?: TruePlusMinus;-  typeParam: TsTypeParameter;-  nameType?: TsType;-  optional?: TruePlusMinus;-  typeAnnotation?: TsType;-}--export interface TsLiteralType extends Node, HasSpan {-  type: "TsLiteralType";--  literal: TsLiteral;-}--export type TsLiteral =-  | NumericLiteral-  | StringLiteral-  | BooleanLiteral-  | BigIntLiteral-  | TsTemplateLiteralType;--export interface TsTemplateLiteralType extends Node, HasSpan {-  type: "TemplateLiteral";-  types: TsType[];-  quasis: TemplateElement[];-}--// // ================-// // TypeScript declarations-// // ================--export interface TsInterfaceDeclaration extends Node, HasSpan {-  type: "TsInterfaceDeclaration";--  id: Identifier;-  declare: boolean;-  typeParams?: TsTypeParameterDeclaration;-  extends: TsExpressionWithTypeArguments[];-  body: TsInterfaceBody;-}--export interface TsInterfaceBody extends Node, HasSpan {-  type: "TsInterfaceBody";--  body: TsTypeElement[];-}--export interface TsExpressionWithTypeArguments extends Node, HasSpan {-  type: "TsExpressionWithTypeArguments";--  expression: Expression;-  typeArguments?: TsTypeParameterInstantiation;-}--export interface TsTypeAliasDeclaration extends Node, HasSpan {-  type: "TsTypeAliasDeclaration";--  declare: boolean;-  id: Identifier;-  typeParams?: TsTypeParameterDeclaration;-  typeAnnotation: TsType;-}--export interface TsEnumDeclaration extends Node, HasSpan {-  type: "TsEnumDeclaration";--  declare: boolean;-  isConst: boolean;-  id: Identifier;-  members: TsEnumMember[];-}--export interface TsEnumMember extends Node, HasSpan {-  type: "TsEnumMember";--  id: TsEnumMemberId;-  init?: Expression;-}--export type TsEnumMemberId = Identifier | StringLiteral;--export interface TsModuleDeclaration extends Node, HasSpan {-  type: "TsModuleDeclaration";--  declare: boolean;-  global: boolean;-  id: TsModuleName;-  body?: TsNamespaceBody;-}--/**- * `namespace A.B { }` is a namespace named `A` with another TsNamespaceDecl as its body.- */-export type TsNamespaceBody = TsModuleBlock | TsNamespaceDeclaration;--export interface TsModuleBlock extends Node, HasSpan {-  type: "TsModuleBlock";--  body: ModuleItem[];-}--export interface TsNamespaceDeclaration extends Node, HasSpan {-  type: "TsNamespaceDeclaration";--  declare: boolean;-  global: boolean;-  id: Identifier;-  body: TsNamespaceBody;-}--export type TsModuleName = Identifier | StringLiteral;--export interface TsImportEqualsDeclaration extends Node, HasSpan {-  type: "TsImportEqualsDeclaration";--  declare: boolean;-  isExport: boolean;-  isTypeOnly: boolean;-  id: Identifier;-  moduleRef: TsModuleReference;-}--export type TsModuleReference = TsEntityName | TsExternalModuleReference;--export interface TsExternalModuleReference extends Node, HasSpan {-  type: "TsExternalModuleReference";--  expression: StringLiteral;-}--export interface TsExportAssignment extends Node, HasSpan {-  type: "TsExportAssignment";--  expression: Expression;-}--export interface TsNamespaceExportDeclaration extends Node, HasSpan {-  type: "TsNamespaceExportDeclaration";--  id: Identifier;-}--export interface TsAsExpression extends ExpressionBase {-  type: "TsAsExpression";--  expression: Expression;-  typeAnnotation: TsType;-}--export interface TsInstantiation extends Node, HasSpan {-  type: "TsInstantiation";--  expression: Expression;-  typeArguments: TsTypeParameterInstantiation;-}--export interface TsTypeAssertion extends ExpressionBase {-  type: "TsTypeAssertion";--  expression: Expression;-  typeAnnotation: TsType;-}--export interface TsConstAssertion extends ExpressionBase {-  type: "TsConstAssertion";--  expression: Expression;-}--export interface TsNonNullExpression extends ExpressionBase {-  type: "TsNonNullExpression";--  expression: Expression;-}--export type Accessibility = "public" | "protected" | "private";--export interface Invalid extends Node, HasSpan {-  type: "Invalid";-}-"#;

deps/swc/bindings/binding_es_ast_viewer/Cargo.toml

deleted file mode 100644@@ -1,43 +0,0 @@-[package]-authors    = ["강동윤 <kdy1997.dev@gmail.com>"]-edition    = "2021"-license    = { workspace = true }-name       = "binding_es_ast_viewer"-publish    = false-repository = { workspace = true }-version    = "1.16.18"--[dependencies]-anyhow       = { workspace = true }-wasm-bindgen = { workspace = true }--[dependencies.swc_core]-features = [-  "ecma_ast",-  "common",-  "ecma_visit",-  "ecma_transforms",-  "ecma_parser_unstable",-]-path = "../../crates/swc_core"--[dependencies.swc_error_reporters]-path = "../../crates/swc_error_reporters"--[lib]-crate-type = ["cdylib", "rlib"]--[[example]]-name = "cli"-path = "examples/cli.rs"--[profile.release]-codegen-units = 1-debug         = false     # set to `true` for debug information-lto           = true-opt-level     = "s"-panic         = "abort"   # Let it crash and force ourselves to write safe Rust.-strip         = "symbols" # set to `false` for debug information--[package.metadata.wasm-pack.profile.release]-wasm-opt = false

deps/swc/bindings/binding_es_ast_viewer/examples/cli.rs

deleted file mode 100644@@ -1,52 +0,0 @@-use std::{env, fs, path::Path};--use binding_es_ast_viewer::parse;--fn main() {-    let args: Vec<String> = env::args().collect();--    if args.len() != 2 {-        eprintln!("Usage: {} <file_path>", args[0]);-        eprintln!("Example: {} example.js", args[0]);-        std::process::exit(1);-    }--    let file_path = &args[1];--    // Check if file exists-    if !Path::new(file_path).exists() {-        eprintln!("Error: File '{file_path}' does not exist");-        std::process::exit(1);-    }--    // Read file content-    let content = match fs::read_to_string(file_path) {-        Ok(content) => content,-        Err(err) => {-            eprintln!("Error: Cannot read file '{file_path}': {err}");-            std::process::exit(1);-        }-    };--    // Get filename from file path-    let file_name = Path::new(file_path)-        .file_name()-        .and_then(|name| name.to_str())-        .unwrap_or("unknown")-        .to_string();--    // Parse code-    match parse(&content, Some(file_name)) {-        Ok(results) => {-            println!("=== AST Parse Results ===\n");-            println!("{}", results[0]);--            println!("\n=== Token Parse Results ===\n");-            println!("{}", results[1]);-        }-        Err(err) => {-            eprintln!("Parse error: {err}");-            std::process::exit(1);-        }-    }-}

deps/swc/bindings/binding_es_ast_viewer/jest.config.json

deleted file mode 100644@@ -1,3 +0,0 @@-{-    "transform": {}-}\ No newline at end of file

deps/swc/bindings/binding_es_ast_viewer/package.json

deleted file mode 100644@@ -1,5 +0,0 @@-{-    "devDependencies": {-        "@rstest/core": "^0.7.8"-    }-}

deps/swc/bindings/binding_es_ast_viewer/rstest.config.mjs

deleted file mode 100644@@ -1,16 +0,0 @@-export default {-    include: ["__tests__/**/*.{js,jsx,ts,tsx}"],-    globals: true,-    tools: {-        rspack: {-            module: {-                rules: [],-                parser: {-                    javascript: {-                        url: false,-                    },-                },-            },-        },-    },-};

deps/swc/bindings/binding_es_ast_viewer/scripts/build.sh

deleted file mode 100755@@ -1,7 +0,0 @@-#!/usr/bin/env bash-set -eux--wasm-pack build --out-name es_ast_viewer --release --scope=swc --target web $@-ls -al ./pkg--node ./scripts/package.mjs\ No newline at end of file

deps/swc/bindings/binding_es_ast_viewer/scripts/package.mjs

deleted file mode 100644@@ -1,17 +0,0 @@-import fs from "node:fs/promises";--const pkgJsonFile = await fs.readFile("pkg/package.json", "utf8");-const pkgJson = JSON.parse(pkgJsonFile);-pkgJson.name = "@swc/es-ast-viewer";-pkgJson.type = "module";-pkgJson.files.push("es_ast_viewer_node.js");-pkgJson.exports = {-    types: "./es_ast_viewer.d.ts",-    node: "./es_ast_viewer_node.js",-    default: "./es_ast_viewer.js",-};--await Promise.all([-    fs.cp("src/es_ast_viewer_node.js", "pkg/es_ast_viewer_node.js"),-    fs.writeFile("pkg/package.json", JSON.stringify(pkgJson, null, 2)),-]);

deps/swc/bindings/binding_es_ast_viewer/scripts/test.sh

deleted file mode 100755@@ -1,7 +0,0 @@-#!/usr/bin/env bash--set -eu--./scripts/build.sh--npx rstest $@

deps/swc/bindings/binding_es_ast_viewer/src/es_ast_viewer_node.js

deleted file mode 100644@@ -1,10 +0,0 @@-import fs from "node:fs/promises";-import initAsync from "./es_ast_viewer.js";--const wasm = new URL("./es_ast_viewer_bg.wasm", import.meta.url);--export default function (init = { module_or_path: fs.readFile(wasm) }) {-    return initAsync(init);-}--export * from "./es_ast_viewer.js";\ No newline at end of file

deps/swc/bindings/binding_es_ast_viewer/src/lib.rs

deleted file mode 100644@@ -1,117 +0,0 @@-use std::sync::Arc;--use anyhow::Result;-use swc_core::{-    self,-    common::{errors::ColorConfig, FileName, Globals, Mark, SourceMap, GLOBALS},-    ecma::{-        ast::*,-        parser::{unstable::Capturing, EsSyntax, Lexer, Parser, StringInput, Syntax, TsSyntax},-        transforms::base::resolver,-        visit::VisitMutWith,-    },-};-use swc_error_reporters::handler::{try_with_handler, HandlerOpts};-use wasm_bindgen::prelude::wasm_bindgen;--static FILE_NAME: &str = "main.mtsx";--#[wasm_bindgen]-pub fn parse(input: &str, file_name: Option<String>) -> Result<Vec<String>, String> {-    let file_name = file_name.unwrap_or_else(|| FILE_NAME.to_string());-    let mut iter = file_name.rsplit('.');-    let ext = iter.next();--    let lower_ext = ext.map(|e| e.to_ascii_lowercase());--    let is_jsx = lower_ext-        .as_deref()-        .map(|e| {-            e == "jsx" || e == "tsx" || e == "mjsx" || e == "cjsx" || e == "mtsx" || e == "ctsx"-        })-        .unwrap_or_default();--    let is_esm = lower_ext-        .as_deref()-        .map(|e| e == "mjs" || e == "mts" || e == "mjsx" || e == "mtsx")-        .unwrap_or_default();--    let is_cjs = lower_ext-        .as_deref()-        .map(|e| e == "cjs" || e == "cts" || e == "cjsx" || e == "ctsx")-        .unwrap_or_default();--    let is_ts = lower_ext-        .as_deref()-        .map(|e| e == "ts" || e == "tsx" || e == "mts" || e == "cts" || e == "mtsx" || e == "ctsx")-        .unwrap_or_default();--    let is_d_ts =-        is_ts && matches!(iter.next(), Some("d" | "D")) || matches!(iter.next(), Some("d" | "D"));--    let cm: Arc<SourceMap> = Default::default();-    let fm = cm.new_source_file(-        Arc::new(FileName::Real(file_name.into())),-        input.to_string(),-    );--    let syntax = if is_ts {-        Syntax::Typescript(TsSyntax {-            tsx: is_jsx,-            dts: is_d_ts,-            ..Default::default()-        })-    } else {-        Syntax::Es(EsSyntax {-            jsx: is_jsx,-            ..Default::default()-        })-    };-    let target = EsVersion::latest();--    let lexer = Capturing::new(Lexer::new(syntax, target, StringInput::from(&*fm), None));--    let mut parser = Parser::new_from(lexer);--    let program = if is_esm {-        parser.parse_module().map(Program::Module)-    } else if is_cjs {-        parser.parse_commonjs().map(Program::Script)-    } else {-        parser.parse_program()-    };--    let mut ast = try_with_handler(-        cm,-        HandlerOpts {-            color: ColorConfig::Never,-            ..Default::default()-        },-        |handler| {-            for err in parser.take_errors() {-                err.into_diagnostic(handler).emit();-            }--            program.map_err(|err| {-                err.into_diagnostic(handler).emit();-                anyhow::anyhow!("Failed to parse the input")-            })-        },-    )-    .map_err(|err| err.to_pretty_string())?;--    let tokens = parser.input_mut().iter_mut().take();--    GLOBALS.set(&Globals::default(), || {-        let unresolved_mark = Mark::new();-        let top_level_mark = Mark::new();-        ast.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, is_ts));--        Ok(vec![format!("{ast:#?}"), format!("{tokens:#?}")])-    })-}--#[wasm_bindgen]-pub fn version() -> String {-    swc_core::SWC_CORE_VERSION.into()-}

deps/swc/bindings/binding_html_node/Cargo.toml

deleted file mode 100644@@ -1,43 +0,0 @@-[package]-authors = ["강동윤 <kdy1997.dev@gmail.com>"]-build   = "build.rs"-edition = "2021"-exclude = ["artifacts.json", "index.node"]-license = "Apache-2.0"-name    = "binding_html_node"-publish = false-version = "0.2.0"--[lib]-bench      = false-crate-type = ["cdylib"]--[features]--[build-dependencies]-napi-build = { workspace = true }--[dependencies]-anyhow = { workspace = true }-lightningcss = { workspace = true }-napi = { workspace = true, features = ["napi3", "serde-json"] }-napi-derive = { workspace = true, features = ["type-def"] }-serde = { workspace = true, features = ["derive"] }-serde_json = { workspace = true }-swc_atoms = { path = "../../crates/swc_atoms" }-swc_common = { path = "../../crates/swc_common", features = [-  "diagnostic-serde",-] }-swc_config = { path = "../../crates/swc_config", features = ["regex"] }-swc_css_ast = { path = "../../crates/swc_css_ast" }-swc_css_codegen = { path = "../../crates/swc_css_codegen" }-swc_css_minifier = { path = "../../crates/swc_css_minifier" }-swc_css_parser = { path = "../../crates/swc_css_parser" }-swc_error_reporters = { path = "../../crates/swc_error_reporters" }-swc_html = { path = "../../crates/swc_html" }-swc_html_ast = { path = "../../crates/swc_html_ast", features = ["serde"] }-swc_html_minifier = { path = "../../crates/swc_html_minifier", features = [-  "custom-css-minifier",-] }-swc_nodejs_common = { path = "../../crates/swc_nodejs_common" }-tracing = { workspace = true, features = ["release_max_level_info"] }

deps/swc/bindings/binding_html_node/build.rs

deleted file mode 100644@@ -1,23 +0,0 @@-use std::{-    env,-    fs::File,-    io::{BufWriter, Write},-    path::Path,-};--extern crate napi_build;--fn main() {-    let out_dir = env::var("OUT_DIR").expect("Out dir should exist");-    let dest_path = Path::new(&out_dir).join("triple.txt");-    let mut f =-        BufWriter::new(File::create(dest_path).expect("Failed to create target triple text"));-    write!(-        f,-        "{}",-        env::var("TARGET").expect("Target should be specified")-    )-    .expect("Failed to write target triple text");--    napi_build::setup();-}

deps/swc/bindings/binding_html_node/src/lib.rs

deleted file mode 100644@@ -1,764 +0,0 @@-#[macro_use]-extern crate napi_derive;--mod tag_omission;-mod util;--use std::{backtrace::Backtrace, borrow::Cow, env, panic::set_hook};--use anyhow::{bail, Context};-use lightningcss::{printer::PrinterOptions, stylesheet::StyleSheet, targets::Targets};-use napi::{bindgen_prelude::*, Task};-use serde::{Deserialize, Serialize};-use swc_atoms::atom;-use swc_common::{sync::Lrc, FileName, FilePathMapping, SourceMap, DUMMY_SP};-use swc_config::regex::CachedRegex;-use swc_html::{-    ast::{DocumentMode, Namespace},-    codegen::{-        writer::basic::{BasicHtmlWriter, BasicHtmlWriterConfig},-        CodeGenerator, CodegenConfig, Emit,-    },-    parser::{parse_file_as_document, parse_file_as_document_fragment},-};-use swc_html_ast::{Document, DocumentFragment};-use swc_html_minifier::{-    minify_document_fragment_with_custom_css_minifier, minify_document_with_custom_css_minifier,-    option::{-        CollapseWhitespaces, MinifierType, MinifyCssOption, MinifyJsOption, MinifyJsonOption,-        RemoveRedundantAttributes,-    },-    CssMinificationMode, MinifyCss,-};-use swc_nodejs_common::{deserialize_json, get_deserialized, MapErr};--use crate::{tag_omission::TagOmission, util::try_with};--#[napi_derive::module_init]-fn init() {-    if cfg!(debug_assertions) || env::var("SWC_DEBUG").unwrap_or_default() == "1" {-        set_hook(Box::new(|panic_info| {-            let backtrace = Backtrace::force_capture();-            println!("Panic: {panic_info:?}\nBacktrace: {backtrace:?}");-        }));-    }-}--#[napi_derive::napi(object)]-#[derive(Debug, Serialize)]-pub struct Diagnostic {-    pub level: String,-    pub message: String,-    pub span: serde_json::Value,-}--#[napi_derive::napi(object)]-#[derive(Debug, Serialize)]-pub struct TransformOutput {-    pub code: String,-    #[serde(skip_serializing_if = "Option::is_none")]-    pub errors: Option<Vec<Diagnostic>>,-}--struct MinifyTask {-    code: String,-    options: String,-    is_fragment: bool,-}--#[napi_derive::napi(object)]-#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Attribute {-    #[serde(default)]-    pub namespace: Option<String>,-    #[serde(default)]-    pub prefix: Option<String>,-    pub name: String,-    #[serde(default)]-    pub value: Option<String>,-}--#[napi_derive::napi(object)]-#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Element {-    pub tag_name: String,-    pub namespace: String,-    pub attributes: Vec<Attribute>,-    pub is_self_closing: bool,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct MinifyOptions {-    #[serde(default)]-    filename: Option<String>,--    // Parser options-    #[serde(default)]-    iframe_srcdoc: bool,-    #[serde(default)]-    scripting_enabled: bool,-    /// Used only for Document Fragment-    /// Default: NoQuirks-    #[serde(default)]-    mode: Option<DocumentMode>,-    /// Used only for Document Fragment-    /// Default: `template` in HTML namespace-    #[serde(default)]-    context_element: Option<Element>,-    /// Used only for Document Fragment-    /// Default: None-    #[serde(default)]-    form_element: Option<Element>,--    // Minification options-    #[serde(default)]-    force_set_html5_doctype: bool,-    #[serde(default = "default_collapse_whitespaces")]-    collapse_whitespaces: CollapseWhitespaces,-    // Remove safe empty elements with metadata content, i.e. the `script` and `style` element-    // without content and attributes, `meta` and `link` elements without attributes and etc-    #[serde(default = "true_by_default")]-    remove_empty_metadata_elements: bool,-    #[serde(default = "true_by_default")]-    remove_comments: bool,-    #[serde(default = "default_preserve_comments")]-    preserve_comments: Option<Vec<CachedRegex>>,-    #[serde(default = "true_by_default")]-    minify_conditional_comments: bool,-    #[serde(default = "true_by_default")]-    remove_empty_attributes: bool,-    #[serde(default)]-    remove_redundant_attributes: RemoveRedundantAttributes,-    #[serde(default = "true_by_default")]-    collapse_boolean_attributes: bool,-    #[serde(default = "true_by_default")]-    normalize_attributes: bool,-    #[serde(default = "minify_json_by_default")]-    minify_json: MinifyJsonOption,-    #[serde(default = "minify_js_by_default")]-    minify_js: MinifyJsOption,-    #[serde(default = "minify_css_by_default")]-    minify_css: MinifyCssOption<CssMinfierOptions>,-    #[serde(default)]-    minify_additional_scripts_content: Option<Vec<(CachedRegex, MinifierType)>>,-    #[serde(default)]-    minify_additional_attributes: Option<Vec<(CachedRegex, MinifierType)>>,-    #[serde(default = "true_by_default")]-    sort_space_separated_attribute_values: bool,-    #[serde(default)]-    sort_attributes: bool,-    #[serde(default = "true_by_default")]-    merge_metadata_elements: bool,--    // Codegen options-    #[serde(default)]-    tag_omission: Option<TagOmission>,-    #[serde(default)]-    self_closing_void_elements: Option<bool>,-    #[serde(default)]-    quotes: Option<bool>,-}--const fn true_by_default() -> bool {-    true-}--const fn minify_json_by_default() -> MinifyJsonOption {-    MinifyJsonOption::Bool(true)-}--const fn minify_js_by_default() -> MinifyJsOption {-    MinifyJsOption::Bool(true)-}--const fn minify_css_by_default() -> MinifyCssOption<CssMinfierOptions> {-    MinifyCssOption::Bool(true)-}--fn default_preserve_comments() -> Option<Vec<CachedRegex>> {-    Some(vec![-        // License comments-        CachedRegex::new("@preserve").unwrap(),-        CachedRegex::new("@copyright").unwrap(),-        CachedRegex::new("@lic").unwrap(),-        CachedRegex::new("@cc_on").unwrap(),-        // Allow to keep custom comments-        CachedRegex::new("^!").unwrap(),-        // Server-side comments-        CachedRegex::new("^\\s*#").unwrap(),-        // Conditional IE comments-        CachedRegex::new("^\\[if\\s[^\\]+]").unwrap(),-        CachedRegex::new("\\[endif]").unwrap(),-    ])-}--const fn default_collapse_whitespaces() -> CollapseWhitespaces {-    CollapseWhitespaces::OnlyMetadata-}--#[napi]-impl Task for MinifyTask {-    type JsValue = TransformOutput;-    type Output = TransformOutput;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        let opts = deserialize_json(&self.options)-            .context("failed to deserialize minifier options")-            .convert_err()?;--        minify_inner(&self.code, opts, self.is_fragment).convert_err()-    }--    fn resolve(&mut self, _env: napi::Env, output: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(output)-    }-}--enum DocumentOrDocumentFragment {-    Document(Document),-    DocumentFragment(DocumentFragment),-}--fn create_namespace(namespace: &str) -> anyhow::Result<Namespace> {-    match &*namespace.to_lowercase() {-        "http://www.w3.org/1999/xhtml" => Ok(Namespace::HTML),-        "http://www.w3.org/1998/math/mathml" => Ok(Namespace::MATHML),-        "http://www.w3.org/2000/svg" => Ok(Namespace::SVG),-        "http://www.w3.org/1999/xlink" => Ok(Namespace::XLINK),-        "http://www.w3.org/xml/1998/namespace" => Ok(Namespace::XML),-        "http://www.w3.org/2000/xmlns/" => Ok(Namespace::XMLNS),-        _ => {-            bail!("failed to parse namespace of context element")-        }-    }-}--fn create_element(context_element: Element) -> anyhow::Result<swc_html_ast::Element> {-    let mut attributes = Vec::with_capacity(context_element.attributes.len());--    for attribute in context_element.attributes.into_iter() {-        let namespace = match attribute.namespace {-            Some(namespace) => Some(create_namespace(&namespace)?),-            _ => None,-        };--        attributes.push(swc_html_ast::Attribute {-            span: DUMMY_SP,-            namespace,-            prefix: attribute.prefix.map(|value| value.into()),-            name: attribute.name.into(),-            raw_name: None,-            value: attribute.value.map(|value| value.into()),-            raw_value: None,-        })-    }--    Ok(swc_html_ast::Element {-        span: DUMMY_SP,-        tag_name: context_element.tag_name.into(),-        namespace: create_namespace(&context_element.namespace)?,-        attributes,-        children: vec![],-        content: None,-        is_self_closing: context_element.is_self_closing,-    })-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-#[serde(tag = "lib")]-pub enum CssMinfierOptions {-    #[serde(rename = "lightningcss")]-    LightningCss(LightningCssOptions),-    #[serde(rename = "swc")]-    Swc(swc_html_minifier::option::CssOptions),-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase", deny_unknown_fields)]-pub struct LightningCssOptions {}--struct CssMinifier;--impl MinifyCss for CssMinifier {-    type Options = CssMinfierOptions;--    fn minify_css(-        &self,-        options: &MinifyCssOption<Self::Options>,-        data: String,-        mode: swc_html_minifier::CssMinificationMode,-    ) -> Option<String> {-        let opts = match options {-            MinifyCssOption::Bool(v) => {-                if *v {-                    Cow::Owned(CssMinfierOptions::LightningCss(LightningCssOptions {}))-                } else {-                    return None;-                }-            }-            MinifyCssOption::Options(opts) => Cow::Borrowed(opts),-        };--        match &*opts {-            CssMinfierOptions::LightningCss(_) => {-                let mut ss = StyleSheet::parse(-                    &data,-                    lightningcss::stylesheet::ParserOptions {-                        flags: lightningcss::stylesheet::ParserFlags::all(),-                        ..Default::default()-                    },-                )-                .ok()?;--                let targets = Targets::default();--                ss.minify(lightningcss::stylesheet::MinifyOptions {-                    targets,-                    ..Default::default()-                })-                .ok()?;--                let to_css_result = ss-                    .to_css(PrinterOptions {-                        minify: true,-                        targets,-                        ..Default::default()-                    })-                    .ok()?;--                Some(to_css_result.code)-            }--            CssMinfierOptions::Swc(options) => {-                let mut options = options.clone();-                let mut errors: Vec<_> = Vec::new();--                let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));-                let fm = cm.new_source_file(FileName::Anon.into(), data);--                let mut stylesheet = match mode {-                    CssMinificationMode::Stylesheet => {-                        match swc_css_parser::parse_file(&fm, None, options.parser, &mut errors) {-                            Ok(stylesheet) => stylesheet,-                            _ => return None,-                        }-                    }-                    CssMinificationMode::ListOfDeclarations => {-                        match swc_css_parser::parse_file::<Vec<swc_css_ast::DeclarationOrAtRule>>(-                            &fm,-                            None,-                            options.parser,-                            &mut errors,-                        ) {-                            Ok(list_of_declarations) => {-                                let declaration_list: Vec<swc_css_ast::ComponentValue> =-                                    list_of_declarations-                                        .into_iter()-                                        .map(|node| node.into())-                                        .collect();--                                swc_css_ast::Stylesheet {-                                    span: Default::default(),-                                    rules: vec![swc_css_ast::Rule::QualifiedRule(-                                        swc_css_ast::QualifiedRule {-                                            span: Default::default(),-                                            prelude:-                                                swc_css_ast::QualifiedRulePrelude::SelectorList(-                                                    swc_css_ast::SelectorList {-                                                        span: Default::default(),-                                                        children: Vec::new(),-                                                    },-                                                ),-                                            block: swc_css_ast::SimpleBlock {-                                                span: Default::default(),-                                                name: swc_css_ast::TokenAndSpan {-                                                    span: DUMMY_SP,-                                                    token: swc_css_ast::Token::LBrace,-                                                },-                                                value: declaration_list,-                                            },-                                        }-                                        .into(),-                                    )],-                                }-                            }-                            _ => return None,-                        }-                    }-                    CssMinificationMode::MediaQueryList => {-                        match swc_css_parser::parse_file::<swc_css_ast::MediaQueryList>(-                            &fm,-                            None,-                            options.parser,-                            &mut errors,-                        ) {-                            Ok(media_query_list) => swc_css_ast::Stylesheet {-                                span: Default::default(),-                                rules: vec![swc_css_ast::Rule::AtRule(-                                    swc_css_ast::AtRule {-                                        span: Default::default(),-                                        name: swc_css_ast::AtRuleName::Ident(swc_css_ast::Ident {-                                            span: Default::default(),-                                            value: atom!("media"),-                                            raw: None,-                                        }),-                                        prelude: Some(-                                            swc_css_ast::AtRulePrelude::MediaPrelude(-                                                media_query_list,-                                            )-                                            .into(),-                                        ),-                                        block: Some(swc_css_ast::SimpleBlock {-                                            span: Default::default(),-                                            name: swc_css_ast::TokenAndSpan {-                                                span: DUMMY_SP,-                                                token: swc_css_ast::Token::LBrace,-                                            },-                                            // TODO make the `compress_empty` option for CSS-                                            // minifier and-                                            // remove it-                                            value: vec![swc_css_ast::ComponentValue::Str(-                                                Box::new(swc_css_ast::Str {-                                                    span: Default::default(),-                                                    value: atom!("placeholder"),-                                                    raw: None,-                                                }),-                                            )],-                                        }),-                                    }-                                    .into(),-                                )],-                            },-                            _ => return None,-                        }-                    }-                };--                // Avoid compress potential invalid CSS-                if !errors.is_empty() {-                    return None;-                }--                swc_css_minifier::minify(&mut stylesheet, options.minifier);--                let mut minified = String::new();-                let wr = swc_css_codegen::writer::basic::BasicCssWriter::new(-                    &mut minified,-                    None,-                    swc_css_codegen::writer::basic::BasicCssWriterConfig::default(),-                );--                options.codegen.minify = true;--                let mut gen = swc_css_codegen::CodeGenerator::new(wr, options.codegen);--                match mode {-                    CssMinificationMode::Stylesheet => {-                        swc_css_codegen::Emit::emit(&mut gen, &stylesheet).unwrap();-                    }-                    CssMinificationMode::ListOfDeclarations => {-                        let swc_css_ast::Stylesheet { rules, .. } = &stylesheet;--                        // Because CSS is grammar free, protect for fails-                        let Some(swc_css_ast::Rule::QualifiedRule(qualified_rule)) = rules.first()-                        else {-                            return None;-                        };--                        let swc_css_ast::QualifiedRule { block, .. } = &**qualified_rule;--                        swc_css_codegen::Emit::emit(&mut gen, &block).unwrap();--                        minified = minified[1..minified.len() - 1].to_string();-                    }-                    CssMinificationMode::MediaQueryList => {-                        let swc_css_ast::Stylesheet { rules, .. } = &stylesheet;--                        // Because CSS is grammar free, protect for fails-                        let Some(swc_css_ast::Rule::AtRule(at_rule)) = rules.first() else {-                            return None;-                        };--                        let swc_css_ast::AtRule { prelude, .. } = &**at_rule;--                        swc_css_codegen::Emit::emit(&mut gen, &prelude).unwrap();--                        minified = minified.trim().to_string();-                    }-                }--                Some(minified)-            }-        }-    }-}--fn minify_inner(-    code: &str,-    opts: MinifyOptions,-    is_fragment: bool,-) -> anyhow::Result<TransformOutput> {-    swc_common::GLOBALS.set(&swc_common::Globals::new(), || {-        try_with(|cm, handler| {-            let filename = match opts.filename {-                Some(v) => FileName::Real(v.into()),-                None => FileName::Anon,-            };--            let fm = cm.new_source_file(filename.into(), code.to_string());--            let scripting_enabled = opts.scripting_enabled;-            let mut errors = vec![];--            let (mut document_or_document_fragment, context_element) = if is_fragment {-                let context_element = match opts.context_element {-                    Some(context_element) => create_element(context_element)?,-                    _ => swc_html_ast::Element {-                        span: DUMMY_SP,-                        tag_name: atom!("template"),-                        namespace: Namespace::HTML,-                        attributes: vec![],-                        children: vec![],-                        content: None,-                        is_self_closing: false,-                    },-                };-                let mode = match opts.mode {-                    Some(mode) => mode,-                    _ => DocumentMode::NoQuirks,-                };-                let form_element = match opts.form_element {-                    Some(form_element) => Some(create_element(form_element)?),-                    _ => None,-                };-                let document_fragment = parse_file_as_document_fragment(-                    &fm,-                    &context_element,-                    mode,-                    form_element.as_ref(),-                    swc_html::parser::parser::ParserConfig {-                        scripting_enabled,-                        iframe_srcdoc: opts.iframe_srcdoc,-                        ..Default::default()-                    },-                    &mut errors,-                );--                let document_fragment = match document_fragment {-                    Ok(v) => v,-                    Err(err) => {-                        err.to_diagnostics(handler).emit();--                        for err in errors {-                            err.to_diagnostics(handler).emit();-                        }--                        bail!("failed to parse input as document fragment")-                    }-                };--                (-                    DocumentOrDocumentFragment::DocumentFragment(document_fragment),-                    Some(context_element),-                )-            } else {-                let document = parse_file_as_document(-                    &fm,-                    swc_html::parser::parser::ParserConfig {-                        scripting_enabled,-                        iframe_srcdoc: opts.iframe_srcdoc,-                        ..Default::default()-                    },-                    &mut errors,-                );--                let document = match document {-                    Ok(v) => v,-                    Err(err) => {-                        err.to_diagnostics(handler).emit();--                        for err in errors {-                            err.to_diagnostics(handler).emit();-                        }--                        bail!("failed to parse input as document")-                    }-                };--                (DocumentOrDocumentFragment::Document(document), None)-            };--            let mut returned_errors = None;--            if !errors.is_empty() {-                returned_errors = Some(Vec::with_capacity(errors.len()));--                for err in errors {-                    let mut buf = vec![];--                    err.to_diagnostics(handler).buffer(&mut buf);--                    for i in buf {-                        returned_errors.as_mut().unwrap().push(Diagnostic {-                            level: i.level.to_string(),-                            message: i.message(),-                            span: serde_json::to_value(&i.span)?,-                        });-                    }-                }-            }--            let options = swc_html_minifier::option::MinifyOptions {-                force_set_html5_doctype: opts.force_set_html5_doctype,-                collapse_whitespaces: opts.collapse_whitespaces,-                remove_empty_metadata_elements: opts.remove_empty_metadata_elements,-                remove_comments: opts.remove_comments,-                preserve_comments: opts.preserve_comments,-                minify_conditional_comments: opts.minify_conditional_comments,-                remove_empty_attributes: opts.remove_empty_attributes,-                remove_redundant_attributes: opts.remove_redundant_attributes,-                collapse_boolean_attributes: opts.collapse_boolean_attributes,-                normalize_attributes: opts.normalize_attributes,-                minify_json: opts.minify_json,-                minify_js: opts.minify_js,-                minify_css: opts.minify_css,-                minify_additional_scripts_content: opts.minify_additional_scripts_content,-                minify_additional_attributes: opts.minify_additional_attributes,-                sort_space_separated_attribute_values: opts.sort_space_separated_attribute_values,-                sort_attributes: opts.sort_attributes,-                merge_metadata_elements: opts.merge_metadata_elements,-            };--            match document_or_document_fragment {-                DocumentOrDocumentFragment::Document(ref mut document) => {-                    minify_document_with_custom_css_minifier(document, &options, &CssMinifier);-                }-                DocumentOrDocumentFragment::DocumentFragment(ref mut document_fragment) => {-                    minify_document_fragment_with_custom_css_minifier(-                        document_fragment,-                        context_element.as_ref().unwrap(),-                        &options,-                        &CssMinifier,-                    );-                }-            }--            let code = {-                let mut buf = String::new();--                {-                    let mut wr = BasicHtmlWriter::new(-                        &mut buf,-                        None,-                        BasicHtmlWriterConfig {-                            ..Default::default()-                        },-                    );-                    let (tag_omission, keep_head_and_body) = match opts.tag_omission {-                        Some(TagOmission::Bool(v)) => (Some(v), Some(false)),-                        Some(TagOmission::KeepHeadAndBody) => (Some(true), Some(true)),-                        None => (None, None),-                    };-                    let mut gen = CodeGenerator::new(-                        &mut wr,-                        CodegenConfig {-                            minify: true,-                            scripting_enabled,-                            context_element: context_element.as_ref(),-                            tag_omission,-                            keep_head_and_body,-                            self_closing_void_elements: opts.self_closing_void_elements,-                            quotes: opts.quotes,-                        },-                    );--                    match document_or_document_fragment {-                        DocumentOrDocumentFragment::Document(document) => {-                            gen.emit(&document).context("failed to emit")?;-                        }-                        DocumentOrDocumentFragment::DocumentFragment(document_fragment) => {-                            gen.emit(&document_fragment).context("failed to emit")?;-                        }-                    }-                }--                buf-            };--            Ok(TransformOutput {-                code,-                errors: returned_errors,-            })-        })-    })-}--fn to_string(code: Either<Buffer, String>) -> String {-    match code {-        Either::A(code) => String::from_utf8_lossy(code.as_ref()).into_owned(),-        Either::B(code) => code,-    }-}--#[allow(unused)]-#[napi]-fn minify(-    code: Either<Buffer, String>,-    opts: Buffer,-    signal: Option<AbortSignal>,-) -> AsyncTask<MinifyTask> {-    let code = to_string(code);-    let options = String::from_utf8_lossy(opts.as_ref()).into_owned();--    let task = MinifyTask {-        code,-        options,-        is_fragment: false,-    };--    AsyncTask::with_optional_signal(task, signal)-}--#[allow(unused)]-#[napi]-fn minify_fragment(-    code: Either<Buffer, String>,-    opts: Buffer,-    signal: Option<AbortSignal>,-) -> AsyncTask<MinifyTask> {-    let code = to_string(code);-    let options = String::from_utf8_lossy(opts.as_ref()).into_owned();--    let task = MinifyTask {-        code,-        options,-        is_fragment: true,-    };--    AsyncTask::with_optional_signal(task, signal)-}--#[allow(unused)]-#[napi]-pub fn minify_sync(code: Either<Buffer, String>, opts: Buffer) -> napi::Result<TransformOutput> {-    let code = to_string(code);-    let options = get_deserialized(opts)?;--    minify_inner(&code, options, false).convert_err()-}--#[allow(unused)]-#[napi]-pub fn minify_fragment_sync(-    code: Either<Buffer, String>,-    opts: Buffer,-) -> napi::Result<TransformOutput> {-    let code = to_string(code);-    let options = get_deserialized(opts)?;--    minify_inner(&code, options, true).convert_err()-}

deps/swc/bindings/binding_html_node/src/tag_omission.rs

deleted file mode 100644@@ -1,46 +0,0 @@-use serde::{-    de::{Unexpected, Visitor},-    Deserialize,-};--#[derive(Debug)]-pub enum TagOmission {-    Bool(bool),-    KeepHeadAndBody,-}--struct TagOmissionVisitor;--impl Visitor<'_> for TagOmissionVisitor {-    type Value = TagOmission;--    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {-        formatter.write_str("a boolean or 'keep-head-and-body'")-    }--    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>-    where-        E: serde::de::Error,-    {-        Ok(TagOmission::Bool(v))-    }--    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>-    where-        E: serde::de::Error,-    {-        match v {-            "keep-head-and-body" => Ok(TagOmission::KeepHeadAndBody),-            _ => Err(serde::de::Error::invalid_value(Unexpected::Str(v), &self)),-        }-    }-}--impl<'de> Deserialize<'de> for TagOmission {-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>-    where-        D: serde::Deserializer<'de>,-    {-        deserializer.deserialize_any(TagOmissionVisitor)-    }-}

deps/swc/bindings/binding_html_node/src/util.rs

deleted file mode 100644@@ -1,36 +0,0 @@-use anyhow::{anyhow, Error};-use swc_common::{errors::Handler, sync::Lrc, FilePathMapping, SourceMap};-use swc_error_reporters::handler::{try_with_handler, HandlerOpts};--pub fn try_with<F, Ret>(op: F) -> Result<Ret, Error>-where-    F: FnOnce(&Lrc<SourceMap>, &Handler) -> Result<Ret, Error>,-{-    let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));-    try_with_handler(-        cm.clone(),-        HandlerOpts {-            skip_filename: false,-            ..Default::default()-        },-        |handler| {-            //-            let result =-                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| op(&cm, handler)));--            let p = match result {-                Ok(v) => return v,-                Err(v) => v,-            };--            if let Some(s) = p.downcast_ref::<String>() {-                Err(anyhow!("failed to handle: {s}"))-            } else if let Some(s) = p.downcast_ref::<&str>() {-                Err(anyhow!("failed to handle: {s}"))-            } else {-                Err(anyhow!("failed to handle with unknown panic message"))-            }-        },-    )-    .map_err(|e| e.to_pretty_error())-}

deps/swc/bindings/binding_html_wasm/Cargo.toml

deleted file mode 100644@@ -1,42 +0,0 @@-[package]-authors     = ["강동윤 <kdy1997.dev@gmail.com>"]-description = "wasm module for swc html"-edition     = { workspace = true }-license     = { workspace = true }-name        = "binding_html_wasm"-publish     = false-repository  = { workspace = true }-version     = "1.16.18"--[lib]-bench      = false-crate-type = ["cdylib"]--[dependencies]-anyhow = { workspace = true }-getrandom = { workspace = true, features = ["wasm_js"] }-lightningcss = { workspace = true }-serde = { workspace = true, features = ["derive"] }-serde-wasm-bindgen = { workspace = true }-serde_json = { workspace = true }-swc_atoms = { path = "../../crates/swc_atoms" }-swc_common = { path = "../../crates/swc_common", features = ["diagnostic-serde"] }-swc_config = { path = "../../crates/swc_config", features = ["regex"] }-swc_css_ast = { path = "../../crates/swc_css_ast" }-swc_css_codegen = { path = "../../crates/swc_css_codegen" }-swc_css_minifier = { path = "../../crates/swc_css_minifier" }-swc_css_parser = { path = "../../crates/swc_css_parser" }-swc_error_reporters = { path = "../../crates/swc_error_reporters" }-swc_html = { path = "../../crates/swc_html" }-swc_html_ast = { path = "../../crates/swc_html_ast", features = ["serde"] }-swc_html_minifier = { path = "../../crates/swc_html_minifier", features = ["custom-css-minifier"] }-tracing = { workspace = true, features = ["max_level_off"] }-wasm-bindgen = { workspace = true, features = ["enable-interning"] }-wasm-bindgen-futures = { workspace = true }--[package.metadata.wasm-pack.profile.release]-wasm-opt = false--[package.metadata.cargo-shear]-# ignored, as they are only used to enable features-ignored = ["anyhow", "getrandom", "serde-wasm-bindgen"]

deps/swc/bindings/binding_html_wasm/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.\ No newline at end of file

deps/swc/bindings/binding_html_wasm/package.json

deleted file mode 100644@@ -1,5 +0,0 @@-{-    "devDependencies": {-        "@rstest/core": "^0.7.8"-    }-}

deps/swc/bindings/binding_html_wasm/rstest.config.mjs

deleted file mode 100644@@ -1,4 +0,0 @@-export default {-    include: ["__tests__/**/*.{js,jsx,ts,tsx}"],-    globals: true,-};

deps/swc/bindings/binding_html_wasm/scripts/test.sh

deleted file mode 100755@@ -1,6 +0,0 @@-#!/usr/bin/env bash--set -eu--wasm-pack build --out-name wasm --release --scope=swc --target nodejs-npx rstest "$@"

deps/swc/bindings/binding_html_wasm/src/lib.rs

deleted file mode 100644@@ -1,783 +0,0 @@-mod tag_omission;-mod util;--use std::{backtrace::Backtrace, borrow::Cow, panic::set_hook, sync::Once};--use anyhow::{bail, Context};-use lightningcss::{printer::PrinterOptions, stylesheet::StyleSheet, targets::Targets};-use serde::{Deserialize, Serialize};-use swc_atoms::atom;-use swc_common::{sync::Lrc, FileName, FilePathMapping, SourceMap, DUMMY_SP};-use swc_config::regex::CachedRegex;-use swc_html::{-    ast::{DocumentMode, Namespace},-    codegen::{-        writer::basic::{BasicHtmlWriter, BasicHtmlWriterConfig},-        CodeGenerator, CodegenConfig, Emit,-    },-    parser::{parse_file_as_document, parse_file_as_document_fragment},-};-use swc_html_ast::{Document, DocumentFragment};-use swc_html_minifier::{-    minify_document_fragment_with_custom_css_minifier, minify_document_with_custom_css_minifier,-    option::{-        CollapseWhitespaces, MinifierType, MinifyCssOption, MinifyJsOption, MinifyJsonOption,-        RemoveRedundantAttributes,-    },-    CssMinificationMode, MinifyCss,-};-use wasm_bindgen::prelude::*;-use wasm_bindgen_futures::{future_to_promise, js_sys::Promise};--use crate::{tag_omission::TagOmission, util::try_with};--static INIT_HOOK: Once = Once::new();--#[wasm_bindgen(typescript_custom_section)]-const INTERFACE_DEFINITIONS: &'static str = r#"-export type MinifierType = "js-module" | "js-script" | "json" | "css" | "html";--export interface Attribute {-    namespace?: string;-    prefix?: string;-    name: string;-    value?: string;-}--export interface Element {-    tagName: string;-    namespace: string;-    attributes: Attribute[];-    isSelfClosing: boolean;-}--export interface Diagnostic {-    level: string;-    message: string;-    span: unknown;-}--export interface TransformOutput {-    code: string;-    errors?: Diagnostic[];-}--export interface Options {-    filename?: string;-    iframeSrcdoc?: boolean;-    scriptingEnabled?: boolean;-    forceSetHtml5Doctype?: boolean;-    collapseWhitespaces?: "none" | "all" | "smart" | "conservative" | "advanced-conservative" | "only-metadata";-    removeEmptyMetadataElements?: boolean;-    removeComments?: boolean;-    preserveComments?: string[];-    minifyConditionalComments?: boolean;-    removeEmptyAttributes?: boolean;-    removeRedundantAttributes?: "none" | "all" | "smart";-    collapseBooleanAttributes?: boolean;-    normalizeAttributes?: boolean;-    minifyJson?: boolean | { pretty?: boolean };-    minifyJs?: boolean | { parser?: unknown; minifier?: unknown; codegen?: unknown };-    minifyCss?: boolean | { lib: "lightningcss" } | { lib: "swc"; parser?: unknown; minifier?: unknown; codegen?: unknown };-    minifyAdditionalScriptsContent?: [string, MinifierType][];-    minifyAdditionalAttributes?: [string, MinifierType][];-    sortSpaceSeparatedAttributeValues?: boolean;-    sortAttributes?: boolean;-    mergeMetadataElements?: boolean;-    tagOmission?: boolean | "keep-head-and-body";-    selfClosingVoidElements?: boolean;-    quotes?: boolean;-}--export interface FragmentOptions extends Options {-    mode?: "no-quirks" | "limited-quirks" | "quirks";-    contextElement?: Element;-    context_element?: Element;-    formElement?: Element;-    form_element?: Element;-}--export function minify(content: string, options?: Options): Promise<TransformOutput>;-export function minifySync(content: string, options?: Options): TransformOutput;-export function minifyFragment(content: string, options?: FragmentOptions): Promise<TransformOutput>;-export function minifyFragmentSync(content: string, options?: FragmentOptions): TransformOutput;-"#;--fn init_panic_hook() {-    if !cfg!(debug_assertions) {-        return;-    }--    INIT_HOOK.call_once(|| {-        set_hook(Box::new(|panic_info| {-            let backtrace = Backtrace::force_capture();-            println!("Panic: {panic_info:?}\nBacktrace: {backtrace:?}");-        }));-    });-}--#[derive(Debug, Serialize)]-pub struct Diagnostic {-    pub level: String,-    pub message: String,-    pub span: serde_json::Value,-}--#[derive(Debug, Serialize)]-pub struct TransformOutput {-    pub code: String,-    #[serde(skip_serializing_if = "Option::is_none")]-    pub errors: Option<Vec<Diagnostic>>,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Attribute {-    #[serde(default)]-    pub namespace: Option<String>,-    #[serde(default)]-    pub prefix: Option<String>,-    pub name: String,-    #[serde(default)]-    pub value: Option<String>,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Element {-    pub tag_name: String,-    pub namespace: String,-    pub attributes: Vec<Attribute>,-    pub is_self_closing: bool,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct MinifyOptions {-    #[serde(default)]-    filename: Option<String>,--    // Parser options-    #[serde(default)]-    iframe_srcdoc: bool,-    #[serde(default)]-    scripting_enabled: bool,-    /// Used only for Document Fragment-    /// Default: NoQuirks-    #[serde(default)]-    mode: Option<DocumentMode>,-    /// Used only for Document Fragment-    /// Default: `template` in HTML namespace-    #[serde(default, alias = "context_element")]-    context_element: Option<Element>,-    /// Used only for Document Fragment-    /// Default: None-    #[serde(default, alias = "form_element")]-    form_element: Option<Element>,--    // Minification options-    #[serde(default)]-    force_set_html5_doctype: bool,-    #[serde(default = "default_collapse_whitespaces")]-    collapse_whitespaces: CollapseWhitespaces,-    // Remove safe empty elements with metadata content, i.e. the `script` and `style` element-    // without content and attributes, `meta` and `link` elements without attributes and etc-    #[serde(default = "true_by_default")]-    remove_empty_metadata_elements: bool,-    #[serde(default = "true_by_default")]-    remove_comments: bool,-    #[serde(default = "default_preserve_comments")]-    preserve_comments: Option<Vec<CachedRegex>>,-    #[serde(default = "true_by_default")]-    minify_conditional_comments: bool,-    #[serde(default = "true_by_default")]-    remove_empty_attributes: bool,-    #[serde(default)]-    remove_redundant_attributes: RemoveRedundantAttributes,-    #[serde(default = "true_by_default")]-    collapse_boolean_attributes: bool,-    #[serde(default = "true_by_default")]-    normalize_attributes: bool,-    #[serde(default = "minify_json_by_default")]-    minify_json: MinifyJsonOption,-    #[serde(default = "minify_js_by_default")]-    minify_js: MinifyJsOption,-    #[serde(default = "minify_css_by_default")]-    minify_css: MinifyCssOption<CssMinfierOptions>,-    #[serde(default)]-    minify_additional_scripts_content: Option<Vec<(CachedRegex, MinifierType)>>,-    #[serde(default)]-    minify_additional_attributes: Option<Vec<(CachedRegex, MinifierType)>>,-    #[serde(default = "true_by_default")]-    sort_space_separated_attribute_values: bool,-    #[serde(default)]-    sort_attributes: bool,-    #[serde(default = "true_by_default")]-    merge_metadata_elements: bool,--    // Codegen options-    #[serde(default)]-    tag_omission: Option<TagOmission>,-    #[serde(default)]-    self_closing_void_elements: Option<bool>,-    #[serde(default)]-    quotes: Option<bool>,-}--const fn true_by_default() -> bool {-    true-}--const fn minify_json_by_default() -> MinifyJsonOption {-    MinifyJsonOption::Bool(true)-}--const fn minify_js_by_default() -> MinifyJsOption {-    MinifyJsOption::Bool(true)-}--const fn minify_css_by_default() -> MinifyCssOption<CssMinfierOptions> {-    MinifyCssOption::Bool(true)-}--fn default_preserve_comments() -> Option<Vec<CachedRegex>> {-    Some(vec![-        // License comments-        CachedRegex::new("@preserve").unwrap(),-        CachedRegex::new("@copyright").unwrap(),-        CachedRegex::new("@lic").unwrap(),-        CachedRegex::new("@cc_on").unwrap(),-        // Allow to keep custom comments-        CachedRegex::new("^!").unwrap(),-        // Server-side comments-        CachedRegex::new("^\\s*#").unwrap(),-        // Conditional IE comments-        CachedRegex::new("^\\[if\\s[^\\]+]").unwrap(),-        CachedRegex::new("\\[endif]").unwrap(),-    ])-}--const fn default_collapse_whitespaces() -> CollapseWhitespaces {-    CollapseWhitespaces::OnlyMetadata-}--enum DocumentOrDocumentFragment {-    Document(Document),-    DocumentFragment(DocumentFragment),-}--fn create_namespace(namespace: &str) -> anyhow::Result<Namespace> {-    match &*namespace.to_lowercase() {-        "http://www.w3.org/1999/xhtml" => Ok(Namespace::HTML),-        "http://www.w3.org/1998/math/mathml" => Ok(Namespace::MATHML),-        "http://www.w3.org/2000/svg" => Ok(Namespace::SVG),-        "http://www.w3.org/1999/xlink" => Ok(Namespace::XLINK),-        "http://www.w3.org/xml/1998/namespace" => Ok(Namespace::XML),-        "http://www.w3.org/2000/xmlns/" => Ok(Namespace::XMLNS),-        _ => {-            bail!("failed to parse namespace of context element")-        }-    }-}--fn create_element(context_element: Element) -> anyhow::Result<swc_html_ast::Element> {-    let mut attributes = Vec::with_capacity(context_element.attributes.len());--    for attribute in context_element.attributes.into_iter() {-        let namespace = match attribute.namespace {-            Some(namespace) => Some(create_namespace(&namespace)?),-            _ => None,-        };--        attributes.push(swc_html_ast::Attribute {-            span: DUMMY_SP,-            namespace,-            prefix: attribute.prefix.map(|value| value.into()),-            name: attribute.name.into(),-            raw_name: None,-            value: attribute.value.map(|value| value.into()),-            raw_value: None,-        })-    }--    Ok(swc_html_ast::Element {-        span: DUMMY_SP,-        tag_name: context_element.tag_name.into(),-        namespace: create_namespace(&context_element.namespace)?,-        attributes,-        children: vec![],-        content: None,-        is_self_closing: context_element.is_self_closing,-    })-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-#[serde(tag = "lib")]-pub enum CssMinfierOptions {-    #[serde(rename = "lightningcss")]-    LightningCss(LightningCssOptions),-    #[serde(rename = "swc")]-    Swc(swc_html_minifier::option::CssOptions),-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase", deny_unknown_fields)]-pub struct LightningCssOptions {}--struct CssMinifier;--impl MinifyCss for CssMinifier {-    type Options = CssMinfierOptions;--    fn minify_css(-        &self,-        options: &MinifyCssOption<Self::Options>,-        data: String,-        mode: swc_html_minifier::CssMinificationMode,-    ) -> Option<String> {-        let opts = match options {-            MinifyCssOption::Bool(v) => {-                if *v {-                    Cow::Owned(CssMinfierOptions::LightningCss(LightningCssOptions {}))-                } else {-                    return None;-                }-            }-            MinifyCssOption::Options(opts) => Cow::Borrowed(opts),-        };--        match &*opts {-            CssMinfierOptions::LightningCss(_) => {-                let mut ss = StyleSheet::parse(-                    &data,-                    lightningcss::stylesheet::ParserOptions {-                        flags: lightningcss::stylesheet::ParserFlags::all(),-                        ..Default::default()-                    },-                )-                .ok()?;--                let targets = Targets::default();--                ss.minify(lightningcss::stylesheet::MinifyOptions {-                    targets,-                    ..Default::default()-                })-                .ok()?;--                let to_css_result = ss-                    .to_css(PrinterOptions {-                        minify: true,-                        targets,-                        ..Default::default()-                    })-                    .ok()?;--                Some(to_css_result.code)-            }--            CssMinfierOptions::Swc(options) => {-                let mut options = options.clone();-                let mut errors: Vec<_> = Vec::new();--                let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));-                let fm = cm.new_source_file(FileName::Anon.into(), data);--                let mut stylesheet = match mode {-                    CssMinificationMode::Stylesheet => {-                        match swc_css_parser::parse_file(&fm, None, options.parser, &mut errors) {-                            Ok(stylesheet) => stylesheet,-                            _ => return None,-                        }-                    }-                    CssMinificationMode::ListOfDeclarations => {-                        match swc_css_parser::parse_file::<Vec<swc_css_ast::DeclarationOrAtRule>>(-                            &fm,-                            None,-                            options.parser,-                            &mut errors,-                        ) {-                            Ok(list_of_declarations) => {-                                let declaration_list: Vec<swc_css_ast::ComponentValue> =-                                    list_of_declarations-                                        .into_iter()-                                        .map(|node| node.into())-                                        .collect();--                                swc_css_ast::Stylesheet {-                                    span: Default::default(),-                                    rules: vec![swc_css_ast::Rule::QualifiedRule(-                                        swc_css_ast::QualifiedRule {-                                            span: Default::default(),-                                            prelude:-                                                swc_css_ast::QualifiedRulePrelude::SelectorList(-                                                    swc_css_ast::SelectorList {-                                                        span: Default::default(),-                                                        children: Vec::new(),-                                                    },-                                                ),-                                            block: swc_css_ast::SimpleBlock {-                                                span: Default::default(),-                                                name: swc_css_ast::TokenAndSpan {-                                                    span: DUMMY_SP,-                                                    token: swc_css_ast::Token::LBrace,-                                                },-                                                value: declaration_list,-                                            },-                                        }-                                        .into(),-                                    )],-                                }-                            }-                            _ => return None,-                        }-                    }-                    CssMinificationMode::MediaQueryList => {-                        match swc_css_parser::parse_file::<swc_css_ast::MediaQueryList>(-                            &fm,-                            None,-                            options.parser,-                            &mut errors,-                        ) {-                            Ok(media_query_list) => swc_css_ast::Stylesheet {-                                span: Default::default(),-                                rules: vec![swc_css_ast::Rule::AtRule(-                                    swc_css_ast::AtRule {-                                        span: Default::default(),-                                        name: swc_css_ast::AtRuleName::Ident(swc_css_ast::Ident {-                                            span: Default::default(),-                                            value: atom!("media"),-                                            raw: None,-                                        }),-                                        prelude: Some(-                                            swc_css_ast::AtRulePrelude::MediaPrelude(-                                                media_query_list,-                                            )-                                            .into(),-                                        ),-                                        block: Some(swc_css_ast::SimpleBlock {-                                            span: Default::default(),-                                            name: swc_css_ast::TokenAndSpan {-                                                span: DUMMY_SP,-                                                token: swc_css_ast::Token::LBrace,-                                            },-                                            // TODO make the `compress_empty` option for CSS-                                            // minifier and-                                            // remove it-                                            value: vec![swc_css_ast::ComponentValue::Str(-                                                Box::new(swc_css_ast::Str {-                                                    span: Default::default(),-                                                    value: atom!("placeholder"),-                                                    raw: None,-                                                }),-                                            )],-                                        }),-                                    }-                                    .into(),-                                )],-                            },-                            _ => return None,-                        }-                    }-                };--                // Avoid compress potential invalid CSS-                if !errors.is_empty() {-                    return None;-                }--                swc_css_minifier::minify(&mut stylesheet, options.minifier);--                let mut minified = String::new();-                let wr = swc_css_codegen::writer::basic::BasicCssWriter::new(-                    &mut minified,-                    None,-                    swc_css_codegen::writer::basic::BasicCssWriterConfig::default(),-                );--                options.codegen.minify = true;--                let mut gen = swc_css_codegen::CodeGenerator::new(wr, options.codegen);--                match mode {-                    CssMinificationMode::Stylesheet => {-                        swc_css_codegen::Emit::emit(&mut gen, &stylesheet).unwrap();-                    }-                    CssMinificationMode::ListOfDeclarations => {-                        let swc_css_ast::Stylesheet { rules, .. } = &stylesheet;--                        // Because CSS is grammar free, protect for fails-                        let Some(swc_css_ast::Rule::QualifiedRule(qualified_rule)) = rules.first()-                        else {-                            return None;-                        };--                        let swc_css_ast::QualifiedRule { block, .. } = &**qualified_rule;--                        swc_css_codegen::Emit::emit(&mut gen, &block).unwrap();--                        minified = minified[1..minified.len() - 1].to_string();-                    }-                    CssMinificationMode::MediaQueryList => {-                        let swc_css_ast::Stylesheet { rules, .. } = &stylesheet;--                        // Because CSS is grammar free, protect for fails-                        let Some(swc_css_ast::Rule::AtRule(at_rule)) = rules.first() else {-                            return None;-                        };--                        let swc_css_ast::AtRule { prelude, .. } = &**at_rule;--                        swc_css_codegen::Emit::emit(&mut gen, &prelude).unwrap();--                        minified = minified.trim().to_string();-                    }-                }--                Some(minified)-            }-        }-    }-}--fn minify_inner(-    code: &str,-    opts: MinifyOptions,-    is_fragment: bool,-) -> anyhow::Result<TransformOutput> {-    swc_common::GLOBALS.set(&swc_common::Globals::new(), || {-        try_with(|cm, handler| {-            let filename = match opts.filename {-                Some(v) => FileName::Real(v.into()),-                None => FileName::Anon,-            };--            let fm = cm.new_source_file(filename.into(), code.to_string());--            let scripting_enabled = opts.scripting_enabled;-            let mut errors = vec![];--            let (mut document_or_document_fragment, context_element) = if is_fragment {-                let context_element = match opts.context_element {-                    Some(context_element) => create_element(context_element)?,-                    _ => swc_html_ast::Element {-                        span: DUMMY_SP,-                        tag_name: atom!("template"),-                        namespace: Namespace::HTML,-                        attributes: vec![],-                        children: vec![],-                        content: None,-                        is_self_closing: false,-                    },-                };-                let mode = match opts.mode {-                    Some(mode) => mode,-                    _ => DocumentMode::NoQuirks,-                };-                let form_element = match opts.form_element {-                    Some(form_element) => Some(create_element(form_element)?),-                    _ => None,-                };-                let document_fragment = parse_file_as_document_fragment(-                    &fm,-                    &context_element,-                    mode,-                    form_element.as_ref(),-                    swc_html::parser::parser::ParserConfig {-                        scripting_enabled,-                        iframe_srcdoc: opts.iframe_srcdoc,-                        ..Default::default()-                    },-                    &mut errors,-                );--                let document_fragment = match document_fragment {-                    Ok(v) => v,-                    Err(err) => {-                        err.to_diagnostics(handler).emit();--                        for err in errors {-                            err.to_diagnostics(handler).emit();-                        }--                        bail!("failed to parse input as document fragment")-                    }-                };--                (-                    DocumentOrDocumentFragment::DocumentFragment(document_fragment),-                    Some(context_element),-                )-            } else {-                let document = parse_file_as_document(-                    &fm,-                    swc_html::parser::parser::ParserConfig {-                        scripting_enabled,-                        iframe_srcdoc: opts.iframe_srcdoc,-                        ..Default::default()-                    },-                    &mut errors,-                );--                let document = match document {-                    Ok(v) => v,-                    Err(err) => {-                        err.to_diagnostics(handler).emit();--                        for err in errors {-                            err.to_diagnostics(handler).emit();-                        }--                        bail!("failed to parse input as document")-                    }-                };--                (DocumentOrDocumentFragment::Document(document), None)-            };--            let mut returned_errors = None;--            if !errors.is_empty() {-                returned_errors = Some(Vec::with_capacity(errors.len()));--                for err in errors {-                    let mut buf = vec![];--                    err.to_diagnostics(handler).buffer(&mut buf);--                    for i in buf {-                        returned_errors.as_mut().unwrap().push(Diagnostic {-                            level: i.level.to_string(),-                            message: i.message(),-                            span: serde_json::to_value(&i.span)?,-                        });-                    }-                }-            }--            let options = swc_html_minifier::option::MinifyOptions {-                force_set_html5_doctype: opts.force_set_html5_doctype,-                collapse_whitespaces: opts.collapse_whitespaces,-                remove_empty_metadata_elements: opts.remove_empty_metadata_elements,-                remove_comments: opts.remove_comments,-                preserve_comments: opts.preserve_comments,-                minify_conditional_comments: opts.minify_conditional_comments,-                remove_empty_attributes: opts.remove_empty_attributes,-                remove_redundant_attributes: opts.remove_redundant_attributes,-                collapse_boolean_attributes: opts.collapse_boolean_attributes,-                normalize_attributes: opts.normalize_attributes,-                minify_json: opts.minify_json,-                minify_js: opts.minify_js,-                minify_css: opts.minify_css,-                minify_additional_scripts_content: opts.minify_additional_scripts_content,-                minify_additional_attributes: opts.minify_additional_attributes,-                sort_space_separated_attribute_values: opts.sort_space_separated_attribute_values,-                sort_attributes: opts.sort_attributes,-                merge_metadata_elements: opts.merge_metadata_elements,-            };--            match document_or_document_fragment {-                DocumentOrDocumentFragment::Document(ref mut document) => {-                    minify_document_with_custom_css_minifier(document, &options, &CssMinifier);-                }-                DocumentOrDocumentFragment::DocumentFragment(ref mut document_fragment) => {-                    minify_document_fragment_with_custom_css_minifier(-                        document_fragment,-                        context_element.as_ref().unwrap(),-                        &options,-                        &CssMinifier,-                    );-                }-            }--            let code = {-                let mut buf = String::new();--                {-                    let mut wr = BasicHtmlWriter::new(-                        &mut buf,-                        None,-                        BasicHtmlWriterConfig {-                            ..Default::default()-                        },-                    );-                    let (tag_omission, keep_head_and_body) = match opts.tag_omission {-                        Some(TagOmission::Bool(v)) => (Some(v), Some(false)),-                        Some(TagOmission::KeepHeadAndBody) => (Some(true), Some(true)),-                        None => (None, None),-                    };-                    let mut gen = CodeGenerator::new(-                        &mut wr,-                        CodegenConfig {-                            minify: true,-                            scripting_enabled,-                            context_element: context_element.as_ref(),-                            tag_omission,-                            keep_head_and_body,-                            self_closing_void_elements: opts.self_closing_void_elements,-                            quotes: opts.quotes,-                        },-                    );--                    match document_or_document_fragment {-                        DocumentOrDocumentFragment::Document(document) => {-                            gen.emit(&document).context("failed to emit")?;-                        }-                        DocumentOrDocumentFragment::DocumentFragment(document_fragment) => {-                            gen.emit(&document_fragment).context("failed to emit")?;-                        }-                    }-                }--                buf-            };--            Ok(TransformOutput {-                code,-                errors: returned_errors,-            })-        })-    })-}--fn js_error(err: impl std::fmt::Display) -> JsValue {-    JsValue::from_str(&err.to_string())-}--fn parse_options(options: JsValue) -> Result<MinifyOptions, JsValue> {-    if options.is_undefined() || options.is_null() {-        return serde_json::from_str("{}").map_err(js_error);-    }--    serde_wasm_bindgen::from_value(options).map_err(js_error)-}--fn minify_js(code: String, options: JsValue, is_fragment: bool) -> Result<JsValue, JsValue> {-    init_panic_hook();--    let options = parse_options(options)?;-    let output = minify_inner(&code, options, is_fragment).map_err(js_error)?;--    serde_wasm_bindgen::to_value(&output).map_err(js_error)-}--#[wasm_bindgen(skip_typescript)]-pub fn minify(code: String, options: JsValue) -> Promise {-    future_to_promise(async move { minify_js(code, options, false) })-}--#[wasm_bindgen(js_name = "minifyFragment", skip_typescript)]-pub fn minify_fragment(code: String, options: JsValue) -> Promise {-    future_to_promise(async move { minify_js(code, options, true) })-}--#[wasm_bindgen(js_name = "minifySync", skip_typescript)]-pub fn minify_sync(code: String, options: JsValue) -> Result<JsValue, JsValue> {-    minify_js(code, options, false)-}--#[wasm_bindgen(js_name = "minifyFragmentSync", skip_typescript)]-pub fn minify_fragment_sync(code: String, options: JsValue) -> Result<JsValue, JsValue> {-    minify_js(code, options, true)-}

deps/swc/bindings/binding_html_wasm/src/tag_omission.rs

deleted file mode 100644@@ -1,46 +0,0 @@-use serde::{-    de::{Unexpected, Visitor},-    Deserialize,-};--#[derive(Debug)]-pub enum TagOmission {-    Bool(bool),-    KeepHeadAndBody,-}--struct TagOmissionVisitor;--impl Visitor<'_> for TagOmissionVisitor {-    type Value = TagOmission;--    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {-        formatter.write_str("a boolean or 'keep-head-and-body'")-    }--    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>-    where-        E: serde::de::Error,-    {-        Ok(TagOmission::Bool(v))-    }--    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>-    where-        E: serde::de::Error,-    {-        match v {-            "keep-head-and-body" => Ok(TagOmission::KeepHeadAndBody),-            _ => Err(serde::de::Error::invalid_value(Unexpected::Str(v), &self)),-        }-    }-}--impl<'de> Deserialize<'de> for TagOmission {-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>-    where-        D: serde::Deserializer<'de>,-    {-        deserializer.deserialize_any(TagOmissionVisitor)-    }-}

deps/swc/bindings/binding_html_wasm/src/util.rs

deleted file mode 100644@@ -1,36 +0,0 @@-use anyhow::{anyhow, Error};-use swc_common::{errors::Handler, sync::Lrc, FilePathMapping, SourceMap};-use swc_error_reporters::handler::{try_with_handler, HandlerOpts};--pub fn try_with<F, Ret>(op: F) -> Result<Ret, Error>-where-    F: FnOnce(&Lrc<SourceMap>, &Handler) -> Result<Ret, Error>,-{-    let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));-    try_with_handler(-        cm.clone(),-        HandlerOpts {-            skip_filename: false,-            ..Default::default()-        },-        |handler| {-            //-            let result =-                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| op(&cm, handler)));--            let p = match result {-                Ok(v) => return v,-                Err(v) => v,-            };--            if let Some(s) = p.downcast_ref::<String>() {-                Err(anyhow!("failed to handle: {s}"))-            } else if let Some(s) = p.downcast_ref::<&str>() {-                Err(anyhow!("failed to handle: {s}"))-            } else {-                Err(anyhow!("failed to handle with unknown panic message"))-            }-        },-    )-    .map_err(|e| e.to_pretty_error())-}

deps/swc/bindings/binding_minifier_node/Cargo.toml

deleted file mode 100644@@ -1,46 +0,0 @@-[package]-authors = ["강동윤 <kdy1997.dev@gmail.com>"]-build   = "build.rs"-edition = "2021"-exclude = ["artifacts.json", "index.node"]-license = "Apache-2.0"-name    = "binding_minifier_node"-publish = false-version = "0.2.0"--[lib]-bench      = false-crate-type = ["cdylib"]--[build-dependencies]-napi-build = { workspace = true }--[dependencies]-anyhow             = { workspace = true }-backtrace          = { workspace = true }-napi               = { workspace = true, features = ["napi3", "serde-json"] }-napi-derive        = { workspace = true, features = ["type-def"] }-par-core           = { workspace = true, features = ["chili"] }-serde              = { workspace = true, features = ["derive"] }-tracing            = { workspace = true, features = ["release_max_level_info"] }---swc_compiler_base = { path = "../../crates/swc_compiler_base", features = [-  "node",-] }-swc_config = { path = "../../crates/swc_config", features = ["regex"] }-swc_core = { path = "../../crates/swc_core", features = [-  "allocator_node",-  "common_concurrent",-  "common_sourcemap",-  "ecma_ast",-  "ecma_codegen",-  "ecma_parser",-  "ecma_minifier",-  "ecma_minifier_concurrent",-  "ecma_transforms",-  "ecma_visit",-] }-swc_error_reporters = { path = "../../crates/swc_error_reporters" }-swc_malloc = { path = "../../crates/swc_malloc" }-swc_nodejs_common = { path = "../../crates/swc_nodejs_common" }

deps/swc/bindings/binding_minifier_node/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.\ No newline at end of file

deps/swc/bindings/binding_minifier_node/build.rs

deleted file mode 100644@@ -1,23 +0,0 @@-use std::{-    env,-    fs::File,-    io::{BufWriter, Write},-    path::Path,-};--extern crate napi_build;--fn main() {-    let out_dir = env::var("OUT_DIR").expect("Outdir should exist");-    let dest_path = Path::new(&out_dir).join("triple.txt");-    let mut f =-        BufWriter::new(File::create(dest_path).expect("Failed to create target triple text"));-    write!(-        f,-        "{}",-        env::var("TARGET").expect("Target should be specified")-    )-    .expect("Failed to write target triple text");--    napi_build::setup();-}

deps/swc/bindings/binding_minifier_node/src/lib.rs

deleted file mode 100644@@ -1,31 +0,0 @@-#![recursion_limit = "2048"]-#![allow(dead_code)]--#[macro_use]-extern crate napi_derive;--extern crate swc_malloc;--use std::{env, panic::set_hook};--use backtrace::Backtrace;--mod minify;-mod util;--#[napi_derive::module_init]-fn init() {-    if cfg!(debug_assertions) || env::var("SWC_DEBUG").unwrap_or_default() == "1" {-        set_hook(Box::new(|panic_info| {-            let backtrace = Backtrace::new();-            println!("Panic: {panic_info:?}\nBacktrace: {backtrace:?}");-        }));-    }-}--/// Hack for `Type Generation`-#[napi(object)]-pub struct TransformOutput {-    pub code: String,-    pub map: Option<String>,-}

deps/swc/bindings/binding_minifier_node/src/minify.rs

deleted file mode 100644@@ -1,285 +0,0 @@-use std::sync::Arc;--use anyhow::{Context, Error};-use napi::{-    bindgen_prelude::{AbortSignal, AsyncTask, Buffer, External},-    Task,-};-use swc_compiler_base::{-    minify_file_comments, parse_js, IdentCollector, PrintArgs, SourceMapsConfig, TransformOutput,-};-use swc_config::types::BoolOr;-use swc_core::{-    common::{-        comments::{Comments, SingleThreadedComments},-        sync::Lrc,-        FileName, Mark, SourceMap,-    },-    ecma::{-        minifier::{-            js::{JsMinifyCommentOption, JsMinifyOptions},-            option::{MangleCache, MinifyOptions, SimpleMangleCache, TopLevelOptions},-        },-        parser::{EsSyntax, Syntax},-        transforms::base::{fixer::fixer, hygiene::hygiene, resolver},-        visit::{VisitMutWith, VisitWith},-    },-};-use swc_nodejs_common::{deserialize_json, get_deserialized, MapErr};--use crate::util::try_with;--#[napi(object, object_to_js = false)]-pub struct NapiMinifyExtra {-    #[napi(ts_type = "object")]-    pub mangle_name_cache: Option<&'static NameMangleCache>,-}--struct MinifyTask {-    input: Option<String>,-    options: String,-    extras: Option<NapiMinifyExtra>,-}--fn do_work(-    input: String,-    options: JsMinifyOptions,-    extras: NapiMinifyExtra,-) -> anyhow::Result<TransformOutput> {-    let cm: Arc<SourceMap> = Arc::default();--    let fm = cm.new_source_file(FileName::Anon.into(), input);--    try_with(cm.clone(), false, |handler| {-        let target = options.ecma.clone().into();--        let (source_map, orig) = options-            .source_map-            .as_ref()-            .map(|obj| -> Result<_, Error> {-                Ok((-                    SourceMapsConfig::Bool(true),-                    obj.content.as_ref().map(|s| s.to_sourcemap()).transpose()?,-                ))-            })-            .unwrap_as_option(|v| {-                Some(Ok(match v {-                    Some(true) => (SourceMapsConfig::Bool(true), None),-                    _ => (SourceMapsConfig::Bool(false), None),-                }))-            })-            .unwrap()?;--        let mut min_opts = MinifyOptions {-            compress: options-                .compress-                .clone()-                .unwrap_as_option(|default| match default {-                    Some(true) | None => Some(Default::default()),-                    _ => None,-                })-                .map(|v| v.into_config(cm.clone())),-            mangle: options-                .mangle-                .clone()-                .unwrap_as_option(|default| match default {-                    Some(true) | None => Some(Default::default()),-                    _ => None,-                }),-            ..Default::default()-        };--        let comments = SingleThreadedComments::default();--        let module = parse_js(-            cm.clone(),-            fm.clone(),-            handler,-            target,-            Syntax::Es(EsSyntax {-                jsx: true,-                decorators: true,-                decorators_before_export: true,-                import_attributes: true,-                ..Default::default()-            }),-            options.module,-            Some(&comments),-        )-        .context("failed to parse input file")?;--        // top_level defaults to true if module is true--        // https://github.com/swc-project/swc/issues/2254--        if module.is_module() {-            if let Some(opts) = &mut min_opts.compress {-                if opts.top_level.is_none() {-                    opts.top_level = Some(TopLevelOptions { functions: true });-                }-            }--            if let Some(opts) = &mut min_opts.mangle {-                if opts.top_level.is_none() {-                    opts.top_level = Some(true);-                }-            }-        }--        if options.keep_fnames {-            if let Some(opts) = &mut min_opts.compress {-                opts.keep_fnames = true;-            }-            if let Some(opts) = &mut min_opts.mangle {-                opts.keep_fn_names = true;-            }-        }--        let source_map_names = if source_map.enabled() {-            let mut v = IdentCollector {-                names: Default::default(),-            };--            module.visit_with(&mut v);--            v.names-        } else {-            Default::default()-        };--        let unresolved_mark = Mark::new();-        let top_level_mark = Mark::new();--        let is_mangler_enabled = min_opts.mangle.is_some();--        let module = {-            let module = module.apply(resolver(unresolved_mark, top_level_mark, false));--            let mut module = swc_core::ecma::minifier::optimize(-                module,-                cm.clone(),-                Some(&comments),-                None,-                &min_opts,-                &swc_core::ecma::minifier::option::ExtraOptions {-                    unresolved_mark,-                    top_level_mark,-                    mangle_name_cache: extras.mangle_name_cache.map(|s| (*s).clone()),-                },-            );--            if !is_mangler_enabled {-                module.visit_mut_with(&mut hygiene())-            }-            module.visit_mut_with(&mut fixer(Some(&comments as &dyn Comments)));-            module-        };--        let preserve_comments = options-            .format-            .comments-            .clone()-            .into_inner()-            .unwrap_or(BoolOr::Data(JsMinifyCommentOption::PreserveSomeComments));-        let extracted_comments = minify_file_comments(-            &comments,-            preserve_comments,-            options-                .extract_comments-                .clone()-                .into_inner()-                .unwrap_or(BoolOr::Bool(false)),-            options.format.preserve_annotations,-        );--        let mut output = swc_compiler_base::print(-            cm.clone(),-            &module,-            PrintArgs {-                source_file_name: Some(&fm.name.to_string()),-                output_path: options.output_path.clone().map(From::from),-                inline_sources_content: options.inline_sources_content,-                source_map,-                source_map_names: &source_map_names,-                orig,-                comments: Some(&comments),-                emit_source_map_columns: options.emit_source_map_columns,-                preamble: &options.format.preamble,-                codegen_config: swc_core::ecma::codegen::Config::default()-                    .with_target(target)-                    .with_minify(true)-                    .with_ascii_only(options.format.ascii_only)-                    .with_emit_assert_for_import_attributes(-                        options.format.emit_assert_for_import_attributes,-                    ),-                ..Default::default()-            },-        )?;--        if !extracted_comments.is_empty() {-            output.extracted_comments = Some(extracted_comments);-        }--        Ok(output)-    })-}--#[napi]-impl Task for MinifyTask {-    type JsValue = TransformOutput;-    type Output = TransformOutput;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        let input = self.input.take().unwrap();-        let options: JsMinifyOptions = deserialize_json(&self.options)?;--        do_work(input, options, self.extras.take().unwrap()).convert_err()-    }--    fn resolve(&mut self, _env: napi::Env, output: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(output)-    }-}--type NameMangleCache = External<Arc<dyn MangleCache>>;--#[napi(ts_return_type = "object")]-fn new_mangle_name_cache() -> NameMangleCache {-    let cache = Arc::new(SimpleMangleCache::default());-    External::new(cache)-}--#[napi]-fn minify(-    code: Buffer,-    opts: Buffer,-    extras: NapiMinifyExtra,-    signal: Option<AbortSignal>,-) -> AsyncTask<MinifyTask> {-    crate::util::init_default_trace_subscriber();-    let code = String::from_utf8_lossy(code.as_ref()).into_owned();-    let options = String::from_utf8_lossy(opts.as_ref()).into_owned();--    let task = MinifyTask {-        input: Some(code),-        options,-        extras: Some(extras),-    };--    AsyncTask::with_optional_signal(task, signal)-}--#[napi]-pub fn minify_sync(-    code: Buffer,-    opts: Buffer,-    extras: NapiMinifyExtra,-) -> napi::Result<TransformOutput> {-    crate::util::init_default_trace_subscriber();-    let code = String::from_utf8_lossy(code.as_ref()).into_owned();-    let opts = get_deserialized(opts)?;--    let cm = Lrc::new(SourceMap::default());--    try_with(cm.clone(), false, |_| do_work(code, opts, extras)).convert_err()-}

deps/swc/bindings/binding_minifier_node/src/util.rs

deleted file mode 100644@@ -1,65 +0,0 @@-#![deny(warnings)]--use std::panic::{catch_unwind, AssertUnwindSafe};--use anyhow::{anyhow, Error};-use napi::Env;-use swc_core::common::{errors::Handler, sync::Lrc, SourceMap, GLOBALS};-use swc_error_reporters::handler::try_with_handler;--static TARGET_TRIPLE: &str = include_str!(concat!(env!("OUT_DIR"), "/triple.txt"));--#[napi]-pub fn get_target_triple() -> napi::Result<String> {-    Ok(TARGET_TRIPLE.to_string())-}--#[napi]-pub fn init_custom_trace_subscriber(-    _env: Env,-    _trace_out_file_path: Option<String>,-) -> napi::Result<()> {-    Ok(())-}--#[cfg_attr(debug_assertions, tracing::instrument(level = "trace", skip_all))]-pub fn try_with<F, Ret>(cm: Lrc<SourceMap>, skip_filename: bool, op: F) -> Result<Ret, Error>-where-    F: FnOnce(&Handler) -> Result<Ret, Error>,-{-    GLOBALS-        .set(&Default::default(), || {-            try_with_handler(-                cm,-                swc_error_reporters::handler::HandlerOpts {-                    skip_filename,-                    ..Default::default()-                },-                |handler| {-                    //-                    let result = catch_unwind(AssertUnwindSafe(|| op(handler)));--                    let p = match result {-                        Ok(v) => return v,-                        Err(v) => v,-                    };--                    if let Some(s) = p.downcast_ref::<String>() {-                        Err(anyhow!("failed to handle: {s}"))-                    } else if let Some(s) = p.downcast_ref::<&str>() {-                        Err(anyhow!("failed to handle: {s}"))-                    } else {-                        Err(anyhow!("failed to handle with unknown panic message"))-                    }-                },-            )-        })-        .map_err(|e| e.to_pretty_error())-}--// This was originally under swc_nodejs_common, but this is not a public-// interface for the custom binary - they should choose own trace initialization-// instead. Will keep as hidden for now until there's proper usecase.--/// Deprecated no-op kept for compatibility with existing binding entrypoints.-pub fn init_default_trace_subscriber() {}

deps/swc/bindings/binding_minifier_wasm/Cargo.toml

deleted file mode 100644@@ -1,51 +0,0 @@-[package]-authors     = ["강동윤 <kdy1997.dev@gmail.com>"]-description = "wasm module for swc"-edition     = { workspace = true }-license     = { workspace = true }-name        = "binding_minifier_wasm"-publish     = false-repository  = { workspace = true }-version     = "1.16.18"--[lib]-bench      = false-crate-type = ["cdylib"]--[features]-default = ["swc_v1"]-swc_v1  = []-swc_v2  = []-# This feature exists to allow cargo operations-# [TODO]: this is disabled due to signature mismatch between host_native and host_js,-# which causes build errors like-# .call(&mut self.store, ptr.0, ptr.1)-#   |                  ^^^^ the trait `NativeWasmTypeInto` is not implemented for `u32`-#   |-#   = help: the following other types implement trait `NativeWasmTypeInto`:-#             f32-#             f64-#             i32-#             i64-#             u128-plugin = []--[dependencies]-getrandom = { workspace = true, features = ["wasm_js"] }-serde = { workspace = true, features = ["derive"] }-swc_core = { path = "../../crates/swc_core", features = [-  "ecma_ast_serde",-  "ecma_codegen",-  "binding_macro_wasm",-  "ecma_transforms",-  "ecma_visit",-] }-tracing = { workspace = true, features = ["max_level_off"] }-wasm-bindgen = { workspace = true, features = ["enable-interning"] }--[package.metadata.wasm-pack.profile.release]-wasm-opt = false--[package.metadata.cargo-shear]-# ignored, as they are only used to enable features-ignored = ["getrandom"]

deps/swc/bindings/binding_minifier_wasm/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.\ No newline at end of file

deps/swc/bindings/binding_minifier_wasm/package.json

deleted file mode 100644@@ -1,5 +0,0 @@-{-    "devDependencies": {-        "@rstest/core": "^0.7.8"-    }-}

deps/swc/bindings/binding_minifier_wasm/rstest.config.mjs

deleted file mode 100644@@ -1,4 +0,0 @@-export default {-    include: ["__tests__/**/*.{js,jsx,ts,tsx}"],-    globals: true,-};

deps/swc/bindings/binding_minifier_wasm/scripts/test.sh

deleted file mode 100755@@ -1,6 +0,0 @@-#!/usr/bin/env bash--set -eu--wasm-pack build --out-name wasm --release --scope=swc --target nodejs-npx rstest $@\ No newline at end of file

deps/swc/bindings/binding_minifier_wasm/src/lib.rs

deleted file mode 100644@@ -1,14 +0,0 @@-use swc_core::binding_macros::{build_minify, build_minify_sync};-use wasm_bindgen::prelude::*;-mod types;--/// Custom interface definitions for the @swc/wasm's public interface instead of-/// auto generated one, which is not reflecting most of types in detail.-#[wasm_bindgen(typescript_custom_section)]-const INTERFACE_DEFINITIONS: &'static str = r#"-export function minify(src: string, opts?: JsMinifyOptions): Promise<Output>;-export function minifySync(code: string, opts?: JsMinifyOptions): Output;-"#;--build_minify_sync!(#[wasm_bindgen(js_name = "minifySync", skip_typescript)]);-build_minify!(#[wasm_bindgen(js_name = "minify", skip_typescript)]);

deps/swc/bindings/binding_minifier_wasm/src/types.rs

deleted file mode 100644@@ -1,2922 +0,0 @@-use wasm_bindgen::prelude::wasm_bindgen;--/// This is direct copy-paste from `node-swc/src/types` to support typed-/// interfaces for @swc/wasm as same as @swc/core.-///-/// While this is redundant, wasm-bindgen does not support to import these types-/// effeciently (https://github.com/rustwasm/wasm-bindgen/issues/2417). Once there is an upstream support this'll-/// be removed.-///-/// Note while these options being accepted by `@swc/wasm`, this doesn't mean-/// all of runtime feature parity is gauranteed. There will be some improvement-/// to handle those differences.-#[wasm_bindgen(typescript_custom_section)]-const SWC_TYPES_DEFINITION: &'static str = r#"-export interface Plugin {-  (module: Program): Program;-}--// TODO:-export type ParseOptions = ParserConfig & {-  comments?: boolean;-  script?: boolean;-  /**-   * Defaults to es3.-   */-  target?: JscTarget;-};--export type TerserEcmaVersion = 5 | 2015 | 2016 | string | number;--export interface JsMinifyOptions {-  compress?: TerserCompressOptions | boolean,--  format?: JsFormatOptions & ToSnakeCaseProperties<JsFormatOptions>,--  mangle?: TerserMangleOptions | boolean,--  ecma?: TerserEcmaVersion,--  keep_classnames?: boolean,--  keep_fnames?: boolean,--  module?: boolean,--  safari10?: boolean--  toplevel?: boolean--  sourceMap?: boolean--  /**-   * Serializable subset of terser-webpack-plugin's `extractComments`.-   * `true` behaves like `'some'`.-   */-  extractComments?: boolean | "some" | "all" | { regex: string }--  outputPath?: string--  inlineSourcesContent?: boolean-}--/**- * @example ToSnakeCase<'indentLevel'> == 'indent_level'- */-type ToSnakeCase<T extends string> = T extends `${infer A}${infer B}`-  ? `${A extends Lowercase<A> ? A : `_${Lowercase<A>}`}${ToSnakeCase<B>}`-  : T--/**- * @example ToSnakeCaseProperties<{indentLevel: 3}> == {indent_level: 3}- */-type ToSnakeCaseProperties<T> = {-  [K in keyof T as (K extends string ? ToSnakeCase<K> : K)]: T[K]-}--/**- * These properties are mostly not implemented yet,- * but it exists to support passing terser config to swc minify- * without modification.- */-export interface JsFormatOptions {-  /**-   * Currently noop.-   * @default false-   * @alias ascii_only-   */-  asciiOnly?: boolean--  /**-   * Currently noop.-   * @default false-   */-  beautify?: boolean--  /**-   * Currently noop.-   * @default false-   */-  braces?: boolean--  /**-   * - `false`: removes all comments-   * - `'some'`: preserves some comments-   * - `'all'`: preserves all comments-   * - `{ regex: string }`: preserves comments that match the regex-   * @default false-   */-  comments?: false | "some" | "all" | { regex: string };--  /**-   * Currently noop.-   * @default 5-   */-  ecma?: TerserEcmaVersion--  /**-   * Currently noop.-   * @alias indent_level-   */-  indentLevel?: number--  /**-   * Currently noop.-   * @alias indent_start-   */-  indentStart?: number--  /**-   * Currently noop.-   * @alias inline_script-   */-  inlineScript?: number--  /**-   * Currently noop.-   * @alias keep_numbers-   */-  keepNumbers?: number--  /**-   * Currently noop.-   * @alias keep_quoted_props-   */-  keepQuotedProps?: boolean--  /**-   * Currently noop.-   * @alias max_line_len-   */-  maxLineLen?: number | false--  /**-   * Currently noop.-   */-  preamble?: string--  /**-   * Currently noop.-   * @alias quote_keys-   */-  quoteKeys?: boolean--  /**-   * Currently noop.-   * @alias quote_style-   */-  quoteStyle?: boolean--  /**-   * Currently noop.-   * @alias preserve_annotations-   */-  preserveAnnotations?: boolean--  /**-   * Currently noop.-   */-  safari10?: boolean--  /**-   * Currently noop.-   */-  semicolons?: boolean--  /**-   * Currently noop.-   */-  shebang?: boolean--  /**-   * Currently noop.-   */-  webkit?: boolean--  /**-   * Currently noop.-   * @alias wrap_iife-   */-  wrapIife?: boolean--  /**-   * Currently noop.-   * @alias wrap_func_args-   */-  wrapFuncArgs?: boolean-}--export interface TerserCompressOptions {-  arguments?: boolean,-  arrows?: boolean,---  booleans?: boolean,---  booleans_as_integers?: boolean,---  collapse_vars?: boolean,---  comparisons?: boolean,---  computed_props?: boolean,---  conditionals?: boolean,---  dead_code?: boolean,--  defaults?: boolean,---  directives?: boolean,---  drop_console?: boolean,---  drop_debugger?: boolean,--  ecma?: TerserEcmaVersion,---  evaluate?: boolean,---  expression?: boolean,---  global_defs?: any,---  hoist_funs?: boolean,---  hoist_props?: boolean,---  hoist_vars?: boolean,---  ie8?: boolean,---  if_return?: boolean,---  inline?: 0 | 1 | 2 | 3---  join_vars?: boolean,---  keep_classnames?: boolean,---  keep_fargs?: boolean,---  keep_fnames?: boolean,---  keep_infinity?: boolean,---  loops?: boolean,-  // module        : false,--  negate_iife?: boolean,---  passes?: number,---  properties?: boolean,---  pure_getters?: any,---  pure_funcs?: string[],---  reduce_funcs?: boolean,---  reduce_vars?: boolean,---  sequences?: any,---  side_effects?: boolean,---  switches?: boolean,---  top_retain?: any,---  toplevel?: any,---  typeofs?: boolean,---  unsafe?: boolean,---  unsafe_passes?: boolean,---  unsafe_arrows?: boolean,---  unsafe_comps?: boolean,---  unsafe_function?: boolean,---  unsafe_math?: boolean,---  unsafe_symbols?: boolean,---  unsafe_methods?: boolean,---  unsafe_proto?: boolean,---  unsafe_regexp?: boolean,---  unsafe_undefined?: boolean,---  unused?: boolean,---  module?: boolean,-}--export interface TerserMangleOptions {-  props?: TerserManglePropertiesOptions,--  toplevel?: boolean,--  keep_classnames?: boolean,--  keep_fnames?: boolean,--  keep_private_props?: boolean,--  ie8?: boolean,--  safari10?: boolean,--  reserved?: string[],-}--export interface TerserManglePropertiesOptions {--}---/**- * Programmatic options.- */-export interface Options extends Config {-  /**-   * If true, a file is parsed as a script instead of module.-   */-  script?: boolean;--  /**-   * The working directory that all paths in the programmatic-   * options will be resolved relative to.-   *-   * Defaults to `process.cwd()`.-   */-  cwd?: string;-  caller?: CallerOptions;-  /** The filename associated with the code currently being compiled,-   * if there is one. The filename is optional, but not all of Swc's-   * functionality is available when the filename is unknown, because a-   * subset of options rely on the filename for their functionality.-   *-   * The three primary cases users could run into are:-   *-   * - The filename is exposed to plugins. Some plugins may require the-   * presence of the filename.-   * - Options like "test", "exclude", and "ignore" require the filename-   * for string/RegExp matching.-   * - .swcrc files are loaded relative to the file being compiled.-   * If this option is omitted, Swc will behave as if swcrc: false has been set.-   */-  filename?: string;--  /**-   * The initial path that will be processed based on the "rootMode" to-   * determine the conceptual root folder for the current Swc project.-   * This is used in two primary cases:-   *-   * - The base directory when checking for the default "configFile" value-   * - The default value for "swcrcRoots".-   *-   * Defaults to `opts.cwd`-   */-  root?: string;--  /**-   * This option, combined with the "root" value, defines how Swc chooses-   * its project root. The different modes define different ways that Swc-   * can process the "root" value to get the final project root.-   *-   * "root" - Passes the "root" value through as unchanged.-   * "upward" - Walks upward from the "root" directory, looking for a directory-   * containing a .swcrc file, and throws an error if a .swcrc-   * is not found.-   * "upward-optional" - Walk upward from the "root" directory, looking for-   * a directory containing a .swcrc file, and falls back to "root"-   *  if a .swcrc is not found.-   *-   *-   * "root" is the default mode because it avoids the risk that Swc-   * will accidentally load a .swcrc that is entirely outside-   * of the current project folder. If you use "upward-optional",-   * be aware that it will walk up the directory structure all the-   * way to the filesystem root, and it is always possible that someone-   * will have a forgotten .swcrc in their home directory,-   * which could cause unexpected errors in your builds.-   *-   *-   * Users with monorepo project structures that run builds/tests on a-   * per-package basis may well want to use "upward" since monorepos-   * often have a .swcrc in the project root. Running Swc-   * in a monorepo subdirectory without "upward", will cause Swc-   * to skip loading any .swcrc files in the project root,-   * which can lead to unexpected errors and compilation failure.-   */-  rootMode?: "root" | "upward" | "upward-optional";--  /**-   * The current active environment used during configuration loading.-   * This value is used as the key when resolving "env" configs,-   * and is also available inside configuration functions, plugins,-   * and presets, via the api.env() function.-   *-   * Defaults to `process.env.SWC_ENV || process.env.NODE_ENV || "development"`-   */-  envName?: string;--  /**-   * Defaults to searching for a default `.swcrc` file, but can-   * be passed the path of any JS or JSON5 config file.-   *-   *-   * NOTE: This option does not affect loading of .swcrc files,-   * so while it may be tempting to do configFile: "./foo/.swcrc",-   * it is not recommended. If the given .swcrc is loaded via the-   * standard file-relative logic, you'll end up loading the same-   * config file twice, merging it with itself. If you are linking-   * a specific config file, it is recommended to stick with a-   * naming scheme that is independent of the "swcrc" name.-   *-   * Defaults to `path.resolve(opts.root, ".swcrc")`-   */-  configFile?: string | boolean;--  /**-   * true will enable searching for configuration files relative to the "filename" provided to Swc.-   *-   * A swcrc value passed in the programmatic options will override one set within a configuration file.-   *-   * Note: .swcrc files are only loaded if the current "filename" is inside of-   *  a package that matches one of the "swcrcRoots" packages.-   *-   *-   * Defaults to true as long as the filename option has been specified-   */-  swcrc?: boolean;--  /**-   * By default, Babel will only search for .babelrc files within the "root" package-   *  because otherwise Babel cannot know if a given .babelrc is meant to be loaded,-   *  or if it's "plugins" and "presets" have even been installed, since the file-   *  being compiled could be inside node_modules, or have been symlinked into the project.-   *-   *-   * This option allows users to provide a list of other packages that should be-   * considered "root" packages when considering whether to load .babelrc files.-   *-   *-   * For example, a monorepo setup that wishes to allow individual packages-   * to have their own configs might want to do-   *-   *-   *-   * Defaults to `opts.root`-   */-  swcrcRoots?: boolean | MatchPattern | MatchPattern[];--  /**-   * `true` will attempt to load an input sourcemap from the file itself, if it-   * contains a //# sourceMappingURL=... comment. If no map is found, or the-   * map fails to load and parse, it will be silently discarded.-   *-   *  If an object is provided, it will be treated as the source map object itself.-   *-   * Defaults to `true`.-   */-  inputSourceMap?: boolean | string;--  /**-   * The name to use for the file inside the source map object.-   *-   * Defaults to `path.basename(opts.filenameRelative)` when available, or `"unknown"`.-   */-  sourceFileName?: string;--  /**-   * The sourceRoot fields to set in the generated source map, if one is desired.-   */-  sourceRoot?: string;--  plugin?: Plugin;--  isModule?: boolean | 'unknown';--  /**-   * Destination path. Note that this value is used only to fix source path-   * of source map files and swc does not write output to this path.-   */-  outputPath?: string-}--export interface CallerOptions {-  name: string;-  [key: string]: any;-}--export type Swcrc = Config | Config[];--/**- * .swcrc- */-export interface Config {-  /**-   * Note: The type is string because it follows rust's regex syntax.-   */-  test?: string | string[];-  /**-   * Note: The type is string because it follows rust's regex syntax.-   */-  exclude?: string | string[];-  env?: EnvConfig;-  jsc?: JscConfig;-  module?: ModuleConfig;-  minify?: boolean;--  /**-   * - true to generate a sourcemap for the code and include it in the result object.-   * - "inline" to generate a sourcemap and append it as a data URL to the end of the code, but not include it in the result object.-   *-   * `swc-cli` overloads some of these to also affect how maps are written to disk:-   *-   * - true will write the map to a .map file on disk-   * - "inline" will write the file directly, so it will have a data: containing the map-   * - Note: These options are bit weird, so it may make the most sense to just use true-   *  and handle the rest in your own code, depending on your use case.-   */-  sourceMaps?: boolean | "inline";--  inlineSourcesContent?: boolean-}--/**- * Configuration ported from babel-preset-env- */-export interface EnvConfig {-  mode?: "usage" | "entry";-  debug?: boolean;-  dynamicImport?: boolean;--  loose?: boolean;--  /// Skipped es features.-  ///-  /// e.g.)-  ///  - `core-js/modules/foo`-  skip?: string[];--  include?: string[];--  exclude?: string[];--  /**-   * The version of the used core js.-   *-   */-  coreJs?: string;--  targets?: any;--  path?: string;--  shippedProposals?: boolean;--  /**-   * Enable all transforms-   */-  forceAllTransforms?: boolean;-}--export interface JscConfig {-  loose?: boolean;--  /**-   * Defaults to EsParserConfig-   */-  parser?: ParserConfig;-  transform?: TransformConfig;-  /**-   * Use `@swc/helpers` instead of inline helpers.-   */-  externalHelpers?: boolean;--  /**-   * Defaults to `es3` (which enabled **all** pass).-   */-  target?: JscTarget;--  /**-   * Keep class names.-   */-  keepClassNames?: boolean--  experimental?: {-    optimizeHygiene?: boolean,-    keepImportAssertions?: boolean,-    /**-     * Specify the location where SWC stores its intermediate cache files.-     * Currently only transform plugin uses this. If not specified, SWC will-     * create `.swc` directories.-     */-    cacheRoot?: string;-    /**-     * List of custom transform plugins written in WebAssembly.-     * First parameter of tuple indicates the name of the plugin - it can be either-     * a name of the npm package can be resolved, or absolute path to .wasm binary.-     *-     * Second parameter of tuple is JSON based configuration for the plugin.-     */-    plugins?: Array<[string, Record<string, any>]>-  },--  baseUrl?: string--  paths?: {-    [from: string]: string[]-  }--  minify?: JsMinifyOptions;--  preserveAllComments?: boolean;--  output?: {-    /**-     * This can be used to keep the output ascii-only.-     * If this option is set, `minify.format.asciiOnly` will be ignored.-     * @default 'utf8'-     */-    charset?: 'utf8' | 'ascii';-  }-}--export type JscTarget =-  | "es3"-  | "es5"-  | "es2015"-  | "es2016"-  | "es2017"-  | "es2018"-  | "es2019"-  | "es2020"-  | "es2021"-  | "es2022"-  | "esnext";--export type ParserConfig = TsParserConfig | EsParserConfig | FlowParserConfig;-export interface TsParserConfig {-  syntax: "typescript";-  /**-   * Defaults to `false`.-   */-  tsx?: boolean;-  /**-   * Defaults to `false`.-   */-  decorators?: boolean;-  /**-   * Defaults to `false`-   */-  dynamicImport?: boolean;-}--export interface FlowParserConfig {-  syntax: "flow";-  /**-   * Defaults to `false`.-   */-  jsx?: boolean;-  /**-   * Defaults to `false`.-   */-  all?: boolean;-  /**-   * Defaults to `false`.-   */-  requireDirective?: boolean;-  /**-   * Defaults to `false`.-   */-  enums?: boolean;-  /**-   * Defaults to `false`.-   */-  decorators?: boolean;-  /**-   * Defaults to `false`.-   */-  components?: boolean;-  /**-   * Defaults to `false`.-   */-  patternMatching?: boolean;-}--export interface EsParserConfig {-  syntax: "ecmascript";-  /**-   * Defaults to false.-   */-  jsx?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  numericSeparator?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  classPrivateProperty?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  privateMethod?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  classProperty?: boolean;-  /**-   * Defaults to `false`-   */-  functionBind?: boolean;-  /**-   * Defaults to `false`-   */-  decorators?: boolean;-  /**-   * Defaults to `false`-   */-  decoratorsBeforeExport?: boolean;-  /**-   * Defaults to `false`-   */-  exportDefaultFrom?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  exportNamespaceFrom?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  dynamicImport?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  nullishCoalescing?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  optionalChaining?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  importMeta?: boolean;-  /**-   * @deprecated Always true because it's in ecmascript spec.-   */-  topLevelAwait?: boolean;-  /**-   * Defaults to `false`-   */-  importAssertions?: boolean;-}--/**- * Options for transform.- */-export interface TransformConfig {-  /**-   * Effective only if `syntax` supports ƒ.-   */-  react?: ReactConfig;--  constModules?: ConstModulesConfig;--  /**-   * Defaults to null, which skips optimizer pass.-   */-  optimizer?: OptimizerConfig;--  /**-   * https://swc.rs/docs/configuring-swc.html#jsctransformlegacydecorator-   */-  legacyDecorator?: boolean;--  /**-   * https://swc.rs/docs/configuring-swc.html#jsctransformdecoratormetadata-   */-  decoratorMetadata?: boolean;--  treatConstEnumAsEnum?: boolean;--  useDefineForClassFields?: boolean;-}--export interface ReactConfig {-  /**-   * Replace the function used when compiling JSX expressions.-   *-   * Defaults to `React.createElement`.-   */-  pragma?: string;-  /**-   * Replace the component used when compiling JSX fragments.-   *-   * Defaults to `React.Fragment`-   */-  pragmaFrag?: string;-  /**-   * Toggles whether or not to throw an error if a XML namespaced tag name is used. For example:-   * `<f:image />`-   *-   * Though the JSX spec allows this, it is disabled by default since React's-   * JSX does not currently have support for it.-   *-   */-  throwIfNamespace?: boolean;-  /**-   * Toggles plugins that aid in development, such as @swc/plugin-transform-react-jsx-self-   * and @swc/plugin-transform-react-jsx-source.-   *-   * Defaults to `false`,-   *-   */-  development?: boolean;-  /**-   * Use `Object.assign()` instead of `_extends`. Defaults to false.-   * @deprecated-   */-  useBuiltins?: boolean;--  /**-   * Enable fast refresh feature for React app-   */-  refresh?:-    | boolean-    | {-          /**-           * Identifier for the `react-refresh` register function.-           *-           * Defaults to `$RefreshReg$`-           */-          refreshReg?: string;-          /**-           * Identifier for the `react-refresh` signature function.-           *-           * Defaults to `$RefreshSig$`-           */-          refreshSig?: string;-          /**-           * Flag to emit full signatures.-           *-           * Defaults to `false`-           */-          emitFullSignatures?: boolean;-      };--  /**-   * Decides which runtime to use when transforming JSX.-   * - `"automatic"` - Automatically imports the functions that JSX transpiles to.-   * This is the modern approach introduced in React 17+ that eliminates the need to-   * manually import React in every file that uses JSX.-   * - `"classic"` - Uses the traditional JSX transform that relies on `React.createElement`-   * calls. Requires React to be in scope, which was the standard behavior before React 17.-   * - `"preserve"` - Leaves JSX syntax unchanged without transforming it.-   * @default "classic"-   */-  runtime?: "automatic" | "classic" | "preserve";--  /**-   * Declares the module specifier to be used for importing the `jsx` and `jsxs` factory-   * functions when using `runtime` 'automatic'-   * @default "react"-   */-  importSource?: string;-}-/**- *  - `import { DEBUG } from '@ember/env-flags';`- *  - `import { FEATURE_A, FEATURE_B } from '@ember/features';`- *- * See: https://github.com/swc-project/swc/issues/18#issuecomment-466272558- */-export interface ConstModulesConfig {-  globals?: {-    [module: string]: {-      [name: string]: string;-    };-  };-}--/// https://swc.rs/docs/configuring-swc.html#jsctransformoptimizerjsonify-export interface OptimizerConfig {-  /// https://swc.rs/docs/configuration/compilation#jsctransformoptimizersimplify-  simplify?: boolean;-  /// https://swc.rs/docs/configuring-swc.html#jsctransformoptimizerglobals-  globals?: GlobalPassOption;-  /// https://swc.rs/docs/configuring-swc.html#jsctransformoptimizerjsonify-  jsonify?: { minCost: number };-}--/**- * Options for inline-global pass.- */-export interface GlobalPassOption {-  /**-   * Global variables.-   *-   * e.g. `{ __DEBUG__: true }`-   */-  vars?: { [key: string]: string };--  /**-   * Name of environment variables to inline.-   *-   * Defaults to `[]`-   */-  envs?: string[] | Record<string, string>;-}--export type ModuleConfig = Es6Config | CommonJsConfig | UmdConfig | AmdConfig | NodeNextConfig | SystemjsConfig;--export interface BaseModuleConfig {-  /**-   * By default, when using exports with babel a non-enumerable `__esModule`-   * property is exported. In some cases this property is used to determine-   * if the import is the default export or if it contains the default export.-   *-   * In order to prevent the __esModule property from being exported, you-   *  can set the strict option to true.-   *-   * Defaults to `false`.-   */-  strict?: boolean;--  /**-   * Emits 'use strict' directive.-   *-   * Defaults to `true`.-   */-  strictMode?: boolean;--  /**-   * Changes Babel's compiled import statements to be lazily evaluated when their imported bindings are used for the first time.-   *-   * This can improve initial load time of your module because evaluating dependencies up-   *  front is sometimes entirely un-necessary. This is especially the case when implementing-   *  a library module.-   *-   *-   * The value of `lazy` has a few possible effects:-   *-   *  - `false` - No lazy initialization of any imported module.-   *  - `true` - Do not lazy-initialize local `./foo` imports, but lazy-init `foo` dependencies.-   *-   * Local paths are much more likely to have circular dependencies, which may break if loaded lazily,-   * so they are not lazy by default, whereas dependencies between independent modules are rarely cyclical.-   *-   *  - `Array<string>` - Lazy-initialize all imports with source matching one of the given strings.-   *-   * ------   *-   * The two cases where imports can never be lazy are:-   *-   *  - `import "foo";`-   *-   * Side-effect imports are automatically non-lazy since their very existence means-   *  that there is no binding to later kick off initialization.-   *-   *  - `export * from "foo"`-   *-   * Re-exporting all names requires up-front execution because otherwise there is no-   * way to know what names need to be exported.-   *-   * Defaults to `false`.-   */-  lazy?: boolean | string[];-  /**-   * @deprecated  Use the `importInterop` option instead.-   *-   * By default, when using exports with swc a non-enumerable __esModule property is exported.-   * This property is then used to determine if the import is the default export or if-   *  it contains the default export.-   *-   * In cases where the auto-unwrapping of default is not needed, you can set the noInterop option-   *  to true to avoid the usage of the interopRequireDefault helper (shown in inline form above).-   *-   * Defaults to `false`.-   */-  noInterop?: boolean;-  /**-   * Defaults to `swc`.-   *-   * CommonJS modules and ECMAScript modules are not fully compatible.-   * However, compilers, bundlers and JavaScript runtimes developed different strategies-   * to make them work together as well as possible.-   *-   * - `swc` (alias: `babel`)-   *-   * When using exports with `swc` a non-enumerable `__esModule` property is exported-   * This property is then used to determine if the import is the default export-   * or if it contains the default export.-   *-   * ```javascript-   * import foo from "foo";-   * import { bar } from "bar";-   * foo;-   * bar;-   *-   * // Is compiled to ...-   *-   * "use strict";-   *-   * function _interop_require_default(obj) {-   *   return obj && obj.__esModule ? obj : { default: obj };-   * }-   *-   * var _foo = _interop_require_default(require("foo"));-   * var _bar = require("bar");-   *-   * _foo.default;-   * _bar.bar;-   * ```-   *-   * When this import interop is used, if both the imported and the importer module are compiled-   * with swc they behave as if none of them was compiled.-   *-   * This is the default behavior.-   *-   * - `node`-   *-   * When importing CommonJS files (either directly written in CommonJS, or generated with a compiler)-   * Node.js always binds the `default` export to the value of `module.exports`.-   *-   * ```javascript-   * import foo from "foo";-   * import { bar } from "bar";-   * foo;-   * bar;-   *-   * // Is compiled to ...-   *-   * "use strict";-   *-   * var _foo = require("foo");-   * var _bar = require("bar");-   *-   * _foo;-   * _bar.bar;-   * ```-   * This is not exactly the same as what Node.js does since swc allows accessing any property of `module.exports`-   * as a named export, while Node.js only allows importing statically analyzable properties of `module.exports`.-   * However, any import working in Node.js will also work when compiled with swc using `importInterop: "node"`.-   *-   * - `none`-   *-   * If you know that the imported file has been transformed with a compiler that stores the `default` export on-   * `exports.default` (such as swc or Babel), you can safely omit the `_interop_require_default` helper.-   *-   * ```javascript-   * import foo from "foo";-   * import { bar } from "bar";-   * foo;-   * bar;-   *-   * // Is compiled to ...-   *-   * "use strict";-   *-   * var _foo = require("foo");-   * var _bar = require("bar");-   *-   * _foo.default;-   * _bar.bar;-   * ```-   */-  importInterop?: "swc" | "babel" | "node" | "none";-  /**-   * Output extension for generated files.-   *-   * Defaults to `js`.-  */-  outFileExtension?: "js" | "mjs" | "cjs";-  /**-   * Emits `cjs-module-lexer` annotation-   * `cjs-module-lexer` is used in Node.js core for detecting the named exports available when importing a CJS module into ESM.-   * swc will emit `cjs-module-lexer` detectable annotation with this option enabled.-   *-   * Defaults to `true` if import_interop is Node, else `false`-   */-  exportInteropAnnotation?: boolean;-  /**-   * If set to true, dynamic imports will be preserved.-   */-  ignoreDynamic?: boolean;-  allowTopLevelThis?: boolean;-  preserveImportMeta?: boolean;-  /**-   * If set to true, This will resolve top .mjs-   */-  resolveFully?: boolean;-}--export interface Es6Config extends BaseModuleConfig {-  type: "es6";-}--export interface NodeNextConfig extends BaseModuleConfig {-  type: "nodenext";-}--export interface CommonJsConfig extends BaseModuleConfig {-  type: "commonjs";-}--export interface UmdConfig extends BaseModuleConfig {-  type: "umd";-  globals?: { [key: string]: string };-}--export interface AmdConfig extends BaseModuleConfig {-  type: "amd";-  moduleId?: string;-  moduleRoot?: string;-}-export interface SystemjsConfig {-  type: "systemjs";-  allowTopLevelThis?: boolean;-}-export interface Output {-  /**-   * Transformed code-   */-  code: string;-  /**-   * Sourcemap (**not** base64 encoded)-   */-  map?: string;-  /**-   * Extracted comments collected during minification.-   */-  extractedComments?: string[];-}--export interface MatchPattern { }--// --------------------------------// ---------- Ast nodes -----------// ---------------------------------export interface Span {-  start: number;-  end: number;-  ctxt: number;-}--export interface Node {-  type: string;-}--export interface HasSpan {-  span: Span;-}--export interface HasDecorator {-  decorators?: Decorator[];-}--export interface Class extends HasSpan, HasDecorator {-  body: ClassMember[];--  superClass?: Expression;--  isAbstract: boolean;--  typeParams?: TsTypeParameterDeclaration;--  superTypeParams?: TsTypeParameterInstantiation;--  implements: TsExpressionWithTypeArguments[];-}--export type ClassMember =-  | Constructor-  | ClassMethod-  | PrivateMethod-  | ClassProperty-  | PrivateProperty-  | TsIndexSignature-  | EmptyStatement-  | StaticBlock;--export interface ClassPropertyBase extends Node, HasSpan, HasDecorator {-  value?: Expression;--  typeAnnotation?: TsTypeAnnotation;--  isStatic: boolean;--  accessibility?: Accessibility;--  isOptional: boolean;--  isOverride: boolean;--  readonly: boolean;--  definite: boolean;-}--export interface ClassProperty extends ClassPropertyBase {-  type: "ClassProperty";--  key: PropertyName;--  isAbstract: boolean;--  declare: boolean;-}--export interface PrivateProperty extends ClassPropertyBase {-  type: "PrivateProperty";--  key: PrivateName;-}--export interface Param extends Node, HasSpan, HasDecorator {-  type: "Parameter";-  pat: Pattern;-}--export interface Constructor extends Node, HasSpan {-  type: "Constructor";--  key: PropertyName;--  params: (TsParameterProperty | Param)[];--  body?: FunctionBody;--  accessibility?: Accessibility;--  isOptional: boolean;-}--export interface ClassMethodBase extends Node, HasSpan {-  function: Fn;--  kind: MethodKind;--  isStatic: boolean;--  accessibility?: Accessibility;--  isAbstract: boolean;--  isOptional: boolean;--  isOverride: boolean;-}--export interface ClassMethod extends ClassMethodBase {-  type: "ClassMethod";--  key: PropertyName;-}--export interface PrivateMethod extends ClassMethodBase {-  type: "PrivateMethod";--  key: PrivateName;-}--export interface StaticBlock extends Node, HasSpan {-  type: "StaticBlock";--  body: BlockStatement;-}--export interface Decorator extends Node, HasSpan {-  type: "Decorator";--  expression: Expression;-}--export type MethodKind = "method" | "getter" | "setter";--export type Declaration =-  | ClassDeclaration-  | FunctionDeclaration-  | VariableDeclaration-  | TsInterfaceDeclaration-  | TsTypeAliasDeclaration-  | TsEnumDeclaration-  | TsModuleDeclaration;--export interface FunctionDeclaration extends Fn {-  type: "FunctionDeclaration";--  identifier: Identifier;--  declare: boolean;-}--export interface ClassDeclaration extends Class, Node {-  type: "ClassDeclaration";--  identifier: Identifier;--  declare: boolean;-}--export interface VariableDeclaration extends Node, HasSpan {-  type: "VariableDeclaration";--  kind: VariableDeclarationKind;--  declare: boolean;--  declarations: VariableDeclarator[];-}--export type VariableDeclarationKind = "var" | "let" | "const";--export interface VariableDeclarator extends Node, HasSpan {-  type: "VariableDeclarator";--  id: Pattern;--  /// Initialization expression.-  init?: Expression;--  /// Typescript only-  definite: boolean;-}--export type Expression =-  | ThisExpression-  | ArrayExpression-  | ObjectExpression-  | FunctionExpression-  | UnaryExpression-  | UpdateExpression-  | BinaryExpression-  | AssignmentExpression-  | MemberExpression-  | SuperPropExpression-  | ConditionalExpression-  | CallExpression-  | NewExpression-  | SequenceExpression-  | Identifier-  | Literal-  | TemplateLiteral-  | TaggedTemplateExpression-  | ArrowFunctionExpression-  | ClassExpression-  | YieldExpression-  | MetaProperty-  | AwaitExpression-  | ParenthesisExpression-  | JSXMemberExpression-  | JSXNamespacedName-  | JSXEmptyExpression-  | JSXElement-  | JSXFragment-  | TsTypeAssertion-  | TsConstAssertion-  | TsNonNullExpression-  | TsAsExpression-  | TsInstantiation-  | PrivateName-  | OptionalChainingExpression-  | Invalid;--interface ExpressionBase extends Node, HasSpan { }--export interface Identifier extends ExpressionBase {-  type: "Identifier";--  value: string;--  /// TypeScript only. Used in case of an optional parameter.-  optional: boolean;-}--export interface OptionalChainingExpression extends ExpressionBase {-  type: "OptionalChainingExpression";-  questionDotToken: Span;-  /**-   * Call expression or member expression.-   */-  base: MemberExpression | OptionalChainingCall;-}--export interface OptionalChainingCall extends ExpressionBase {-  type: "CallExpression";-  callee: Expression;-  arguments: ExprOrSpread[];-  typeArguments?: TsTypeParameterInstantiation;-}--export interface ThisExpression extends ExpressionBase {-  type: "ThisExpression";-}--export interface ArrayExpression extends ExpressionBase {-  type: "ArrayExpression";--  elements: (ExprOrSpread | undefined)[];-}--export interface ExprOrSpread {-  spread?: Span;-  expression: Expression;-}--export interface ObjectExpression extends ExpressionBase {-  type: "ObjectExpression";--  properties: (SpreadElement | Property)[];-}--export interface Argument {-  spread?: Span;-  expression: Expression;-}--export interface SpreadElement extends Node {-  type: "SpreadElement";--  spread: Span;--  arguments: Expression;-}--export interface UnaryExpression extends ExpressionBase {-  type: "UnaryExpression";--  operator: UnaryOperator;--  argument: Expression;-}--export interface UpdateExpression extends ExpressionBase {-  type: "UpdateExpression";--  operator: UpdateOperator;--  prefix: boolean;--  argument: Expression;-}--export interface BinaryExpression extends ExpressionBase {-  type: "BinaryExpression";--  operator: BinaryOperator;--  left: Expression;--  right: Expression;-}--export interface FunctionExpression extends Fn, ExpressionBase {-  type: "FunctionExpression";--  identifier?: Identifier;-}--export interface ClassExpression extends Class, ExpressionBase {-  type: "ClassExpression";--  identifier?: Identifier;-}--export interface AssignmentExpression extends ExpressionBase {-  type: "AssignmentExpression";--  operator: AssignmentOperator;--  left: Expression | Pattern;--  right: Expression;-}--export interface MemberExpression extends ExpressionBase {-  type: "MemberExpression";--  object: Expression;--  property: Identifier | PrivateName | ComputedPropName;-}--export interface SuperPropExpression extends ExpressionBase {-  type: "SuperPropExpression";--  obj: Super;--  property: Identifier | ComputedPropName;-}--export interface ConditionalExpression extends ExpressionBase {-  type: "ConditionalExpression";--  test: Expression;--  consequent: Expression;--  alternate: Expression;-}--export interface Super extends Node, HasSpan {-  type: "Super";-}--export interface Import extends Node, HasSpan {-  type: "Import";-}--export interface CallExpression extends ExpressionBase {-  type: "CallExpression";--  callee: Super | Import | Expression;--  arguments: Argument[];--  typeArguments?: TsTypeParameterInstantiation;-}--export interface NewExpression extends ExpressionBase {-  type: "NewExpression";--  callee: Expression;--  arguments?: Argument[];--  typeArguments?: TsTypeParameterInstantiation;-}--export interface SequenceExpression extends ExpressionBase {-  type: "SequenceExpression";--  expressions: Expression[];-}--export interface ArrowFunctionExpression extends ExpressionBase {-  type: "ArrowFunctionExpression";--  params: Pattern[];--  body: FunctionBody | Expression;--  async: boolean;--  generator: boolean;--  typeParameters?: TsTypeParameterDeclaration;--  returnType?: TsTypeAnnotation;-}--export interface YieldExpression extends ExpressionBase {-  type: "YieldExpression";--  argument?: Expression;--  delegate: boolean;-}--export interface MetaProperty extends Node, HasSpan {-  type: "MetaProperty";--  kind: "new.target" | "import.meta";-}--export interface AwaitExpression extends ExpressionBase {-  type: "AwaitExpression";--  argument: Expression;-}--export interface TemplateLiteral extends ExpressionBase {-  type: "TemplateLiteral";--  expressions: Expression[];--  quasis: TemplateElement[];-}--export interface TaggedTemplateExpression extends ExpressionBase {-  type: "TaggedTemplateExpression";--  tag: Expression;--  typeParameters?: TsTypeParameterInstantiation;--  template: TemplateLiteral;-}--export interface TemplateElement extends ExpressionBase {-  type: "TemplateElement";--  tail: boolean;-  cooked?: string;-  raw: string;-}--export interface ParenthesisExpression extends ExpressionBase {-  type: "ParenthesisExpression";--  expression: Expression;-}--export interface Fn extends HasSpan, HasDecorator {-  thisParam?: TsThisParameter;--  params: Param[];--  body?: FunctionBody;--  generator: boolean;--  async: boolean;--  typeParameters?: TsTypeParameterDeclaration;--  returnType?: TsTypeAnnotation;-}--interface PatternBase extends Node, HasSpan {-  typeAnnotation?: TsTypeAnnotation;-}--export interface PrivateName extends ExpressionBase {-  type: "PrivateName";--  id: Identifier;-}--export type JSXObject = JSXMemberExpression | Identifier;--export interface JSXMemberExpression extends Node {-  type: "JSXMemberExpression";--  object: JSXObject;-  property: Identifier;-}--/**- * XML-based namespace syntax:- */-export interface JSXNamespacedName extends Node {-  type: "JSXNamespacedName";--  namespace: Identifier;-  name: Identifier;-}--export interface JSXEmptyExpression extends Node, HasSpan {-  type: "JSXEmptyExpression";-}--export interface JSXExpressionContainer extends Node, HasSpan {-  type: "JSXExpressionContainer";--  expression: JSXExpression;-}--export type JSXExpression = JSXEmptyExpression | Expression;--export interface JSXSpreadChild extends Node, HasSpan {-  type: "JSXSpreadChild";--  expression: Expression;-}--export type JSXElementName =-  | Identifier-  | JSXMemberExpression-  | JSXNamespacedName;--export interface JSXOpeningElement extends Node, HasSpan {-  type: "JSXOpeningElement";--  name: JSXElementName;--  attributes: JSXAttributeOrSpread[];--  selfClosing: boolean;--  typeArguments?: TsTypeParameterInstantiation;-}--export type JSXAttributeOrSpread = JSXAttribute | SpreadElement;--export interface JSXClosingElement extends Node, HasSpan {-  type: "JSXClosingElement";--  name: JSXElementName;-}--export interface JSXAttribute extends Node, HasSpan {-  type: "JSXAttribute";--  name: JSXAttributeName;--  value?: JSXAttrValue;-}--export type JSXAttributeName = Identifier | JSXNamespacedName;--export type JSXAttrValue =-  | StringLiteral-  | JSXExpressionContainer-  | JSXElement-  | JSXFragment;--export interface JSXText extends Node, HasSpan {-  type: "JSXText";--  value: string;-  raw: string;-}--export interface JSXElement extends Node, HasSpan {-  type: "JSXElement";--  opening: JSXOpeningElement;-  children: JSXElementChild[];-  closing?: JSXClosingElement;-}--export type JSXElementChild =-  | JSXText-  | JSXExpressionContainer-  | JSXSpreadChild-  | JSXElement-  | JSXFragment;--export interface JSXFragment extends Node, HasSpan {-  type: "JSXFragment";--  opening: JSXOpeningFragment;--  children: JSXElementChild[];--  closing: JSXClosingFragment;-}--export interface JSXOpeningFragment extends Node, HasSpan {-  type: "JSXOpeningFragment";-}--export interface JSXClosingFragment extends Node, HasSpan {-  type: "JSXClosingFragment";-}--export type Literal =-  | StringLiteral-  | BooleanLiteral-  | NullLiteral-  | NumericLiteral-  | BigIntLiteral-  | RegExpLiteral-  | JSXText;--export interface StringLiteral extends Node, HasSpan {-  type: "StringLiteral";--  value: string;--  raw?: string;-}--export interface BooleanLiteral extends Node, HasSpan {-  type: "BooleanLiteral";--  value: boolean;-}--export interface NullLiteral extends Node, HasSpan {-  type: "NullLiteral";-}--export interface RegExpLiteral extends Node, HasSpan {-  type: "RegExpLiteral";--  pattern: string;-  flags: string;-}--export interface NumericLiteral extends Node, HasSpan {-  type: "NumericLiteral";--  value: number;--  raw?: string;-}--export interface BigIntLiteral extends Node, HasSpan {-  type: "BigIntLiteral";--  value: bigint;--  raw?: string;-}--export type ModuleDeclaration =-  | ImportDeclaration-  | ExportDeclaration-  | ExportNamedDeclaration-  | ExportDefaultDeclaration-  | ExportDefaultExpression-  | ExportAllDeclaration-  | TsImportEqualsDeclaration-  | TsExportAssignment-  | TsNamespaceExportDeclaration;--export interface ExportDefaultExpression extends Node, HasSpan {-  type: "ExportDefaultExpression";--  expression: Expression;-}--export interface ExportDeclaration extends Node, HasSpan {-  type: "ExportDeclaration";--  declaration: Declaration;-}--export interface ImportDeclaration extends Node, HasSpan {-  type: "ImportDeclaration";--  specifiers: ImportSpecifier[];--  source: StringLiteral;--  typeOnly: boolean;--  asserts?: ObjectExpression;-}--export interface ExportAllDeclaration extends Node, HasSpan {-  type: "ExportAllDeclaration";--  source: StringLiteral;--  asserts?: ObjectExpression;-}--/**- * - `export { foo } from 'mod'`- * - `export { foo as bar } from 'mod'`- */-export interface ExportNamedDeclaration extends Node, HasSpan {-  type: "ExportNamedDeclaration";--  specifiers: ExportSpecifier[];--  source?: StringLiteral;--  typeOnly: boolean;--  asserts?: ObjectExpression;-}--export interface ExportDefaultDeclaration extends Node, HasSpan {-  type: "ExportDefaultDeclaration";--  decl: DefaultDecl;-}--export type DefaultDecl =-  | ClassExpression-  | FunctionExpression-  | TsInterfaceDeclaration;--export type ImportSpecifier =-  | NamedImportSpecifier-  | ImportDefaultSpecifier-  | ImportNamespaceSpecifier;--/**- * e.g. `import foo from 'mod.js'`- */-export interface ImportDefaultSpecifier extends Node, HasSpan {-  type: "ImportDefaultSpecifier";-  local: Identifier;-}--/**- * e.g. `import * as foo from 'mod.js'`.- */-export interface ImportNamespaceSpecifier extends Node, HasSpan {-  type: "ImportNamespaceSpecifier";--  local: Identifier;-}--/**- * e.g. - `import { foo } from 'mod.js'`- *- * local = foo, imported = None- *- * e.g. `import { foo as bar } from 'mod.js'`- *- * local = bar, imported = Some(foo) for- */-export interface NamedImportSpecifier extends Node, HasSpan {-  type: "ImportSpecifier";-  local: Identifier;-  imported?: ModuleExportName;-  isTypeOnly: boolean;-}--export type ModuleExportName = Identifier | StringLiteral;--export type ExportSpecifier =-  | ExportNamespaceSpecifier-  | ExportDefaultSpecifier-  | NamedExportSpecifier;--/**- * `export * as foo from 'src';`- */-export interface ExportNamespaceSpecifier extends Node, HasSpan {-  type: "ExportNamespaceSpecifier";--  name: ModuleExportName;-}--export interface ExportDefaultSpecifier extends Node, HasSpan {-  type: "ExportDefaultSpecifier";--  exported: Identifier;-}--export interface NamedExportSpecifier extends Node, HasSpan {-  type: "ExportSpecifier";--  orig: ModuleExportName;-  /**-   * `Some(bar)` in `export { foo as bar }`-   */-  exported?: ModuleExportName;-  isTypeOnly: boolean;-}--interface HasInterpreter {-  /**-   * e.g. `/usr/bin/node` for `#!/usr/bin/node`-   */-  interpreter: string;-}--export type Program = Module | Script;--export interface Module extends Node, HasSpan, HasInterpreter {-  type: "Module";--  body: ModuleItem[];-}--export interface Script extends Node, HasSpan, HasInterpreter {-  type: "Script";--  body: Statement[];-}--export type ModuleItem = ModuleDeclaration | Statement;--export type BinaryOperator =-  | "=="-  | "!="-  | "==="-  | "!=="-  | "<"-  | "<="-  | ">"-  | ">="-  | "<<"-  | ">>"-  | ">>>"-  | "+"-  | "-"-  | "*"-  | "/"-  | "%"-  | "|"-  | "^"-  | "&"-  | "||"-  | "&&"-  | "in"-  | "instanceof"-  | "**"-  | "??";--export type AssignmentOperator =-  | "="-  | "+="-  | "-="-  | "*="-  | "/="-  | "%="-  | "<<="-  | ">>="-  | ">>>="-  | "|="-  | "^="-  | "&="-  | "**="-  | "&&="-  | "||="-  | "??=";--export type UpdateOperator = "++" | "--";--export type UnaryOperator =-  | "-"-  | "+"-  | "!"-  | "~"-  | "typeof"-  | "void"-  | "delete";--export type Pattern =-  | BindingIdentifier-  | ArrayPattern-  | RestElement-  | ObjectPattern-  | AssignmentPattern-  | Invalid-  | Expression;--export interface BindingIdentifier extends PatternBase {-  type: "Identifier";-  value: string;-  optional: boolean;-}--export interface ArrayPattern extends PatternBase {-  type: "ArrayPattern";--  elements: (Pattern | undefined)[];--  optional: boolean;-}--export interface ObjectPattern extends PatternBase {-  type: "ObjectPattern";--  properties: ObjectPatternProperty[];--  optional: boolean;-}--export interface AssignmentPattern extends PatternBase {-  type: "AssignmentPattern";--  left: Pattern;-  right: Expression;-}--export interface RestElement extends PatternBase {-  type: "RestElement";--  rest: Span;--  argument: Pattern;-}--export type ObjectPatternProperty =-  | KeyValuePatternProperty-  | AssignmentPatternProperty-  | RestElement;--/**- * `{key: value}`- */-export interface KeyValuePatternProperty extends Node {-  type: "KeyValuePatternProperty";--  key: PropertyName;-  value: Pattern;-}--/**- * `{key}` or `{key = value}`- */-export interface AssignmentPatternProperty extends Node, HasSpan {-  type: "AssignmentPatternProperty";--  key: Identifier;-  value?: Expression;-}--/** Identifier is `a` in `{ a, }` */-export type Property =-  | Identifier-  | KeyValueProperty-  | AssignmentProperty-  | GetterProperty-  | SetterProperty-  | MethodProperty;--interface PropBase extends Node {-  key: PropertyName;-}--export interface KeyValueProperty extends PropBase {-  type: "KeyValueProperty";--  value: Expression;-}--export interface AssignmentProperty extends Node {-  type: "AssignmentProperty";--  key: Identifier;-  value: Expression;-}--export interface GetterProperty extends PropBase, HasSpan {-  type: "GetterProperty";--  function: Fn;-}--export interface SetterProperty extends PropBase, HasSpan {-  type: "SetterProperty";--  function: Fn;-}--export interface MethodProperty extends PropBase, Fn {-  type: "MethodProperty";-}--export type PropertyName =-  | Identifier-  | StringLiteral-  | NumericLiteral-  | ComputedPropName-  | BigIntLiteral;--export interface ComputedPropName extends Node, HasSpan {-  type: "Computed";-  expression: Expression;-}--export interface BlockStatement extends Node, HasSpan {-  type: "BlockStatement";--  stmts: Statement[];-}--export interface FunctionBody extends Node, HasSpan {-  type: "FunctionBody";--  stmts: Statement[];-}--export interface ExpressionStatement extends Node, HasSpan {-  type: "ExpressionStatement";-  expression: Expression;-}--export type Statement =-  | BlockStatement-  | EmptyStatement-  | DebuggerStatement-  | WithStatement-  | ReturnStatement-  | LabeledStatement-  | BreakStatement-  | ContinueStatement-  | IfStatement-  | SwitchStatement-  | ThrowStatement-  | TryStatement-  | WhileStatement-  | DoWhileStatement-  | ForStatement-  | ForInStatement-  | ForOfStatement-  | Declaration-  | ExpressionStatement;--export interface EmptyStatement extends Node, HasSpan {-  type: "EmptyStatement";-}--export interface DebuggerStatement extends Node, HasSpan {-  type: "DebuggerStatement";-}--export interface WithStatement extends Node, HasSpan {-  type: "WithStatement";--  object: Expression;-  body: Statement;-}--export interface ReturnStatement extends Node, HasSpan {-  type: "ReturnStatement";--  argument?: Expression;-}--export interface LabeledStatement extends Node, HasSpan {-  type: "LabeledStatement";--  label: Identifier;-  body: Statement;-}--export interface BreakStatement extends Node, HasSpan {-  type: "BreakStatement";--  label?: Identifier;-}--export interface ContinueStatement extends Node, HasSpan {-  type: "ContinueStatement";--  label?: Identifier;-}--export interface IfStatement extends Node, HasSpan {-  type: "IfStatement";--  test: Expression;-  consequent: Statement;-  alternate?: Statement;-}--export interface SwitchStatement extends Node, HasSpan {-  type: "SwitchStatement";--  discriminant: Expression;-  cases: SwitchCase[];-}--export interface ThrowStatement extends Node, HasSpan {-  type: "ThrowStatement";--  argument: Expression;-}--export interface TryStatement extends Node, HasSpan {-  type: "TryStatement";--  block: BlockStatement;-  handler?: CatchClause;-  finalizer?: BlockStatement;-}--export interface WhileStatement extends Node, HasSpan {-  type: "WhileStatement";--  test: Expression;-  body: Statement;-}--export interface DoWhileStatement extends Node, HasSpan {-  type: "DoWhileStatement";--  test: Expression;-  body: Statement;-}--export interface ForStatement extends Node, HasSpan {-  type: "ForStatement";--  init?: VariableDeclaration | Expression;-  test?: Expression;-  update?: Expression;-  body: Statement;-}--export interface ForInStatement extends Node, HasSpan {-  type: "ForInStatement";--  left: VariableDeclaration | Pattern;-  right: Expression;-  body: Statement;-}--export interface ForOfStatement extends Node, HasSpan {-  type: "ForOfStatement";--  /**-   *  Span of the await token.-   *-   *  es2018 for-await-of statements, e.g., `for await (const x of xs) {`-   */-  await?: Span;-  left: VariableDeclaration | Pattern;-  right: Expression;-  body: Statement;-}--export interface SwitchCase extends Node, HasSpan {-  type: "SwitchCase";--  /**-   * Undefined for default case-   */-  test?: Expression;-  consequent: Statement[];-}--export interface CatchClause extends Node, HasSpan {-  type: "CatchClause";--  /**-   * The param is `undefined` if the catch binding is omitted. E.g., `try { foo() } catch {}`-   */-  param?: Pattern;-  body: BlockStatement;-}--export interface TsTypeAnnotation extends Node, HasSpan {-  type: "TsTypeAnnotation";--  typeAnnotation: TsType;-}--export interface TsTypeParameterDeclaration extends Node, HasSpan {-  type: "TsTypeParameterDeclaration";--  parameters: TsTypeParameter[];-}--export interface TsTypeParameter extends Node, HasSpan {-  type: "TsTypeParameter";--  name: Identifier;-  in: boolean;-  out: boolean;-  constraint?: TsType;-  default?: TsType;-}--export interface TsTypeParameterInstantiation extends Node, HasSpan {-  type: "TsTypeParameterInstantiation";--  params: TsType[];-}--export interface TsParameterProperty extends Node, HasSpan, HasDecorator {-  type: "TsParameterProperty";--  accessibility?: Accessibility;-  override: boolean;-  readonly: boolean;-  param: TsParameterPropertyParameter;-}--export type TsParameterPropertyParameter =-  | BindingIdentifier-  | AssignmentPattern;--export interface TsQualifiedName extends Node {-  type: "TsQualifiedName";--  left: TsEntityName;-  right: Identifier;-}--export type TsEntityName = TsQualifiedName | Identifier;--export type TsTypeElement =-  | TsCallSignatureDeclaration-  | TsConstructSignatureDeclaration-  | TsPropertySignature-  | TsGetterSignature-  | TsSetterSignature-  | TsMethodSignature-  | TsIndexSignature;--export interface TsCallSignatureDeclaration extends Node, HasSpan {-  type: "TsCallSignatureDeclaration";--  params: TsFnParameter[];-  typeAnnotation?: TsTypeAnnotation;-  typeParams?: TsTypeParameterDeclaration;-}--export interface TsConstructSignatureDeclaration extends Node, HasSpan {-  type: "TsConstructSignatureDeclaration";--  params: TsFnParameter[];-  typeAnnotation?: TsTypeAnnotation;-  typeParams?: TsTypeParameterDeclaration;-}--export interface TsPropertySignature extends Node, HasSpan {-  type: "TsPropertySignature";--  readonly: boolean;-  key: Expression;-  computed: boolean;-  optional: boolean;--  init?: Expression;-  params: TsFnParameter[];--  typeAnnotation?: TsTypeAnnotation;-  typeParams?: TsTypeParameterDeclaration;-}--export interface TsGetterSignature extends Node, HasSpan {-  type: "TsGetterSignature";--  readonly: boolean;-  key: Expression;-  computed: boolean;-  optional: boolean;-  typeAnnotation?: TsTypeAnnotation;-}--export interface TsSetterSignature extends Node, HasSpan {-  type: "TsSetterSignature";--  readonly: boolean;-  key: Expression;-  computed: boolean;-  optional: boolean;-  param: TsFnParameter;-}--export interface TsMethodSignature extends Node, HasSpan {-  type: "TsMethodSignature";--  readonly: boolean;-  key: Expression;-  computed: boolean;-  optional: boolean;-  params: TsFnParameter[];--  typeAnn?: TsTypeAnnotation;-  typeParams?: TsTypeParameterDeclaration;-}--export interface TsIndexSignature extends Node, HasSpan {-  type: "TsIndexSignature";--  params: TsFnParameter[];--  typeAnnotation?: TsTypeAnnotation;--  readonly: boolean;-  static: boolean;-}--export type TsType =-  | TsKeywordType-  | TsThisType-  | TsFnOrConstructorType-  | TsTypeReference-  | TsTypeQuery-  | TsTypeLiteral-  | TsArrayType-  | TsTupleType-  | TsOptionalType-  | TsRestType-  | TsUnionOrIntersectionType-  | TsConditionalType-  | TsInferType-  | TsParenthesizedType-  | TsTypeOperator-  | TsIndexedAccessType-  | TsMappedType-  | TsLiteralType-  | TsTypePredicate-  | TsImportType;--export type TsFnOrConstructorType = TsFunctionType | TsConstructorType;--export interface TsKeywordType extends Node, HasSpan {-  type: "TsKeywordType";--  kind: TsKeywordTypeKind;-}--export type TsKeywordTypeKind =-  | "any"-  | "unknown"-  | "number"-  | "object"-  | "boolean"-  | "bigint"-  | "string"-  | "symbol"-  | "void"-  | "undefined"-  | "null"-  | "never"-  | "intrinsic";--export interface TsThisType extends Node, HasSpan {-  type: "TsThisType";-}--export interface TsThisParameter extends Node, HasSpan {-  type: "TsThisParameter";--  thisSpan: Span;--  typeAnnotation?: TsTypeAnnotation;-}--export type TsFnParameter =-  | BindingIdentifier-  | ArrayPattern-  | RestElement-  | ObjectPattern;--export interface TsFunctionType extends Node, HasSpan {-  type: "TsFunctionType";--  params: TsFnParameter[];--  typeParams?: TsTypeParameterDeclaration;-  typeAnnotation: TsTypeAnnotation;-}--export interface TsConstructorType extends Node, HasSpan {-  type: "TsConstructorType";--  params: TsFnParameter[];--  typeParams?: TsTypeParameterDeclaration;-  typeAnnotation: TsTypeAnnotation;-  isAbstract: boolean;-}--export interface TsTypeReference extends Node, HasSpan {-  type: "TsTypeReference";--  typeName: TsEntityName;-  typeParams?: TsTypeParameterInstantiation;-}--export interface TsTypePredicate extends Node, HasSpan {-  type: "TsTypePredicate";--  asserts: boolean;--  paramName: TsThisTypeOrIdent;-  typeAnnotation?: TsTypeAnnotation;-}--export type TsThisTypeOrIdent = TsThisType | Identifier;--export interface TsImportType extends Node, HasSpan {-  type: "TsImportType";--  argument: StringLiteral;-  qualifier?: TsEntityName;-  typeArguments?: TsTypeParameterInstantiation;-}--/**- * `typeof` operator- */-export interface TsTypeQuery extends Node, HasSpan {-  type: "TsTypeQuery";--  exprName: TsTypeQueryExpr;-  typeArguments?: TsTypeParameterInstantiation;-}--export type TsTypeQueryExpr = TsEntityName | TsImportType;--export interface TsTypeLiteral extends Node, HasSpan {-  type: "TsTypeLiteral";--  members: TsTypeElement[];-}--export interface TsArrayType extends Node, HasSpan {-  type: "TsArrayType";--  elemType: TsType;-}--export interface TsTupleType extends Node, HasSpan {-  type: "TsTupleType";--  elemTypes: TsTupleElement[];-}--export interface TsTupleElement extends Node, HasSpan {-  type: "TsTupleElement";--  label?: Pattern;-  ty: TsType;-}--export interface TsOptionalType extends Node, HasSpan {-  type: "TsOptionalType";--  typeAnnotation: TsType;-}--export interface TsRestType extends Node, HasSpan {-  type: "TsRestType";--  typeAnnotation: TsType;-}--export type TsUnionOrIntersectionType = TsUnionType | TsIntersectionType;--export interface TsUnionType extends Node, HasSpan {-  type: "TsUnionType";--  types: TsType[];-}--export interface TsIntersectionType extends Node, HasSpan {-  type: "TsIntersectionType";--  types: TsType[];-}--export interface TsConditionalType extends Node, HasSpan {-  type: "TsConditionalType";--  checkType: TsType;-  extendsType: TsType;-  trueType: TsType;-  falseType: TsType;-}--export interface TsInferType extends Node, HasSpan {-  type: "TsInferType";--  typeParam: TsTypeParameter;-}--export interface TsParenthesizedType extends Node, HasSpan {-  type: "TsParenthesizedType";--  typeAnnotation: TsType;-}--export interface TsTypeOperator extends Node, HasSpan {-  type: "TsTypeOperator";--  op: TsTypeOperatorOp;-  typeAnnotation: TsType;-}--export type TsTypeOperatorOp = "keyof" | "unique" | "readonly";--export interface TsIndexedAccessType extends Node, HasSpan {-  type: "TsIndexedAccessType";--  readonly: boolean;-  objectType: TsType;-  indexType: TsType;-}--export type TruePlusMinus = true | "+" | "-";--export interface TsMappedType extends Node, HasSpan {-  type: "TsMappedType";--  readonly?: TruePlusMinus;-  typeParam: TsTypeParameter;-  nameType?: TsType;-  optional?: TruePlusMinus;-  typeAnnotation?: TsType;-}--export interface TsLiteralType extends Node, HasSpan {-  type: "TsLiteralType";--  literal: TsLiteral;-}--export type TsLiteral =-  | NumericLiteral-  | StringLiteral-  | BooleanLiteral-  | BigIntLiteral-  | TsTemplateLiteralType;--export interface TsTemplateLiteralType extends Node, HasSpan {-  type: "TemplateLiteral";-  types: TsType[];-  quasis: TemplateElement[];-}--// // ================-// // TypeScript declarations-// // ================--export interface TsInterfaceDeclaration extends Node, HasSpan {-  type: "TsInterfaceDeclaration";--  id: Identifier;-  declare: boolean;-  typeParams?: TsTypeParameterDeclaration;-  extends: TsExpressionWithTypeArguments[];-  body: TsInterfaceBody;-}--export interface TsInterfaceBody extends Node, HasSpan {-  type: "TsInterfaceBody";--  body: TsTypeElement[];-}--export interface TsExpressionWithTypeArguments extends Node, HasSpan {-  type: "TsExpressionWithTypeArguments";--  expression: Expression;-  typeArguments?: TsTypeParameterInstantiation;-}--export interface TsTypeAliasDeclaration extends Node, HasSpan {-  type: "TsTypeAliasDeclaration";--  declare: boolean;-  id: Identifier;-  typeParams?: TsTypeParameterDeclaration;-  typeAnnotation: TsType;-}--export interface TsEnumDeclaration extends Node, HasSpan {-  type: "TsEnumDeclaration";--  declare: boolean;-  isConst: boolean;-  id: Identifier;-  members: TsEnumMember[];-}--export interface TsEnumMember extends Node, HasSpan {-  type: "TsEnumMember";--  id: TsEnumMemberId;-  init?: Expression;-}--export type TsEnumMemberId = Identifier | StringLiteral;--export interface TsModuleDeclaration extends Node, HasSpan {-  type: "TsModuleDeclaration";--  declare: boolean;-  global: boolean;-  id: TsModuleName;-  body?: TsNamespaceBody;-}--/**- * `namespace A.B { }` is a namespace named `A` with another TsNamespaceDecl as its body.- */-export type TsNamespaceBody = TsModuleBlock | TsNamespaceDeclaration;--export interface TsModuleBlock extends Node, HasSpan {-  type: "TsModuleBlock";--  body: ModuleItem[];-}--export interface TsNamespaceDeclaration extends Node, HasSpan {-  type: "TsNamespaceDeclaration";--  declare: boolean;-  global: boolean;-  id: Identifier;-  body: TsNamespaceBody;-}--export type TsModuleName = Identifier | StringLiteral;--export interface TsImportEqualsDeclaration extends Node, HasSpan {-  type: "TsImportEqualsDeclaration";--  declare: boolean;-  isExport: boolean;-  isTypeOnly: boolean;-  id: Identifier;-  moduleRef: TsModuleReference;-}--export type TsModuleReference = TsEntityName | TsExternalModuleReference;--export interface TsExternalModuleReference extends Node, HasSpan {-  type: "TsExternalModuleReference";--  expression: StringLiteral;-}--export interface TsExportAssignment extends Node, HasSpan {-  type: "TsExportAssignment";--  expression: Expression;-}--export interface TsNamespaceExportDeclaration extends Node, HasSpan {-  type: "TsNamespaceExportDeclaration";--  id: Identifier;-}--export interface TsAsExpression extends ExpressionBase {-  type: "TsAsExpression";--  expression: Expression;-  typeAnnotation: TsType;-}--export interface TsInstantiation extends Node, HasSpan {-  type: "TsInstantiation";--  expression: Expression;-  typeArguments: TsTypeParameterInstantiation;-}--export interface TsTypeAssertion extends ExpressionBase {-  type: "TsTypeAssertion";--  expression: Expression;-  typeAnnotation: TsType;-}--export interface TsConstAssertion extends ExpressionBase {-  type: "TsConstAssertion";--  expression: Expression;-}--export interface TsNonNullExpression extends ExpressionBase {-  type: "TsNonNullExpression";--  expression: Expression;-}--export type Accessibility = "public" | "protected" | "private";--export interface Invalid extends Node, HasSpan {-  type: "Invalid";-}-"#;

deps/swc/bindings/binding_nodejs_support_wasm/.cargo/config.toml

deleted file mode 100644@@ -1,3 +0,0 @@-[target.wasm32-unknown-unknown]-# support more stack size due to issue: https://github.com/swc-project/swc/issues/10207-rustflags = ["-C", "link-args=-z stack-size=2097152"]

deps/swc/bindings/binding_nodejs_support_wasm/Cargo.toml

deleted file mode 100644@@ -1,45 +0,0 @@-[package]-authors     = ["강동윤 <kdy1997.dev@gmail.com>"]-description = "Node.js support helpers compiled to WebAssembly"-edition     = { workspace = true }-license     = { workspace = true }-name        = "binding_nodejs_support_wasm"-publish     = false-repository  = { workspace = true }-version     = "1.16.18"--[lib]-bench      = false-crate-type = ["cdylib"]--[features]-nightly = ["swc_ts_fast_strip/nightly"]--[dependencies]-anyhow = { workspace = true }-js-sys = { workspace = true }-miette = { workspace = true }-owo-colors = { workspace = true }-serde = { workspace = true, features = ["derive"] }-serde-wasm-bindgen = { workspace = true }-serde_json = { workspace = true }-swc_common = { path = "../../crates/swc_common" }-swc_ecma_ast = { path = "../../crates/swc_ecma_ast" }-swc_ecma_parser = { path = "../../crates/swc_ecma_parser", features = [-  "unstable",-] }-swc_ecma_visit = { path = "../../crates/swc_ecma_visit" }-swc_error_reporters = { path = "../../crates/swc_error_reporters" }-swc_ts_fast_strip = { path = "../../crates/swc_ts_fast_strip", features = [-  "wasm-bindgen",-] }-tracing = { workspace = true, features = ["max_level_off"] }-unicode-width = { workspace = true }-wasm-bindgen = { workspace = true, features = ["enable-interning"] }-wasm-bindgen-futures = { workspace = true }--[dev-dependencies]-testing = { path = "../../crates/testing" }--[package.metadata.wasm-pack.profile.release]-wasm-opt = false

deps/swc/bindings/binding_nodejs_support_wasm/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.

deps/swc/bindings/binding_nodejs_support_wasm/README.md

deleted file mode 100644@@ -1,68 +0,0 @@-# @swc/nodejs-support-wasm--This package provides a standalone WebAssembly binding for Node.js-integrations. Its Rust crate, source, build, and test setup are independent from-`@swc/wasm-typescript`.--It includes the TypeScript transform API from `@swc/wasm-typescript` and-additional helpers for module syntax transformation, assertion locations, and-syntax validation.--## API---   `transform` and `transformSync`--   `transformModuleSyntax`--   `getFirstExpression`--   `isValidSyntax`--   `isRecoverableError`--   `tokenize`--   `findTopLevelAwaits`--All source arguments accept a string or a UTF-8 `Uint8Array`.--### Syntax highlighting--`tokenize(src)` returns `{ kind, start, end }[]` in source order. The token kinds-are `keyword`, `identifier`, `number`, `bigint`, `string`, `template`, `regexp`,-`comment`, and `punctuator`. Offsets are zero-based UTF-16 code units with an-exclusive end, so `src.slice(start, end)` extracts the token. Comments include-their delimiters; hashbangs are comments. Whitespace and EOF are omitted.-Template text includes its backticks, while `${` and `}` are punctuators and-interpolated expressions have their own tokens.--This helper parses JavaScript to distinguish regular expressions from division-and track template substitutions. On incomplete or invalid input it returns the-tokens captured before parsing stopped, without throwing a syntax error. It is-intended for REPL highlighting, not syntax validation or TypeScript tokenization.--### Top-level await locations--`findTopLevelAwaits(src)` returns `{ line, column }[]` in source order for `await`-expressions, `for await` loops, and `await using` declarations in module scope.-Lines start at 1 and UTF-16 columns start at 0, matching Acorn. Each location is-the start of the construct (`for` for a `for await` loop). Function bodies,-including methods and arrow functions, are excluded; class heritage expressions,-computed keys, and method decorators are included. JavaScript and TypeScript are-supported, and invalid or incomplete modules return an empty array.--### REPL imports--`transformModuleSyntax(src)` hoists imports and declares their local bindings,-so a REPL can retain them for subsequent inputs. For example, a default import-declares `const { default: fs } = await __nodeREPLDynamicImport(...)` after-validating that the export exists. The caller supplies `__nodeREPLDynamicImport`-and evaluates the output with top-level await support.--Default and named bindings capture the initial export values, matching Node's-REPL transform; namespace bindings retain the module namespace object. References-and assignments are left intact so normal JavaScript scope, call, and `const`-semantics apply before any further rewriting performed by the host REPL.--## Contributing--See [the main repository](https://github.com/swc-project/swc)'s contributing-guide.--## License--Apache 2.0

deps/swc/bindings/binding_nodejs_support_wasm/package.json

deleted file mode 100644@@ -1,5 +0,0 @@-{-    "devDependencies": {-        "@rstest/core": "^0.7.8"-    }-}

deps/swc/bindings/binding_nodejs_support_wasm/rstest.config.mjs

deleted file mode 100644@@ -1,4 +0,0 @@-export default {-    include: ["__tests__/**/*.{js,jsx,ts,tsx}"],-    globals: true,-};

deps/swc/bindings/binding_nodejs_support_wasm/scripts/build.sh

deleted file mode 100755@@ -1,16 +0,0 @@-#!/usr/bin/env bash-set -eux--export CARGO_PROFILE_RELEASE_LTO="fat"-export CARGO_PROFILE_RELEASE_OPT_LEVEL="z"--wasm-pack build \-  --out-name wasm \-  --release \-  --scope=swc \-  --target nodejs \-  "$@"-ls -al ./pkg--node ./scripts/patch.mjs-cp ./README.md ./pkg/README.md

deps/swc/bindings/binding_nodejs_support_wasm/scripts/patch.mjs

deleted file mode 100644@@ -1,31 +0,0 @@-import fs from "node:fs/promises";--const rawWasmPath = "pkg/wasm_bg.wasm";-const wasmJsPath = "pkg/wasm.js";-const packageJsonPath = "pkg/package.json";-const rawWasmFile = await fs.readFile(rawWasmPath);-const origJsFile = await fs.readFile(wasmJsPath, "utf8");--const base64 = rawWasmFile.toString("base64");-const patchedJsFile = origJsFile-    .replace(-        `const path = require('path').join(__dirname, 'wasm_bg.wasm');`,-        ""-    )-    .replace(", fatal: true", "")-    .replace(-        `const bytes = require('fs').readFileSync(path);`,-        `-const { Buffer } = require('node:buffer');-const bytes = Buffer.from('${base64}', 'base64');`-    );--await fs.writeFile(wasmJsPath, patchedJsFile);-await fs.unlink(rawWasmPath);--const pkgJsonFile = await fs.readFile(packageJsonPath, "utf8");-const pkgJson = JSON.parse(pkgJsonFile);-pkgJson.name = "@swc/nodejs-support-wasm";-pkgJson.description = "SWC WebAssembly helpers for Node.js";-pkgJson.files = pkgJson.files.filter((file) => file !== "wasm_bg.wasm");-await fs.writeFile(packageJsonPath, JSON.stringify(pkgJson, null, 2));

deps/swc/bindings/binding_nodejs_support_wasm/scripts/test.sh

deleted file mode 100755@@ -1,9 +0,0 @@-#!/usr/bin/env bash--set -eu--./scripts/build.sh-npx rstest "$@"--./scripts/build.sh --features nightly-npx rstest "$@"

deps/swc/bindings/binding_nodejs_support_wasm/src/error_reporter.rs

deleted file mode 100644@@ -1,881 +0,0 @@-use std::fmt::{self};--use miette::{-    Diagnostic, GraphicalTheme, LabeledSpan, ReportHandler, SourceCode, SourceSpan, ThemeCharacters,-};-use owo_colors::{OwoColorize, Style};-use unicode_width::UnicodeWidthChar;--/**-A [`ReportHandler`] that displays a given [`Report`](crate::Report) in a-quasi-graphical way, using terminal colors, unicode drawing characters, and-other such things.--This is the default reporter bundled with `miette`.--This printer can be customized by using [`new_themed()`](GraphicalReportHandler::new_themed) and handing it a-[`GraphicalTheme`] of your own creation (or using one of its own defaults!)--See [`set_hook()`](crate::set_hook) for more details on customizing your global-printer.-*/-#[derive(Debug, Clone)]-pub struct SwcReportHandler {-    pub(crate) theme: GraphicalTheme,-    pub(crate) context_lines: usize,-    pub(crate) tab_width: usize,-}--impl SwcReportHandler {-    /// Create a new `GraphicalReportHandler` with the default-    /// [`GraphicalTheme`]. This will use both unicode characters and colors.-    pub fn new() -> Self {-        Self {-            theme: GraphicalTheme::default(),-            context_lines: 1,-            tab_width: 4,-        }-    }--    /// Set a theme for this handler.-    pub fn with_theme(mut self, theme: GraphicalTheme) -> Self {-        self.theme = theme;-        self-    }-}--impl Default for SwcReportHandler {-    fn default() -> Self {-        Self::new()-    }-}--impl SwcReportHandler {-    /// Render a [`Diagnostic`]. This function is mostly internal and meant to-    /// be called by the toplevel [`ReportHandler`] handler, but is made public-    /// to make it easier (possible) to test in isolation from global state.-    pub fn render_report(-        &self,-        f: &mut impl fmt::Write,-        diagnostic: &dyn Diagnostic,-    ) -> fmt::Result {-        self.render_report_inner(f, diagnostic, diagnostic.source_code())-    }--    fn render_report_inner(-        &self,-        f: &mut impl fmt::Write,-        diagnostic: &dyn Diagnostic,-        parent_src: Option<&dyn SourceCode>,-    ) -> fmt::Result {-        let src = diagnostic.source_code().or(parent_src);-        self.render_snippets(f, diagnostic, src)?;--        Ok(())-    }--    fn render_snippets(-        &self,-        f: &mut impl fmt::Write,-        diagnostic: &dyn Diagnostic,-        opt_source: Option<&dyn SourceCode>,-    ) -> fmt::Result {-        let source = match opt_source {-            Some(source) => source,-            None => return Ok(()),-        };-        let labels = match diagnostic.labels() {-            Some(labels) => labels,-            None => return Ok(()),-        };--        let mut labels = labels.collect::<Vec<_>>();-        labels.sort_unstable_by_key(|l| l.inner().offset());--        let mut contexts = Vec::with_capacity(labels.len());-        for right in labels.iter().cloned() {-            let right_conts =-                match source.read_span(right.inner(), self.context_lines, self.context_lines) {-                    Ok(cont) => cont,-                    Err(err) => {-                        writeln!(-                            f,-                            "  [{} `{}` (offset: {}, length: {}): {:?}]",-                            "Failed to read contents for label".style(self.theme.styles.error),-                            right-                                .label()-                                .unwrap_or("<none>")-                                .style(self.theme.styles.link),-                            right.offset().style(self.theme.styles.link),-                            right.len().style(self.theme.styles.link),-                            err.style(self.theme.styles.warning)-                        )?;-                        return Ok(());-                    }-                };--            if contexts.is_empty() {-                contexts.push((right, right_conts));-                continue;-            }--            let (left, left_conts) = contexts.last().unwrap();-            if left_conts.line() + left_conts.line_count() >= right_conts.line() {-                // The snippets will overlap, so we create one Big Chunky Boi-                let left_end = left.offset() + left.len();-                let right_end = right.offset() + right.len();-                let new_end = std::cmp::max(left_end, right_end);--                let new_span = LabeledSpan::new(-                    left.label().map(String::from),-                    left.offset(),-                    new_end - left.offset(),-                );-                // Check that the two contexts can be combined-                if let Ok(new_conts) =-                    source.read_span(new_span.inner(), self.context_lines, self.context_lines)-                {-                    contexts.pop();-                    // We'll throw the contents away later-                    contexts.push((new_span, new_conts));-                    continue;-                }-            }--            contexts.push((right, right_conts));-        }-        for (ctx, _) in contexts {-            self.render_context(f, source, &ctx, &labels[..])?;-        }--        Ok(())-    }--    fn render_context(-        &self,-        f: &mut impl fmt::Write,-        source: &dyn SourceCode,-        context: &LabeledSpan,-        labels: &[LabeledSpan],-    ) -> fmt::Result {-        let lines = self.get_lines(source, context.inner())?;--        // sorting is your friend-        let labels = labels-            .iter()-            .zip(self.theme.styles.highlights.iter().cloned().cycle())-            .map(|(label, st)| FancySpan::new(label.label().map(String::from), *label.inner(), st))-            .collect::<Vec<_>>();--        // The max number of gutter-lines that will be active at any given-        // point. We need this to figure out indentation, so we do one loop-        // over the lines to see what the damage is gonna be.-        let mut max_gutter = 0usize;-        for line in &lines {-            let mut num_highlights = 0;-            for hl in &labels {-                if !line.span_line_only(hl) && line.span_applies_gutter(hl) {-                    num_highlights += 1;-                }-            }-            max_gutter = std::cmp::max(max_gutter, num_highlights);-        }--        // Now it's time for the fun part--actually rendering everything!-        for line in &lines {-            // Then, we need to print the gutter, along with any fly-bys We-            // have separate gutters depending on whether we're on the actual-            // line, or on one of the "highlight lines" below it.-            self.render_line_gutter(f, max_gutter, line, &labels)?;--            // And _now_ we can print out the line text itself!-            self.render_line_text(f, &line.text)?;--            // Next, we write all the highlights that apply to this particular line.-            let (single_line, multi_line): (Vec<_>, Vec<_>) = labels-                .iter()-                .filter(|hl| line.span_applies(hl))-                .partition(|hl| line.span_line_only(hl));-            if !single_line.is_empty() {-                // gutter _again_-                self.render_highlight_gutter(-                    f,-                    max_gutter,-                    line,-                    &labels,-                    LabelRenderMode::SingleLine,-                )?;-                self.render_single_line_highlights(f, line, max_gutter, &single_line, &labels)?;-            }-            for hl in multi_line {-                if hl.label().is_some() && line.span_ends(hl) && !line.span_starts(hl) {-                    self.render_multi_line_end(f, &labels, max_gutter, line, hl)?;-                }-            }-        }--        Ok(())-    }--    fn render_multi_line_end(-        &self,-        f: &mut impl fmt::Write,-        labels: &[FancySpan],-        max_gutter: usize,-        line: &Line,-        label: &FancySpan,-    ) -> fmt::Result {-        if let Some(label_parts) = label.label_parts() {-            // if it has a label, how long is it?-            let (first, rest) = label_parts.split_first().expect(-                "cannot crash because rest would have been None, see docs on the `label` field of \-                 FancySpan",-            );--            if rest.is_empty() {-                // gutter _again_-                self.render_highlight_gutter(-                    f,-                    max_gutter,-                    line,-                    labels,-                    LabelRenderMode::SingleLine,-                )?;--                self.render_multi_line_end_single(-                    f,-                    first,-                    label.style,-                    LabelRenderMode::SingleLine,-                )?;-            } else {-                // gutter _again_-                self.render_highlight_gutter(-                    f,-                    max_gutter,-                    line,-                    labels,-                    LabelRenderMode::MultiLineFirst,-                )?;--                self.render_multi_line_end_single(-                    f,-                    first,-                    label.style,-                    LabelRenderMode::MultiLineFirst,-                )?;-                for label_line in rest {-                    // gutter _again_-                    self.render_highlight_gutter(-                        f,-                        max_gutter,-                        line,-                        labels,-                        LabelRenderMode::MultiLineRest,-                    )?;-                    self.render_multi_line_end_single(-                        f,-                        label_line,-                        label.style,-                        LabelRenderMode::MultiLineRest,-                    )?;-                }-            }-        } else {-            // gutter _again_-            self.render_highlight_gutter(f, max_gutter, line, labels, LabelRenderMode::SingleLine)?;-            // has no label-            writeln!(f, "{}", self.theme.characters.hbar.style(label.style))?;-        }--        Ok(())-    }--    fn render_line_gutter(-        &self,-        f: &mut impl fmt::Write,-        max_gutter: usize,-        line: &Line,-        highlights: &[FancySpan],-    ) -> fmt::Result {-        if max_gutter == 0 {-            return Ok(());-        }-        let chars = &self.theme.characters;-        let mut gutter = String::new();-        let applicable = highlights.iter().filter(|hl| line.span_applies_gutter(hl));-        let mut arrow = false;-        for (i, hl) in applicable.enumerate() {-            if line.span_starts(hl) {-                gutter.push_str(&chars.ltop.style(hl.style).to_string());-                gutter.push_str(-                    &chars-                        .hbar-                        .to_string()-                        .repeat(max_gutter.saturating_sub(i))-                        .style(hl.style)-                        .to_string(),-                );-                gutter.push_str(&chars.rarrow.style(hl.style).to_string());-                arrow = true;-                break;-            } else if line.span_ends(hl) {-                if hl.label().is_some() {-                    gutter.push_str(&chars.lcross.style(hl.style).to_string());-                } else {-                    gutter.push_str(&chars.lbot.style(hl.style).to_string());-                }-                gutter.push_str(-                    &chars-                        .hbar-                        .to_string()-                        .repeat(max_gutter.saturating_sub(i))-                        .style(hl.style)-                        .to_string(),-                );-                gutter.push_str(&chars.rarrow.style(hl.style).to_string());-                arrow = true;-                break;-            } else if line.span_flyby(hl) {-                gutter.push_str(&chars.vbar.style(hl.style).to_string());-            } else {-                gutter.push(' ');-            }-        }-        write!(-            f,-            "{}{}",-            gutter,-            " ".repeat(-                if arrow { 1 } else { 3 } + max_gutter.saturating_sub(gutter.chars().count())-            )-        )?;-        Ok(())-    }--    fn render_highlight_gutter(-        &self,-        f: &mut impl fmt::Write,-        max_gutter: usize,-        line: &Line,-        highlights: &[FancySpan],-        render_mode: LabelRenderMode,-    ) -> fmt::Result {-        if max_gutter == 0 {-            return Ok(());-        }--        // keeps track of how many columns wide the gutter is-        // important for ansi since simply measuring the size of the final string-        // gives the wrong result when the string contains ansi codes.-        let mut gutter_cols = 0;--        let chars = &self.theme.characters;-        let mut gutter = String::new();-        let applicable = highlights.iter().filter(|hl| line.span_applies_gutter(hl));-        for (i, hl) in applicable.enumerate() {-            if !line.span_line_only(hl) && line.span_ends(hl) {-                if render_mode == LabelRenderMode::MultiLineRest {-                    // this is to make multiline labels work. We want to make the right amount-                    // of horizontal space for them, but not actually draw the lines-                    let horizontal_space = max_gutter.saturating_sub(i) + 2;-                    for _ in 0..horizontal_space {-                        gutter.push(' ');-                    }-                    // account for one more horizontal space, since in multiline mode-                    // we also add in the vertical line before the label like this:-                    // 2 │ ╭─▶   text-                    // 3 │ ├─▶     here-                    //   · ╰──┤ these two lines-                    //   ·    │ are the problem-                    //        ^this-                    gutter_cols += horizontal_space + 1;-                } else {-                    let num_repeat = max_gutter.saturating_sub(i) + 2;--                    gutter.push_str(&chars.lbot.style(hl.style).to_string());--                    gutter.push_str(-                        &chars-                            .hbar-                            .to_string()-                            .repeat(-                                num_repeat-                                    // if we are rendering a multiline label, then leave a bit of space for the-                                    // rcross character-                                    - if render_mode == LabelRenderMode::MultiLineFirst {-                                        1-                                    } else {-                                        0-                                    },-                            )-                            .style(hl.style)-                            .to_string(),-                    );--                    // we count 1 for the lbot char, and then a few more, the same number-                    // as we just repeated for. For each repeat we only add 1, even though-                    // due to ansi escape codes the number of bytes in the string could grow-                    // a lot each time.-                    gutter_cols += num_repeat + 1;-                }-                break;-            } else {-                gutter.push_str(&chars.vbar.style(hl.style).to_string());--                // we may push many bytes for the ansi escape codes style adds,-                // but we still only add a single character-width to the string in a terminal-                gutter_cols += 1;-            }-        }--        // now calculate how many spaces to add based on how many columns we just-        // created. it's the max width of the gutter, minus how many-        // character-widths we just generated capped at 0 (though this should-        // never go below in reality), and then we add 3 to account for-        // arrowheads when a gutter line ends-        let num_spaces = (max_gutter + 3).saturating_sub(gutter_cols);-        // we then write the gutter and as many spaces as we need-        write!(f, "{}{:width$}", gutter, "", width = num_spaces)?;-        Ok(())-    }--    /// Returns an iterator over the visual width of each character in a line.-    fn line_visual_char_width<'a>(&self, text: &'a str) -> impl Iterator<Item = usize> + 'a {-        let mut column = 0;-        let mut escaped = false;-        let tab_width = self.tab_width;-        text.chars().map(move |c| {-            let width = match (escaped, c) {-                // Round up to the next multiple of tab_width-                (false, '\t') => tab_width - column % tab_width,-                // start of ANSI escape-                (false, '\x1b') => {-                    escaped = true;-                    0-                }-                // use Unicode width for all other characters-                (false, c) => c.width().unwrap_or(0),-                // end of ANSI escape-                (true, 'm') => {-                    escaped = false;-                    0-                }-                // characters are zero width within escape sequence-                (true, _) => 0,-            };-            column += width;-            width-        })-    }--    /// Returns the visual column position of a byte offset on a specific line.-    ///-    /// If the offset occurs in the middle of a character, the returned column-    /// corresponds to that character's first column in `start` is true, or its-    /// last column if `start` is false.-    fn visual_offset(&self, line: &Line, offset: usize, start: bool) -> usize {-        let line_range = line.offset..=(line.offset + line.length);-        assert!(line_range.contains(&offset));--        let mut text_index = offset - line.offset;-        while text_index <= line.text.len() && !line.text.is_char_boundary(text_index) {-            if start {-                text_index -= 1;-            } else {-                text_index += 1;-            }-        }-        let text = &line.text[..text_index.min(line.text.len())];-        let text_width = self.line_visual_char_width(text).sum();-        if text_index > line.text.len() {-            // Spans extending past the end of the line are always rendered as-            // one column past the end of the visible line.-            //-            // This doesn't necessarily correspond to a specific byte-offset,-            // since a span extending past the end of the line could contain:-            //  - an actual \n character (1 byte)-            //  - a CRLF (2 bytes)-            //  - EOF (0 bytes)-            text_width + 1-        } else {-            text_width-        }-    }--    /// Renders a line to the output formatter, replacing tabs with spaces.-    fn render_line_text(&self, f: &mut impl fmt::Write, text: &str) -> fmt::Result {-        for (c, width) in text.chars().zip(self.line_visual_char_width(text)) {-            if c == '\t' {-                for _ in 0..width {-                    f.write_char(' ')?;-                }-            } else {-                f.write_char(c)?;-            }-        }-        f.write_char('\n')?;-        Ok(())-    }--    fn render_single_line_highlights(-        &self,-        f: &mut impl fmt::Write,-        line: &Line,-        max_gutter: usize,-        single_liners: &[&FancySpan],-        all_highlights: &[FancySpan],-    ) -> fmt::Result {-        let mut underlines = String::new();-        let mut highest = 0;--        let chars = &self.theme.characters;-        let vbar_offsets: Vec<_> = single_liners-            .iter()-            .map(|hl| {-                let byte_start = hl.offset();-                let byte_end = hl.offset() + hl.len();-                let start = self.visual_offset(line, byte_start, true).max(highest);-                let end = if hl.len() == 0 {-                    start + 1-                } else {-                    self.visual_offset(line, byte_end, false).max(start + 1)-                };--                let vbar_offset = (start + end) / 2;-                let num_left = vbar_offset - start;-                let num_right = end - vbar_offset - 1;-                underlines.push_str(-                    &format!(-                        "{:width$}{}{}{}",-                        "",-                        chars.underline.to_string().repeat(num_left),-                        if hl.len() == 0 {-                            chars.uarrow-                        } else if hl.label().is_some() {-                            chars.underbar-                        } else {-                            chars.underline-                        },-                        chars.underline.to_string().repeat(num_right),-                        width = start.saturating_sub(highest),-                    )-                    .style(hl.style)-                    .to_string(),-                );-                highest = std::cmp::max(highest, end);--                (hl, vbar_offset)-            })-            .collect();-        writeln!(f, "{underlines}")?;--        for hl in single_liners.iter().rev() {-            if let Some(label) = hl.label_parts() {-                if label.len() == 1 {-                    self.write_label_text(-                        f,-                        line,-                        max_gutter,-                        all_highlights,-                        chars,-                        &vbar_offsets,-                        hl,-                        &label[0],-                        LabelRenderMode::SingleLine,-                    )?;-                } else {-                    let mut first = true;-                    for label_line in &label {-                        self.write_label_text(-                            f,-                            line,-                            max_gutter,-                            all_highlights,-                            chars,-                            &vbar_offsets,-                            hl,-                            label_line,-                            if first {-                                LabelRenderMode::MultiLineFirst-                            } else {-                                LabelRenderMode::MultiLineRest-                            },-                        )?;-                        first = false;-                    }-                }-            }-        }-        Ok(())-    }--    // I know it's not good practice, but making this a function makes a lot of-    // sense and making a struct for this does not...-    #[allow(clippy::too_many_arguments)]-    fn write_label_text(-        &self,-        f: &mut impl fmt::Write,-        line: &Line,-        max_gutter: usize,-        all_highlights: &[FancySpan],-        chars: &ThemeCharacters,-        vbar_offsets: &[(&&FancySpan, usize)],-        hl: &&FancySpan,-        label: &str,-        render_mode: LabelRenderMode,-    ) -> fmt::Result {-        self.render_highlight_gutter(-            f,-            max_gutter,-            line,-            all_highlights,-            LabelRenderMode::SingleLine,-        )?;-        let mut curr_offset = 1usize;-        for (offset_hl, vbar_offset) in vbar_offsets {-            while curr_offset < *vbar_offset + 1 {-                write!(f, " ")?;-                curr_offset += 1;-            }-            if *offset_hl != hl {-                write!(f, "{}", chars.vbar.to_string().style(offset_hl.style))?;-                curr_offset += 1;-            } else {-                let lines = match render_mode {-                    LabelRenderMode::SingleLine => format!(-                        "{}{} {}",-                        chars.lbot,-                        chars.hbar.to_string().repeat(2),-                        label,-                    ),-                    LabelRenderMode::MultiLineFirst => {-                        format!("{}{}{} {}", chars.lbot, chars.hbar, chars.rcross, label,)-                    }-                    LabelRenderMode::MultiLineRest => {-                        format!("  {} {}", chars.vbar, label,)-                    }-                };-                writeln!(f, "{}", lines.style(hl.style))?;-                break;-            }-        }-        Ok(())-    }--    fn render_multi_line_end_single(-        &self,-        f: &mut impl fmt::Write,-        label: &str,-        style: Style,-        render_mode: LabelRenderMode,-    ) -> fmt::Result {-        match render_mode {-            LabelRenderMode::SingleLine => {-                writeln!(f, "{} {}", self.theme.characters.hbar.style(style), label)?;-            }-            LabelRenderMode::MultiLineFirst => {-                writeln!(f, "{} {}", self.theme.characters.rcross.style(style), label)?;-            }-            LabelRenderMode::MultiLineRest => {-                writeln!(f, "{} {}", self.theme.characters.vbar.style(style), label)?;-            }-        }--        Ok(())-    }--    fn get_lines<'a>(-        &'a self,-        source: &'a dyn SourceCode,-        context_span: &'a SourceSpan,-    ) -> Result<Vec<Line>, fmt::Error> {-        let context_data = source-            .read_span(context_span, self.context_lines, self.context_lines)-            .map_err(|_| fmt::Error)?;-        let context = String::from_utf8_lossy(context_data.data());-        let mut column = context_data.column();-        let mut offset = context_data.span().offset();-        let mut line_offset = offset;-        let mut line_str = String::with_capacity(context.len());-        let mut lines = Vec::with_capacity(1);-        let mut iter = context.chars().peekable();-        while let Some(ch) = iter.next() {-            offset += ch.len_utf8();-            match ch {-                '\r' if iter.next_if_eq(&'\n').is_some() => {-                    offset += 1;-                    column = 0;-                }-                '\r' => {-                    line_str.push(ch);-                    column += 1;-                }-                '\n' => {-                    column = 0;-                }-                _ => {-                    line_str.push(ch);-                    column += 1;-                }-            }--            if column == 0 || iter.peek().is_none() {-                lines.push(Line {-                    offset: line_offset,-                    length: offset - line_offset,-                    text: line_str.clone(),-                });-                line_str.clear();-                line_offset = offset;-            }-        }-        Ok(lines)-    }-}--impl ReportHandler for SwcReportHandler {-    fn debug(&self, diagnostic: &dyn Diagnostic, f: &mut fmt::Formatter<'_>) -> fmt::Result {-        if f.alternate() {-            return fmt::Debug::fmt(diagnostic, f);-        }--        self.render_report(f, diagnostic)-    }-}--/*-Support types-*/--#[derive(PartialEq, Debug)]-enum LabelRenderMode {-    /// we're rendering a single line label (or not rendering in any special-    /// way)-    SingleLine,-    /// we're rendering a multiline label-    MultiLineFirst,-    /// we're rendering the rest of a multiline label-    MultiLineRest,-}--#[derive(Debug)]-struct Line {-    offset: usize,-    length: usize,-    text: String,-}--impl Line {-    fn span_line_only(&self, span: &FancySpan) -> bool {-        span.offset() >= self.offset && span.offset() + span.len() <= self.offset + self.length-    }--    /// Returns whether `span` should be visible on this line, either in the-    /// gutter or under the text on this line-    fn span_applies(&self, span: &FancySpan) -> bool {-        let spanlen = if span.len() == 0 { 1 } else { span.len() };-        // Span starts in this line--        (span.offset() >= self.offset && span.offset() < self.offset + self.length)-            // Span passes through this line-            || (span.offset() < self.offset && span.offset() + spanlen > self.offset + self.length) //todo-            // Span ends on this line-            || (span.offset() + spanlen > self.offset && span.offset() + spanlen <= self.offset + self.length)-    }--    /// Returns whether `span` should be visible on this line in the gutter (so-    /// this excludes spans that are only visible on this line and do not-    /// span multiple lines)-    fn span_applies_gutter(&self, span: &FancySpan) -> bool {-        let spanlen = if span.len() == 0 { 1 } else { span.len() };-        // Span starts in this line-        self.span_applies(span)-            && !(-                // as long as it doesn't start *and* end on this line-                (span.offset() >= self.offset && span.offset() < self.offset + self.length)-                    && (span.offset() + spanlen > self.offset-                        && span.offset() + spanlen <= self.offset + self.length)-            )-    }--    // A 'flyby' is a multi-line span that technically covers this line, but-    // does not begin or end within the line itself. This method is used to-    // calculate gutters.-    fn span_flyby(&self, span: &FancySpan) -> bool {-        // The span itself starts before this line's starting offset (so, in a-        // prev line).-        span.offset() < self.offset-            // ...and it stops after this line's end.-            && span.offset() + span.len() > self.offset + self.length-    }--    // Does this line contain the *beginning* of this multiline span?-    // This assumes self.span_applies() is true already.-    fn span_starts(&self, span: &FancySpan) -> bool {-        span.offset() >= self.offset-    }--    // Does this line contain the *end* of this multiline span?-    // This assumes self.span_applies() is true already.-    fn span_ends(&self, span: &FancySpan) -> bool {-        span.offset() + span.len() >= self.offset-            && span.offset() + span.len() <= self.offset + self.length-    }-}--#[derive(Debug, Clone)]-struct FancySpan {-    /// this is deliberately an option of a vec because I wanted to be very-    /// explicit that there can also be *no* label. If there is a label, it-    /// can have multiple lines which is what the vec is for.-    label: Option<Vec<String>>,-    span: SourceSpan,-    style: Style,-}--impl PartialEq for FancySpan {-    fn eq(&self, other: &Self) -> bool {-        self.label == other.label && self.span == other.span-    }-}--fn split_label(v: String) -> Vec<String> {-    v.split('\n').map(|i| i.to_string()).collect()-}--impl FancySpan {-    fn new(label: Option<String>, span: SourceSpan, style: Style) -> Self {-        FancySpan {-            label: label.map(split_label),-            span,-            style,-        }-    }--    fn style(&self) -> Style {-        self.style-    }--    fn label(&self) -> Option<String> {-        self.label-            .as_ref()-            .map(|l| l.join("\n").style(self.style()).to_string())-    }--    fn label_parts(&self) -> Option<Vec<String>> {-        self.label.as_ref().map(|l| {-            l.iter()-                .map(|i| i.style(self.style()).to_string())-                .collect()-        })-    }--    fn offset(&self) -> usize {-        self.span.offset()-    }--    fn len(&self) -> usize {-        self.span.len()-    }-}

deps/swc/bindings/binding_nodejs_support_wasm/src/lib.rs

deleted file mode 100644@@ -1,345 +0,0 @@-use std::{-    iter::once,-    mem::take,-    sync::{Arc, Mutex},-};--use anyhow::Error;-use error_reporter::SwcReportHandler;-use js_sys::Uint8Array;-use miette::{GraphicalTheme, LabeledSpan, ThemeCharacters, ThemeStyles};-use serde::Serialize;-use swc_common::{-    errors::{DiagnosticBuilder, DiagnosticId, Emitter, Handler, HANDLER},-    sync::Lrc,-    SourceMap, Span, GLOBALS,-};-use swc_error_reporters::{convert_span, to_pretty_source_code};-use swc_ts_fast_strip::{Options, TransformOutput};-use wasm_bindgen::prelude::*;-use wasm_bindgen_futures::{future_to_promise, js_sys::Promise};--mod error_reporter;-mod nodejs;--/// Custom interface definitions for `@swc/nodejs-support-wasm`.-#[wasm_bindgen(typescript_custom_section)]-const INTERFACE_DEFINITIONS: &'static str = r#"-export declare function transform(src: string | Uint8Array, opts?: Options): Promise<TransformOutput>;-export declare function transformSync(src: string | Uint8Array, opts?: Options): TransformOutput;-export declare function transformModuleSyntax(src: string | Uint8Array): ModuleSyntaxTransformOutput;-export declare function getFirstExpression(src: string | Uint8Array, startColumn: number): string;-export declare function isValidSyntax(src: string | Uint8Array): boolean;-export declare function isRecoverableError(src: string | Uint8Array): boolean;-export declare function tokenize(src: string | Uint8Array): Token[];-export declare function findTopLevelAwaits(src: string | Uint8Array): TopLevelAwaitLocation[];-export type { Options, TransformOutput };--export type TokenKind = "keyword" | "identifier" | "number" | "bigint" | "string" | "template" | "regexp" | "comment" | "punctuator";--export interface Token {-    kind: TokenKind;-    /** Zero-based UTF-16 offset, inclusive. */-    start: number;-    /** Zero-based UTF-16 offset, exclusive. */-    end: number;-}--export interface TopLevelAwaitLocation {-    /** One-based line number. */-    line: number;-    /** Zero-based UTF-16 column. */-    column: number;-}--export interface ModuleSyntaxTransformOutput {-    code: string;-    hadModuleSyntax: boolean;-}-"#;--#[wasm_bindgen(skip_typescript)]-pub fn transform(input: JsValue, options: JsValue) -> Promise {-    future_to_promise(async move { transform_sync(input, options) })-}--#[wasm_bindgen(js_name = "transformSync", skip_typescript)]-pub fn transform_sync(input: JsValue, options: JsValue) -> Result<JsValue, JsValue> {-    let options: Options = if options.is_falsy() {-        Default::default()-    } else {-        serde_wasm_bindgen::from_value(options)?-    };--    let input = coerce_input(input)?;--    let result = GLOBALS.set(&Default::default(), || operate(input, options));--    match result {-        Ok(v) => Ok(serde_wasm_bindgen::to_value(&v)?),-        Err(errors) => Err(serde_wasm_bindgen::to_value(&errors[0])?),-    }-}--#[wasm_bindgen(js_name = "transformModuleSyntax", skip_typescript)]-pub fn transform_module_syntax(input: JsValue) -> Result<JsValue, JsValue> {-    let input = coerce_input(input)?;-    let output = nodejs::transform_module_syntax(input);--    Ok(serde_wasm_bindgen::to_value(&output)?)-}--#[wasm_bindgen(js_name = "getFirstExpression", skip_typescript)]-pub fn get_first_expression(input: JsValue, start_column: u32) -> Result<String, JsValue> {-    let input = coerce_input(input)?;--    Ok(nodejs::get_first_expression(input, start_column))-}--#[wasm_bindgen(js_name = "isValidSyntax", skip_typescript)]-pub fn is_valid_syntax(input: JsValue) -> Result<bool, JsValue> {-    let input = coerce_input(input)?;--    Ok(nodejs::is_valid_syntax(input))-}--#[wasm_bindgen(js_name = "isRecoverableError", skip_typescript)]-pub fn is_recoverable_error(input: JsValue) -> Result<bool, JsValue> {-    let input = coerce_input(input)?;--    Ok(nodejs::is_recoverable_error(input))-}--/// Returns compact tokens for syntax highlighting, including a partial prefix-/// when the input is incomplete or invalid.-#[wasm_bindgen(skip_typescript)]-pub fn tokenize(input: JsValue) -> Result<JsValue, JsValue> {-    let input = coerce_input(input)?;-    Ok(serde_wasm_bindgen::to_value(&nodejs::tokenize(&input))?)-}--/// Returns module-scope await locations in source order using Acorn-/// coordinates.-#[wasm_bindgen(js_name = "findTopLevelAwaits", skip_typescript)]-pub fn find_top_level_awaits(input: JsValue) -> Result<JsValue, JsValue> {-    let input = coerce_input(input)?;-    Ok(serde_wasm_bindgen::to_value(-        &nodejs::find_top_level_awaits(&input),-    )?)-}--fn coerce_input(input: JsValue) -> Result<String, JsValue> {-    match input.as_string() {-        Some(input) => Ok(input),-        None => {-            if input.is_instance_of::<Uint8Array>() {-                let input = input.unchecked_into::<Uint8Array>();--                String::from_utf8(input.to_vec())-                    .map_err(|_| JsValue::from_str("Input Uint8Array is not valid utf-8"))-            } else {-                Err(JsValue::from_str("Input is not a string or Uint8Array"))-            }-        }-    }-}--fn operate(input: String, options: Options) -> Result<TransformOutput, Vec<JsonDiagnostic>> {-    let cm = Lrc::new(SourceMap::default());--    try_with_json_handler(cm.clone(), |handler| {-        swc_ts_fast_strip::operate(&cm, handler, input, options).map_err(anyhow::Error::new)-    })-}--#[derive(Clone)]-struct JsonErrorWriter {-    errors: Arc<Mutex<Vec<JsonDiagnostic>>>,-    /// Successful transforms never need the graphical diagnostic reporter.-    reporter: Option<SwcReportHandler>,-    cm: Lrc<SourceMap>,-}--fn try_with_json_handler<F, Ret>(cm: Lrc<SourceMap>, op: F) -> Result<Ret, Vec<JsonDiagnostic>>-where-    F: FnOnce(&Handler) -> Result<Ret, Error>,-{-    let wr = JsonErrorWriter {-        errors: Default::default(),-        reporter: None,-        cm,-    };-    let emitter: Box<dyn Emitter> = Box::new(wr.clone());--    let handler = Handler::with_emitter(true, false, emitter);--    let ret = HANDLER.set(&handler, || op(&handler));--    if handler.has_errors() {-        let mut lock = wr.errors.lock().unwrap();-        let error = take(&mut *lock);--        Err(error)-    } else {-        Ok(ret.expect("it should not fail without emitting errors to handler"))-    }-}--impl Emitter for JsonErrorWriter {-    fn emit(&mut self, db: &mut DiagnosticBuilder) {-        let d = &**db;--        let snippet = d.span.primary_span().and_then(|span| {-            let mut snippet = String::new();-            let reporter = self.reporter.get_or_insert_with(json_reporter);-            match reporter.render_report(-                &mut snippet,-                &Snippet {-                    source_code: &to_pretty_source_code(&self.cm, true),-                    span,-                },-            ) {-                Ok(()) => Some(snippet),-                Err(_) => None,-            }-        });--        let children = d-            .children-            .iter()-            .map(|d| todo!("json subdiagnostic: {d:?}"))-            .collect::<Vec<_>>();--        let error_code = match &d.code {-            Some(DiagnosticId::Error(s)) => Some(&**s),-            Some(DiagnosticId::Lint(s)) => Some(&**s),-            None => None,-        };--        let start = d-            .span-            .primary_span()-            .and_then(|span| self.cm.try_lookup_char_pos(span.lo()).ok());--        let end = d-            .span-            .primary_span()-            .and_then(|span| self.cm.try_lookup_char_pos(span.hi()).ok());--        let filename = start.as_ref().map(|loc| loc.file.name.to_string());--        let error = JsonDiagnostic {-            code: error_code.map(|s| s.to_string()),-            message: d.message[0].0.to_string(),-            snippet,-            filename,-            start_line: start.as_ref().map(|loc| loc.line),-            start_column: start.as_ref().map(|loc| loc.col_display),-            end_line: end.as_ref().map(|loc| loc.line),-            end_column: end.as_ref().map(|loc| loc.col_display),-            children,-        };--        self.errors.lock().unwrap().push(error);-    }--    fn take_diagnostics(&mut self) -> Vec<String> {-        Default::default()-    }-}--fn json_reporter() -> SwcReportHandler {-    SwcReportHandler::default().with_theme(GraphicalTheme {-        characters: ThemeCharacters {-            hbar: ' ',-            vbar: ' ',-            xbar: ' ',-            vbar_break: ' ',-            ltop: ' ',-            rtop: ' ',-            mtop: ' ',-            lbot: ' ',-            rbot: ' ',-            mbot: ' ',-            error: "".into(),-            warning: "".into(),-            advice: "".into(),-            ..ThemeCharacters::ascii()-        },-        styles: ThemeStyles::none(),-    })-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-struct JsonDiagnostic {-    /// Error code-    #[serde(skip_serializing_if = "Option::is_none")]-    code: Option<String>,-    message: String,--    #[serde(skip_serializing_if = "Option::is_none")]-    snippet: Option<String>,--    #[serde(skip_serializing_if = "Option::is_none")]-    filename: Option<String>,--    #[serde(skip_serializing_if = "Option::is_none")]-    start_line: Option<usize>,-    #[serde(skip_serializing_if = "Option::is_none")]-    start_column: Option<usize>,--    #[serde(skip_serializing_if = "Option::is_none")]-    end_line: Option<usize>,-    #[serde(skip_serializing_if = "Option::is_none")]-    end_column: Option<usize>,--    #[serde(skip_serializing_if = "Vec::is_empty")]-    children: Vec<JsonSubdiagnostic>,-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-struct JsonSubdiagnostic {-    message: String,-    #[serde(skip_serializing_if = "Option::is_none")]-    snippet: Option<String>,-    filename: String,-    line: usize,-}--struct Snippet<'a> {-    source_code: &'a dyn miette::SourceCode,-    span: Span,-}--impl miette::Diagnostic for Snippet<'_> {-    fn source_code(&self) -> Option<&dyn miette::SourceCode> {-        if self.span.lo().is_dummy() || self.span.hi().is_dummy() {-            return None;-        }--        Some(self.source_code)-    }--    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {-        Some(Box::new(once(LabeledSpan::new_with_span(-            None,-            convert_span(self.span),-        ))))-    }-}--impl std::error::Error for Snippet<'_> {}--impl std::fmt::Display for Snippet<'_> {-    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {-        Ok(())-    }-}--impl std::fmt::Debug for Snippet<'_> {-    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {-        Ok(())-    }-}

deps/swc/bindings/binding_nodejs_support_wasm/src/nodejs.rs

deleted file mode 100644@@ -1,1369 +0,0 @@-//! Node.js-specific helpers for `@swc/nodejs-support-wasm`.-//!-//! These functions intentionally expose only the compact operations Node needs-//! from Rust and avoid serializing SWC ASTs into JavaScript.--use serde::Serialize;-use swc_common::{comments::SingleThreadedComments, sync::Lrc, FileName, SourceMap, Span, Spanned};-use swc_ecma_ast::{-    CallExpr, Callee, Decl, DefaultDecl, EsVersion, ExportSpecifier, Expr, ImportDecl,-    ImportSpecifier, MetaPropExpr, MetaPropKind, Module, ModuleDecl, ModuleExportName, ModuleItem,-    NamedExport, ObjectLit,-};-use swc_ecma_parser::{-    error::{Error as ParseError, SyntaxError},-    lexer::Lexer,-    unstable::{Token, TokenAndSpan},-    EsSyntax, Parser, StringInput, Syntax, TsSyntax,-};-use swc_ecma_visit::{Visit, VisitWith};--mod awaits;-mod position;-mod tokenize;--#[cfg(test)]-mod fixtures;--pub use self::{awaits::find_top_level_awaits, tokenize::tokenize};--const DYNAMIC_IMPORT_NAME: &str = "__nodeREPLDynamicImport";--#[derive(Debug, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ModuleSyntaxTransformOutput {-    pub code: String,-    pub had_module_syntax: bool,-}--/// Rewrites Node REPL module syntax into script syntax.-///-/// The transform follows Node's edit-list approach: static imports become-/// awaited dynamic imports, dynamic `import(...)` is routed through Node's REPL-/// helper, and exports are unwrapped or dropped depending on whether they have-/// runtime declarations.-pub fn transform_module_syntax(code: String) -> ModuleSyntaxTransformOutput {-    if !code.contains("import") && !code.contains("export") {-        return ModuleSyntaxTransformOutput {-            code,-            had_module_syntax: false,-        };-    }--    let Some(module) = parse_module(&code) else {-        return ModuleSyntaxTransformOutput {-            code,-            had_module_syntax: false,-        };-    };--    let (edits, hoisted) = {-        let mut transform = ModuleSyntaxTransform::new(&code);--        for item in &module.body {-            transform.collect_module_item_edit(item);-        }--        let replaced_ranges = transform-            .edits-            .iter()-            .map(|edit| (edit.start, edit.end))-            .collect::<Vec<_>>();-        module.visit_with(&mut ModuleFeatureCollector {-            code: &code,-            edits: &mut transform.edits,-            replaced_ranges: &replaced_ranges,-        });--        if transform.edits.is_empty() && transform.hoisted.is_empty() {-            return ModuleSyntaxTransformOutput {-                code,-                had_module_syntax: false,-            };-        }--        (transform.edits, transform.hoisted)-    };--    ModuleSyntaxTransformOutput {-        code: prepend_hoisted_imports(apply_edits(code, edits), hoisted),-        had_module_syntax: true,-    }-}--/// Extracts the first source expression associated with a V8 error column.-///-/// `start_column` is interpreted as a JavaScript UTF-16 code-unit column to-/// match Node/V8 source locations. The implementation uses only lexer tokens-/// because the source line can be incomplete JavaScript.-pub fn get_first_expression(code: String, start_column: u32) -> String {-    let start_byte = utf16_column_to_byte_pos(&code, start_column);-    let mut last_token = None;-    let mut potential_expression_start_token = None;-    let mut first_member_access_name_token = None;-    let mut pending_optional_chain_name_token = None;-    let mut terminating_byte = None;-    let mut paren_level = 0u32;-    let mut member_bracket_depth = 0u32;--    for token in lex_tokens(&code) {-        if token.token == Token::Eof {-            break;-        }--        let Some((token_start, token_end)) = span_range(token.span) else {-            continue;-        };-        if token_start < start_byte {-            if token.token == Token::Semi {-                potential_expression_start_token = None;-                first_member_access_name_token = None;-                pending_optional_chain_name_token = None;-                member_bracket_depth = 0;-                last_token = None;-                continue;-            }--            if member_bracket_depth > 0 {-                match token.token {-                    Token::LBracket => member_bracket_depth += 1,-                    Token::RBracket => {-                        member_bracket_depth = member_bracket_depth.saturating_sub(1);-                    }-                    _ => {}-                }-                last_token = Some(token);-                continue;-            }--            if is_member_identifier_token(&code, &token)-                && first_member_access_name_token.is_none()-                && potential_expression_start_token.is_none()-            {-                potential_expression_start_token = Some(token);-            }--            if token.token == Token::QuestionMark-                && last_token-                    .as_ref()-                    .is_some_and(|last: &TokenAndSpan| is_member_identifier_token(&code, last))-            {-                pending_optional_chain_name_token = last_token;-                last_token = Some(token);-                continue;-            }--            if token.token == Token::Dot-                && last_token-                    .as_ref()-                    .is_some_and(|last: &TokenAndSpan| last.token == Token::QuestionMark)-            {-                if let Some(name_token) = pending_optional_chain_name_token.take() {-                    first_member_access_name_token.get_or_insert(name_token);-                    last_token = Some(token);-                    continue;-                }-            } else if pending_optional_chain_name_token.take().is_some() {-                first_member_access_name_token = None;-            }--            if token.token == Token::LBracket-                && last_token-                    .as_ref()-                    .is_some_and(|last: &TokenAndSpan| is_member_identifier_token(&code, last))-            {-                first_member_access_name_token-                    .get_or_insert(potential_expression_start_token.unwrap_or(last_token.unwrap()));-                member_bracket_depth = 1;-                last_token = Some(token);-                continue;-            }--            if is_member_access_token(token.token) {-                if last_token-                    .as_ref()-                    .is_some_and(|last: &TokenAndSpan| is_member_identifier_token(&code, last))-                {-                    first_member_access_name_token.get_or_insert(-                        potential_expression_start_token.unwrap_or(last_token.unwrap()),-                    );-                    last_token = Some(token);-                    continue;-                }-            } else if token.token != Token::LParen && !is_member_name_token(&code, &token) {-                potential_expression_start_token = None;-                first_member_access_name_token = None;-            }--            if token.token == Token::LParen && first_member_access_name_token.is_some() {-                paren_level += 1;-                last_token = Some(token);-                continue;-            }--            if token.token == Token::LParen-                && last_token-                    .as_ref()-                    .is_some_and(|last: &TokenAndSpan| is_member_identifier_token(&code, last))-            {-                first_member_access_name_token-                    .get_or_insert(potential_expression_start_token.unwrap_or(last_token.unwrap()));-                paren_level += 1;-                last_token = Some(token);-                continue;-            }--            last_token = Some(token);-            continue;-        }--        if token.token == Token::LParen-            && last_token-                .as_ref()-                .is_some_and(|last: &TokenAndSpan| is_member_identifier_token(&code, last))-        {-            first_member_access_name_token-                .get_or_insert(potential_expression_start_token.unwrap_or(last_token.unwrap()));-        }--        match token.token {-            Token::LParen => {-                paren_level += 1;-            }-            Token::RParen => {-                paren_level = paren_level.saturating_sub(1);-                if paren_level == 0 {-                    terminating_byte = Some(token_end);-                    break;-                }-            }-            Token::Semi => {-                terminating_byte = Some(token_start);-                break;-            }-            _ => {}-        }-    }--    let start = first_member_access_name_token-        .and_then(|token| span_range(token.span).map(|(start, _)| start))-        .unwrap_or(start_byte);-    let end = terminating_byte.unwrap_or(code.len());--    if start >= code.len()-        || start > end-        || !code.is_char_boundary(start)-        || !code.is_char_boundary(end)-    {-        return String::new();-    }--    code[start..end].to_string()-}--/// Returns true when the source parses as a program or expression.-pub fn is_valid_syntax(code: String) -> bool {-    parses_as_program(&code) || parses_as_program(&format!("_={code}"))-}--/// Returns true for parser errors that should keep a Node REPL input open.-pub fn is_recoverable_error(code: String) -> bool {-    match parse_program_result(&code) {-        ParseOutcome::Valid => false,-        ParseOutcome::Invalid(errors) => {-            if errors-                .iter()-                .any(|error| is_recoverable_parse_error(&code, error))-            {-                return true;-            }--            code.trim_start().starts_with('{') && is_recoverable_error(format!("({code}"))-        }-    }-}--struct ModuleSyntaxTransform<'a> {-    code: &'a str,-    edits: Vec<Edit>,-    hoisted: Vec<String>,-}--impl<'a> ModuleSyntaxTransform<'a> {-    fn new(code: &'a str) -> Self {-        Self {-            code,-            edits: Vec::new(),-            hoisted: Vec::new(),-        }-    }--    fn collect_module_item_edit(&mut self, item: &ModuleItem) {-        let ModuleItem::ModuleDecl(decl) = item else {-            return;-        };--        match decl {-            ModuleDecl::Import(import) => {-                self.delete_span(import.span);-                if !import.type_only {-                    if let Some(script) = self.import_decl_to_script(import) {-                        self.hoisted.push(script);-                    }-                }-            }-            ModuleDecl::ExportDecl(export) => {-                if is_type_only_decl(&export.decl) {-                    self.delete_span(export.span);-                } else if let (Some((start, _)), Some((decl_start, _))) =-                    (span_range(export.span), span_range(export.decl.span()))-                {-                    push_range_edit(&mut self.edits, self.code, start, decl_start, String::new());-                }-            }-            ModuleDecl::ExportNamed(export) => {-                self.delete_span(export.span);-                if let Some(src) = &export.src {-                    if let Some(required_exports) = named_export_source_imports(export) {-                        self.hoist_validated_import(-                            &src.value.to_string_lossy(),-                            export.with.as_deref(),-                            &required_exports,-                        );-                    }-                }-            }-            ModuleDecl::ExportDefaultDecl(export) => {-                self.unwrap_default_declaration(export.span, export.decl.span(), &export.decl);-            }-            ModuleDecl::ExportDefaultExpr(export) => {-                self.unwrap_default_expression(-                    export.span,-                    export.expr.span(),-                    matches!(&*export.expr, Expr::Object(..)),-                );-            }-            ModuleDecl::ExportAll(export) => {-                self.delete_span(export.span);-                if !export.type_only {-                    self.hoist_import(&export.src.value.to_string_lossy(), export.with.as_deref());-                }-            }-            ModuleDecl::TsImportEquals(import) => {-                if import.is_type_only {-                    self.delete_span(import.span);-                }-            }-            ModuleDecl::TsNamespaceExport(export) => {-                self.delete_span(export.span);-            }-            ModuleDecl::TsExportAssignment(..) => {}-        }-    }--    fn delete_span(&mut self, span: Span) {-        let replacement = if needs_statement_separator(self.code, span) {-            ";"-        } else {-            ""-        };-        self.replace_span(span, replacement.to_string());-    }--    fn replace_span(&mut self, span: Span, text: String) {-        push_span_edit(&mut self.edits, self.code, span, text);-    }--    fn hoist_import(&mut self, specifier: &str, with: Option<&ObjectLit>) {-        self.hoisted.push(format!(-            "await {};",-            await_import(self.code, specifier, with, &[])-        ));-    }--    fn hoist_validated_import(-        &mut self,-        specifier: &str,-        with: Option<&ObjectLit>,-        required_exports: &[String],-    ) {-        self.hoisted.push(format!(-            "await {};",-            await_import(self.code, specifier, with, required_exports)-        ));-    }--    fn import_decl_to_script(&self, node: &ImportDecl) -> Option<String> {-        let specifier = node.src.value.to_string_lossy();-        let with = node.with.as_deref();--        if node.specifiers.is_empty() {-            return Some(format!(-                "await {};",-                await_import(self.code, &specifier, with, &[])-            ));-        }--        let mut namespace_name = None;-        let mut default_name = None;-        let mut named = Vec::new();-        let mut required_exports = Vec::new();--        for specifier in &node.specifiers {-            match specifier {-                ImportSpecifier::Namespace(specifier) => {-                    namespace_name = Some(specifier.local.sym.to_string());-                }-                ImportSpecifier::Default(specifier) => {-                    default_name = Some(specifier.local.sym.to_string());-                    push_required_export(&mut required_exports, "default".to_string());-                }-                ImportSpecifier::Named(specifier) => {-                    if specifier.is_type_only {-                        continue;-                    }--                    let local = specifier.local.sym.to_string();-                    let imported = specifier-                        .imported-                        .as_ref()-                        .map(module_export_name)-                        .unwrap_or_else(|| local.clone());-                    push_required_export(&mut required_exports, imported.clone());-                    named.push((local, imported));-                }-            }-        }--        if namespace_name.is_none() && default_name.is_none() && named.is_empty() {-            return None;-        }--        let import = await_import(self.code, &specifier, with, &required_exports);-        if let Some(namespace_name) = namespace_name {-            let mut out = format!("const {namespace_name} = await {import};");-            if let Some(default_name) = default_name {-                out.push_str(&format!(-                    " const {default_name} = {namespace_name}.default;"-                ));-            }-            return Some(out);-        }--        // Declare the user's bindings so subsequent REPL inputs can access them.-        // Like Node's REPL transform, these capture the initial export values;-        // namespace imports still refer to the live module namespace object.-        let mut bindings = Vec::with_capacity(named.len() + usize::from(default_name.is_some()));-        if let Some(default_name) = default_name {-            bindings.push(format!("default: {default_name}"));-        }-        for (local, imported) in named {-            // Quote arbitrary export names while keeping ordinary names readable.-            let key = if is_identifier_name(&imported) {-                imported-            } else {-                json_string(&imported)-            };-            bindings.push(format!("{key}: {local}"));-        }-        Some(format!(-            "const {{ {} }} = await {import};",-            bindings.join(", ")-        ))-    }--    fn unwrap_default_declaration(-        &mut self,-        export_span: Span,-        decl_span: Span,-        decl: &DefaultDecl,-    ) {-        if matches!(decl, DefaultDecl::TsInterfaceDecl(..)) {-            self.delete_span(export_span);-            return;-        }--        let (Some((export_start, _)), Some((decl_start, decl_end))) =-            (span_range(export_span), span_range(decl_span))-        else {-            return;-        };--        push_range_edit(-            &mut self.edits,-            self.code,-            export_start,-            decl_start,-            String::new(),-        );--        if default_declaration_needs_parentheses(decl) {-            push_range_edit(-                &mut self.edits,-                self.code,-                decl_start,-                decl_start,-                "(".to_string(),-            );-            push_range_edit(-                &mut self.edits,-                self.code,-                decl_end,-                decl_end,-                ");".to_string(),-            );-        }-    }--    fn unwrap_default_expression(-        &mut self,-        export_span: Span,-        expr_span: Span,-        needs_parentheses: bool,-    ) {-        let (Some((export_start, export_end)), Some((expr_start, expr_end))) =-            (span_range(export_span), span_range(expr_span))-        else {-            return;-        };--        push_range_edit(-            &mut self.edits,-            self.code,-            export_start,-            expr_start,-            String::new(),-        );--        if needs_parentheses {-            push_range_edit(-                &mut self.edits,-                self.code,-                expr_start,-                expr_start,-                "(".to_string(),-            );-        }--        let has_separator = self-            .code-            .get(expr_end..export_end)-            .is_some_and(|tail| tail.contains(';'));-        if needs_parentheses || !has_separator {-            let mut suffix = String::new();-            if needs_parentheses {-                suffix.push(')');-            }-            if !has_separator {-                suffix.push(';');-            }-            push_range_edit(&mut self.edits, self.code, expr_end, expr_end, suffix);-        }-    }-}--fn await_import(-    code: &str,-    specifier: &str,-    with: Option<&ObjectLit>,-    required_exports: &[String],-) -> String {-    let mut out = format!("{DYNAMIC_IMPORT_NAME}({}", json_string(specifier));-    if let Some(options) = import_options_to_dynamic_options(code, with) {-        out.push_str(", ");-        out.push_str(&options);-    }-    out.push(')');-    if !required_exports.is_empty() {-        out.push_str(".then((m) => { ");-        for export_name in required_exports {-            out.push_str("if (!(");-            out.push_str(&json_string(export_name));-            out.push_str(" in m)) throw new SyntaxError(");-            out.push_str(&json_string(&format!(-                "The requested module '{specifier}' does not provide an export named \-                 '{export_name}'"-            )));-            out.push_str("); ");-        }-        out.push_str("return m; })");-    }-    out-}--fn import_options_to_dynamic_options(code: &str, with: Option<&ObjectLit>) -> Option<String> {-    let attributes = slice_span(code, with?.span)?;-    Some(format!("{{ with: {attributes} }}"))-}--fn default_declaration_needs_parentheses(decl: &DefaultDecl) -> bool {-    matches!(decl, DefaultDecl::Class(class) if class.ident.is_none())-        || matches!(decl, DefaultDecl::Fn(function) if function.ident.is_none())-}--fn is_type_only_decl(decl: &Decl) -> bool {-    matches!(decl, Decl::TsInterface(..) | Decl::TsTypeAlias(..))-}--fn named_export_source_imports(export: &NamedExport) -> Option<Vec<String>> {-    if export.type_only {-        return None;-    }--    let mut loads_source = export.specifiers.is_empty();-    let mut required_exports = Vec::new();--    for specifier in &export.specifiers {-        match specifier {-            ExportSpecifier::Named(named) => {-                if named.is_type_only {-                    continue;-                }--                loads_source = true;-                push_required_export(&mut required_exports, module_export_name(&named.orig));-            }-            ExportSpecifier::Default(..) => {-                loads_source = true;-                push_required_export(&mut required_exports, "default".to_string());-            }-            ExportSpecifier::Namespace(..) => {-                loads_source = true;-            }-        }-    }--    loads_source.then_some(required_exports)-}--fn push_required_export(required_exports: &mut Vec<String>, export_name: String) {-    if !required_exports-        .iter()-        .any(|required| required == &export_name)-    {-        required_exports.push(export_name);-    }-}--fn module_export_name(name: &ModuleExportName) -> String {-    match name {-        ModuleExportName::Ident(ident) => ident.sym.to_string(),-        ModuleExportName::Str(string) => string.value.to_string_lossy().into_owned(),-    }-}--#[derive(Clone, Debug, Eq, PartialEq)]-struct Edit {-    start: usize,-    end: usize,-    text: String,-}--fn push_span_edit(edits: &mut Vec<Edit>, code: &str, span: Span, text: String) {-    if let Some((start, end)) = span_range(span) {-        push_range_edit(edits, code, start, end, text);-    }-}--fn push_range_edit(edits: &mut Vec<Edit>, code: &str, start: usize, end: usize, text: String) {-    if start <= end && end <= code.len() {-        edits.push(Edit { start, end, text });-    }-}--fn apply_edits(mut code: String, mut edits: Vec<Edit>) -> String {-    edits.sort_by(|a, b| b.start.cmp(&a.start).then_with(|| b.end.cmp(&a.end)));--    for edit in edits {-        if edit.start <= edit.end-            && edit.end <= code.len()-            && code.is_char_boundary(edit.start)-            && code.is_char_boundary(edit.end)-        {-            code.replace_range(edit.start..edit.end, &edit.text);-        }-    }--    code-}--fn needs_statement_separator(code: &str, span: Span) -> bool {-    let Some((start, end)) = span_range(span) else {-        return false;-    };--    code[..start].chars().any(|ch| !ch.is_whitespace())-        && code[end..].chars().any(|ch| !ch.is_whitespace())-}--fn prepend_hoisted_imports(code: String, hoisted: Vec<String>) -> String {-    if hoisted.is_empty() {-        return code;-    }--    let imports = hoisted.join("\n");-    if code.starts_with("#!") {-        if let Some(line_end) = code.find('\n') {-            let insert_at = line_end + 1;-            let (hashbang, rest) = code.split_at(insert_at);-            if rest.is_empty() || rest.starts_with('\n') {-                format!("{hashbang}{imports}{rest}")-            } else {-                format!("{hashbang}{imports}\n{rest}")-            }-        } else {-            format!("{code}\n{imports}")-        }-    } else if code.is_empty() {-        imports-    } else if code.starts_with('\n') || code.starts_with("\r\n") {-        format!("{imports}{code}")-    } else {-        format!("{imports}\n{code}")-    }-}--struct ModuleFeatureCollector<'a, 'b> {-    code: &'a str,-    edits: &'b mut Vec<Edit>,-    replaced_ranges: &'b [(usize, usize)],-}--impl Visit for ModuleFeatureCollector<'_, '_> {-    fn visit_call_expr(&mut self, node: &CallExpr) {-        if matches!(node.callee, Callee::Import(..)) {-            if let Some((start, end)) = span_range(node.span) {-                if !range_is_replaced(self.replaced_ranges, start, end) {-                    let original = &self.code[start..end];-                    if original.starts_with("import") {-                        self.edits.push(Edit {-                            start,-                            end: start + "import".len(),-                            text: DYNAMIC_IMPORT_NAME.to_string(),-                        });-                    }-                }-            }-        }--        node.visit_children_with(self);-    }--    fn visit_meta_prop_expr(&mut self, node: &MetaPropExpr) {-        if node.kind == MetaPropKind::ImportMeta {-            if let Some((start, end)) = span_range(node.span) {-                if !range_is_replaced(self.replaced_ranges, start, end) {-                    self.edits.push(Edit {-                        start,-                        end,-                        text: import_meta_error_expression(),-                    });-                }-            }-        }-    }-}--fn range_is_replaced(replaced_ranges: &[(usize, usize)], start: usize, end: usize) -> bool {-    replaced_ranges-        .iter()-        .any(|(replace_start, replace_end)| start >= *replace_start && end <= *replace_end)-}--fn import_meta_error_expression() -> String {-    "(() => { throw new SyntaxError(\"Cannot use import.meta outside a module\"); })()".to_string()-}--fn is_identifier_name(value: &str) -> bool {-    let mut chars = value.chars();-    let Some(first) = chars.next() else {-        return false;-    };--    if !(first == '_' || first == '$' || first.is_ascii_alphabetic()) {-        return false;-    }--    chars.all(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphanumeric())-}--enum ParseOutcome {-    Valid,-    Invalid(Vec<ParseError>),-}--fn parse_program_result(code: &str) -> ParseOutcome {-    let es = parse_program_result_with_syntax(code, Syntax::Es(es_syntax()));-    if matches!(es, ParseOutcome::Valid) {-        return es;-    }--    parse_program_result_with_syntax(code, Syntax::Typescript(ts_syntax()))-}--fn parse_program_result_with_syntax(code: &str, syntax: Syntax) -> ParseOutcome {-    let cm = Lrc::new(SourceMap::default());-    let fm = cm.new_source_file(FileName::Anon.into(), code.to_string());-    let comments = SingleThreadedComments::default();-    let lexer = Lexer::new(-        syntax,-        EsVersion::latest(),-        StringInput::from(&*fm),-        Some(&comments),-    );-    let mut parser = Parser::new_from(lexer);--    match parser.parse_program() {-        Ok(..) => {-            let errors = parser.take_errors();-            if errors.is_empty() {-                ParseOutcome::Valid-            } else {-                ParseOutcome::Invalid(errors)-            }-        }-        Err(error) => {-            let mut errors = vec![error];-            errors.extend(parser.take_errors());-            ParseOutcome::Invalid(errors)-        }-    }-}--fn parse_module(code: &str) -> Option<Module> {-    parse_module_with_syntax(code, Syntax::Es(es_syntax()))-        .or_else(|| parse_module_with_syntax(code, Syntax::Typescript(ts_syntax())))-}--fn parse_module_with_syntax(code: &str, syntax: Syntax) -> Option<Module> {-    let cm = Lrc::new(SourceMap::default());-    let fm = cm.new_source_file(FileName::Anon.into(), code.to_string());-    let comments = SingleThreadedComments::default();-    let lexer = Lexer::new(-        syntax,-        EsVersion::latest(),-        StringInput::from(&*fm),-        Some(&comments),-    );-    let mut parser = Parser::new_from(lexer);-    let module = parser.parse_module().ok()?;--    if parser.take_errors().is_empty() {-        Some(module)-    } else {-        None-    }-}--fn parses_as_program(code: &str) -> bool {-    matches!(parse_program_result(code), ParseOutcome::Valid)-}--fn lex_tokens(code: &str) -> Vec<TokenAndSpan> {-    let cm = Lrc::new(SourceMap::default());-    let fm = cm.new_source_file(FileName::Anon.into(), code.to_string());-    let comments = SingleThreadedComments::default();-    Lexer::new(-        Syntax::Es(es_syntax()),-        EsVersion::latest(),-        StringInput::from(&*fm),-        Some(&comments),-    )-    .collect()-}--fn es_syntax() -> EsSyntax {-    EsSyntax {-        auto_accessors: true,-        explicit_resource_management: true,-        import_attributes: true,-        ..Default::default()-    }-}--fn ts_syntax() -> TsSyntax {-    TsSyntax {-        decorators: true,-        ..Default::default()-    }-}--fn is_recoverable_parse_error(code: &str, error: &ParseError) -> bool {-    match error.kind() {-        SyntaxError::Eof | SyntaxError::UnterminatedTpl | SyntaxError::UnterminatedBlockComment => {-            true-        }-        SyntaxError::UnterminatedStrLit => has_trailing_line_continuation(code),-        SyntaxError::Expected(_, got) | SyntaxError::Unexpected { got, .. } => got == "<eof>",-        _ => false,-    }-}--fn has_trailing_line_continuation(code: &str) -> bool {-    code.ends_with("\\\n")-        || code.ends_with("\\\r")-        || code.ends_with("\\\r\n")-        || code.ends_with("\\\u{2028}")-        || code.ends_with("\\\u{2029}")-}--fn is_member_access_token(token: Token) -> bool {-    matches!(-        token,-        Token::Dot | Token::OptionalChain | Token::LBracket | Token::RBracket-    )-}--fn is_member_name_token(code: &str, token: &TokenAndSpan) -> bool {-    matches!(token.token, Token::Ident | Token::Str | Token::Num)-        || token.token.is_known_ident()-        || token_text_is_identifier(code, token)-}--fn is_member_identifier_token(code: &str, token: &TokenAndSpan) -> bool {-    token.token == Token::Ident-        || token.token.is_known_ident()-        || token_text_is_identifier(code, token)-}--fn token_text_is_identifier(code: &str, token: &TokenAndSpan) -> bool {-    slice_span(code, token.span).is_some_and(is_identifier_name)-}--fn slice_span(code: &str, span: Span) -> Option<&str> {-    let (start, end) = span_range(span)?;-    code.get(start..end)-}--fn span_range(span: Span) -> Option<(usize, usize)> {-    if span.lo.is_dummy() || span.hi.is_dummy() {-        return None;-    }--    let start = span.lo.0.checked_sub(1)? as usize;-    let end = span.hi.0.checked_sub(1)? as usize;-    Some((start, end))-}--fn utf16_column_to_byte_pos(code: &str, column: u32) -> usize {-    let mut utf16_pos = 0u32;--    for (byte_pos, ch) in code.char_indices() {-        if utf16_pos >= column {-            return byte_pos;-        }--        utf16_pos += ch.len_utf16() as u32;-        if utf16_pos > column {-            return byte_pos;-        }-    }--    code.len()-}--fn json_string(value: &str) -> String {-    serde_json::to_string(value).expect("serializing a string should not fail")-}--#[cfg(test)]-mod tests {-    use super::*;--    fn validated_import(specifier: &str, required_exports: &[&str]) -> String {-        validated_import_with_options(specifier, None, required_exports)-    }--    fn validated_import_with_options(-        specifier: &str,-        options: Option<&str>,-        required_exports: &[&str],-    ) -> String {-        let mut out = format!("{DYNAMIC_IMPORT_NAME}({}", json_string(specifier));-        if let Some(options) = options {-            out.push_str(", ");-            out.push_str(options);-        }-        out.push(')');--        if !required_exports.is_empty() {-            out.push_str(".then((m) => { ");-            for export_name in required_exports {-                out.push_str("if (!(");-                out.push_str(&json_string(export_name));-                out.push_str(" in m)) throw new SyntaxError(");-                out.push_str(&json_string(&format!(-                    "The requested module '{specifier}' does not provide an export named \-                     '{export_name}'"-                )));-                out.push_str("); ");-            }-            out.push_str("return m; })");-        }--        out-    }--    #[test]-    fn transform_import_forms() {-        assert_eq!(-            transform_module_syntax("import \"node:fs\";".into()).code,-            "await __nodeREPLDynamicImport(\"node:fs\");"-        );-        assert_eq!(-            transform_module_syntax("import fs from \"node:fs\";".into()).code,-            format!(-                "const {{ default: fs }} = await {};",-                validated_import("node:fs", &["default"])-            )-        );-        assert_eq!(-            transform_module_syntax("import { readFile as rf } from \"node:fs\";".into()).code,-            format!(-                "const {{ readFile: rf }} = await {};",-                validated_import("node:fs", &["readFile"])-            )-        );-        assert_eq!(-            transform_module_syntax("import { readFile as rf } from \"node:fs\";\nrf();".into())-                .code,-            format!(-                "const {{ readFile: rf }} = await {};\nrf();",-                validated_import("node:fs", &["readFile"])-            )-        );-        assert_eq!(-            transform_module_syntax("import def, * as ns from \"mod\";".into()).code,-            format!(-                "const ns = await {}; const def = ns.default;",-                validated_import("mod", &["default"])-            )-        );-        assert_eq!(-            transform_module_syntax("import def, * as ns from \"mod\";\ndef; ns;".into()).code,-            format!(-                "const ns = await {}; const def = ns.default;\ndef; ns;",-                validated_import("mod", &["default"])-            )-        );-        assert_eq!(-            transform_module_syntax("import { \"a-b\" as c } from \"mod\";".into()).code,-            format!(-                "const {{ \"a-b\": c }} = await {};",-                validated_import("mod", &["a-b"])-            )-        );-        assert_eq!(-            transform_module_syntax("import { \"a-b\" as c } from \"mod\";\nc;".into()).code,-            format!(-                "const {{ \"a-b\": c }} = await {};\nc;",-                validated_import("mod", &["a-b"])-            )-        );-        assert_eq!(-            transform_module_syntax(-                "import data from \"./data.json\" with { type: \"json\" };".into()-            )-            .code,-            format!(-                "const {{ default: data }} = await {};",-                validated_import_with_options(-                    "./data.json",-                    Some("{ with: { type: \"json\" } }"),-                    &["default"]-                )-            )-        );-        assert_eq!(-            transform_module_syntax("console.log(typeof fs);\nimport fs from \"node:fs\";".into())-                .code,-            format!(-                "const {{ default: fs }} = await {};\nconsole.log(typeof fs);\n",-                validated_import("node:fs", &["default"])-            )-        );-    }--    #[test]-    fn transform_export_forms() {-        assert_eq!(-            transform_module_syntax("export const x = 1;".into()).code,-            "const x = 1;"-        );-        assert_eq!(-            transform_module_syntax("export default value;".into()).code,-            "value;"-        );-        assert_eq!(-            transform_module_syntax("export default foo; doSomething();".into()).code,-            "foo; doSomething();"-        );-        assert_eq!(-            transform_module_syntax("export default { ...config };".into()).code,-            "({ ...config });"-        );-        assert_eq!(-            transform_module_syntax("export default function () {}".into()).code,-            "(function () {});"-        );-        assert_eq!(-            transform_module_syntax(-                "export default function f() { return import(\"node:fs\"); }".into()-            )-            .code,-            "function f() { return __nodeREPLDynamicImport(\"node:fs\"); }"-        );-        assert_eq!(-            transform_module_syntax(-                "export default function () { return import(\"node:fs\"); }".into()-            )-            .code,-            "(function () { return __nodeREPLDynamicImport(\"node:fs\"); });"-        );-        assert_eq!(-            transform_module_syntax("export default class {}".into()).code,-            "(class {});"-        );-        assert_eq!(transform_module_syntax("export { x };".into()).code, "");-        assert_eq!(-            transform_module_syntax("export * from \"mod\";".into()).code,-            "await __nodeREPLDynamicImport(\"mod\");"-        );-        assert_eq!(-            transform_module_syntax("console.log(1);\nexport { value } from \"mod\";".into()).code,-            format!(-                "await {};\nconsole.log(1);\n",-                validated_import("mod", &["value"])-            )-        );-    }--    #[test]-    fn transform_preserves_missing_export_failures() {-        let missing_default = transform_module_syntax("import missing from \"mod\";".into());-        assert!(missing_default.code.contains("\"default\" in m"));-        assert!(missing_default.code.contains("export named 'default'"));--        let missing_named = transform_module_syntax("import { missing, ok } from \"mod\";".into());-        assert!(missing_named.code.contains("\"missing\" in m"));-        assert!(missing_named.code.contains("\"ok\" in m"));--        let re_export = transform_module_syntax("export { missing } from \"mod\";".into());-        assert!(re_export.code.contains("\"missing\" in m"));-    }--    #[test]-    fn transform_preserves_import_binding_semantics() {-        assert_eq!(-            transform_module_syntax("import { spec } from \"m\";\nimport(spec);".into()).code,-            format!(-                "const {{ spec: spec }} = await {};\n__nodeREPLDynamicImport(spec);",-                validated_import("m", &["spec"])-            )-        );--        assert_eq!(-            transform_module_syntax(-                "import { x } from \"m\";\nfunction f(x) { return x; }\nx;".into()-            )-            .code,-            format!(-                "const {{ x: x }} = await {};\nfunction f(x) {{ return x; }}\nx;",-                validated_import("m", &["x"])-            )-        );--        assert_eq!(-            transform_module_syntax("import { x } from \"m\";\n{ const x = 1; x; }\nx;".into())-                .code,-            format!(-                "const {{ x: x }} = await {};\n{{ const x = 1; x; }}\nx;",-                validated_import("m", &["x"])-            )-        );--        assert_eq!(-            transform_module_syntax("import { x } from \"m\";\ntry {} catch (x) { x; }\nx;".into())-                .code,-            format!(-                "const {{ x: x }} = await {};\ntry {{}} catch (x) {{ x; }}\nx;",-                validated_import("m", &["x"])-            )-        );--        assert_eq!(-            transform_module_syntax(-                "import { x } from \"m\";\nfunction f(){ if (ok) { var x = 1; } return x; }\nx;"-                    .into()-            )-            .code,-            format!(-                "const {{ x: x }} = await {};\nfunction f(){{ if (ok) {{ var x = 1; }} return x; \-                 }}\nx;",-                validated_import("m", &["x"])-            )-        );--        assert_eq!(-            transform_module_syntax("import { readFile } from \"node:fs\";\nreadFile = 1;".into())-                .code,-            format!(-                "const {{ readFile: readFile }} = await {};\nreadFile = 1;",-                validated_import("node:fs", &["readFile"])-            )-        );--        assert_eq!(-            transform_module_syntax(-                "import { readFile } from \"node:fs\";\n({ readFile } = obj);".into()-            )-            .code,-            format!(-                "const {{ readFile: readFile }} = await {};\n({{ readFile }} = obj);",-                validated_import("node:fs", &["readFile"])-            )-        );--        assert_eq!(-            transform_module_syntax("import { readFile } from \"node:fs\";\nreadFile++;".into())-                .code,-            format!(-                "const {{ readFile: readFile }} = await {};\nreadFile++;",-                validated_import("node:fs", &["readFile"])-            )-        );-    }--    #[test]-    fn transform_dynamic_import_and_noops() {-        assert_eq!(-            transform_module_syntax("const mod = import(\"node:fs\");".into()).code,-            "const mod = __nodeREPLDynamicImport(\"node:fs\");"-        );--        let no_module_syntax = transform_module_syntax("const importName = \"import\";".into());-        assert!(!no_module_syntax.had_module_syntax);-        assert_eq!(no_module_syntax.code, "const importName = \"import\";");--        let incomplete = transform_module_syntax("import {".into());-        assert!(!incomplete.had_module_syntax);-        assert_eq!(incomplete.code, "import {");--        let import_meta = transform_module_syntax("console.log(import.meta.url);".into());-        assert!(import_meta.had_module_syntax);-        assert!(import_meta-            .code-            .contains("Cannot use import.meta outside a module"));-    }--    #[test]-    fn transform_preserves_statement_boundaries() {-        let hashbang = transform_module_syntax(-            "#!/usr/bin/env node\nimport fs from \"node:fs\";\nfs.readFile;".into(),-        )-        .code;-        assert!(hashbang.starts_with("#!/usr/bin/env node\nconst { default: fs } = await "));-        assert!(hashbang.contains("\nfs.readFile;"));--        assert_eq!(-            transform_module_syntax("foo()\nimport \"x\";\n[1].forEach(bar)".into()).code,-            "await __nodeREPLDynamicImport(\"x\");\nfoo()\n;\n[1].forEach(bar)"-        );-    }--    #[test]-    fn transform_typescript_module_syntax() {-        assert_eq!(-            transform_module_syntax("import fs from \"node:fs\";\nconst x: number = 1;".into())-                .code,-            format!(-                "const {{ default: fs }} = await {};\nconst x: number = 1;",-                validated_import("node:fs", &["default"])-            )-        );--        let type_only = transform_module_syntax(-            "import type { Foo } from \"types\";\nexport type { Foo };\nconst x: number = 1;"-                .into(),-        );-        assert!(type_only.had_module_syntax);-        assert!(!type_only.code.contains("__nodeREPLDynamicImport"));-        assert!(!type_only.code.contains("import type"));-        assert!(!type_only.code.contains("export type"));--        let re_export_type =-            transform_module_syntax("export { type Foo } from \"types\";\nconst x = 1;".into());-        assert!(!re_export_type.code.contains("__nodeREPLDynamicImport"));-        assert_eq!(re_export_type.code, "\nconst x = 1;");--        let import_equals =-            transform_module_syntax("import type Foo = require(\"foo\");\nconst x = 1;".into());-        assert!(import_equals.had_module_syntax);-        assert_eq!(import_equals.code, "\nconst x = 1;");--        let namespace_export =-            transform_module_syntax("export as namespace Foo;\nconst x = 1;".into());-        assert!(namespace_export.had_module_syntax);-        assert_eq!(namespace_export.code, "\nconst x = 1;");-    }--    #[test]-    fn first_expression_from_error_column() {-        assert_eq!(-            get_first_expression("assert(value)".into(), 6),-            "assert(value)"-        );-        assert_eq!(get_first_expression("ok(value)".into(), 3), "ok(value)");-        assert_eq!(-            get_first_expression("assert.ok(value)".into(), 9),-            "assert.ok(value)"-        );-        assert_eq!(-            get_first_expression("assert['ok'](value)".into(), 12),-            "assert['ok'](value)"-        );-        assert_eq!(-            get_first_expression("assert[method + suffix](value)".into(), 23),-            "assert[method + suffix](value)"-        );-        assert_eq!(-            get_first_expression("assert.deepEqual(foo(), 1)".into(), 17),-            "assert.deepEqual(foo(), 1)"-        );-        assert_eq!(-            get_first_expression("assert?.ok(value)".into(), 10),-            "assert?.ok(value)"-        );-        assert_eq!(-            get_first_expression("a(); assert.ok(value); b()".into(), 13),-            "assert.ok(value)"-        );-        assert_eq!(-            get_first_expression("const 🍣 = 1; assert.ok(🍣)".into(), 23),-            "assert.ok(🍣)"-        );-    }--    #[test]-    fn valid_syntax_checks() {-        assert!(is_valid_syntax("await foo".into()));-        assert!(is_valid_syntax("{ value: 1 }".into()));-        assert!(is_valid_syntax("foo + bar".into()));-        assert!(is_valid_syntax("const x: number = 1".into()));-        assert!(!is_valid_syntax("function foo(".into()));-    }--    #[test]-    fn recoverable_syntax_checks() {-        assert!(is_recoverable_error("function foo() {".into()));-        assert!(is_recoverable_error("{".into()));-        assert!(is_recoverable_error("`template".into()));-        assert!(is_recoverable_error("/* comment".into()));-        assert!(is_recoverable_error("\"continued\\\n".into()));-        assert!(!is_recoverable_error("const x: number = 1".into()));-        assert!(!is_recoverable_error("{ value: 1 }".into()));-        assert!(!is_recoverable_error("{}".into()));-        assert!(!is_recoverable_error("2e".into()));-        assert!(!is_recoverable_error("\"unterminated".into()));-    }-}

deps/swc/bindings/binding_react_compiler_node/Cargo.toml

deleted file mode 100644@@ -1,34 +0,0 @@-[package]-authors = ["강동윤 <kdy1997.dev@gmail.com>"]-build   = "build.rs"-edition = "2021"-exclude = ["artifacts.json", "index.node"]-license = "Apache-2.0"-name    = "binding_react_compiler_node"-publish = false-version = "0.2.0"--[lib]-bench      = false-crate-type = ["cdylib"]--[build-dependencies]-napi-build = { workspace = true }--[dependencies]-backtrace     = { workspace = true }-napi          = { workspace = true, features = ["napi3", "serde-json"] }-napi-derive   = { workspace = true, features = ["type-def"] }-serde         = { workspace = true, features = ["derive"] }-serde_json    = { workspace = true }-tracing       = { workspace = true, features = ["release_max_level_info"] }---swc_core = { path = "../../crates/swc_core", features = [-  "allocator_node",-  "common_sourcemap",-  "ecma_ast",-  "ecma_parser",-] }-swc_ecma_react_compiler = { path = "../../crates/swc_ecma_react_compiler" }-swc_malloc = { path = "../../crates/swc_malloc" }

deps/swc/bindings/binding_react_compiler_node/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.\ No newline at end of file

deps/swc/bindings/binding_react_compiler_node/build.rs

deleted file mode 100644@@ -1,23 +0,0 @@-use std::{-    env,-    fs::File,-    io::{BufWriter, Write},-    path::Path,-};--extern crate napi_build;--fn main() {-    let out_dir = env::var("OUT_DIR").expect("Outdir should exist");-    let dest_path = Path::new(&out_dir).join("triple.txt");-    let mut f =-        BufWriter::new(File::create(dest_path).expect("Failed to create target triple text"));-    write!(-        f,-        "{}",-        env::var("TARGET").expect("Target should be specified")-    )-    .expect("Failed to write target triple text");--    napi_build::setup();-}

deps/swc/bindings/binding_react_compiler_node/src/diagnostics.rs

deleted file mode 100644@@ -1,281 +0,0 @@-use swc_ecma_react_compiler::diagnostics::{-    DiagnosticDetail as CoreDiagnosticDetail, DiagnosticLocation as CoreDiagnosticLocation,-    DiagnosticMessage, DiagnosticPosition as CoreDiagnosticPosition, Severity,-};--// `#[napi]` resolves via the crate-wide `#[macro_use] extern crate-// napi_derive;` in `lib.rs` — matches the convention already used in-// `support.rs`.-#[napi(object)]-#[derive(Debug, Clone)]-pub struct Diagnostic {-    pub severity: String,-    pub message: String,-    #[napi(js_name = "ruleId")]-    pub rule_id: Option<String>,-    pub category: Option<String>,-    pub reason: Option<String>,-    pub description: Option<String>,-    pub loc: Option<DiagnosticLocation>,-    pub details: Vec<DiagnosticDetail>,-}--#[napi(object)]-#[derive(Debug, Clone)]-pub struct DiagnosticLocation {-    pub start: DiagnosticPosition,-    pub end: DiagnosticPosition,-    pub filename: Option<String>,-    #[napi(js_name = "identifierName")]-    pub identifier_name: Option<String>,-}--#[napi(object)]-#[derive(Debug, Clone)]-pub struct DiagnosticPosition {-    pub line: u32,-    pub column: u32,-    pub index: Option<u32>,-}--#[napi(object)]-#[derive(Debug, Clone)]-pub struct DiagnosticDetail {-    pub kind: String,-    pub loc: Option<DiagnosticLocation>,-    pub message: Option<String>,-}--/// Converts a lint result's diagnostics into their napi-facing shape.-///-/// `source_text` is the same source that was linted — needed to convert-/// `CoreDiagnosticPosition`'s byte-based `column`/`index` into the UTF-16-/// code-unit-based positions JS/ESLint consumers expect. See-/// [`diagnostic_position_from`] for why this conversion can't happen-/// upstream in `swc_ecma_react_compiler` itself.-pub fn diagnostic_from_message(source_text: &str, value: &DiagnosticMessage) -> Diagnostic {-    Diagnostic {-        severity: match value.severity {-            Severity::Error => "error".to_string(),-            Severity::Warning => "warning".to_string(),-        },-        message: value.message.clone(),-        rule_id: value.rule_id.clone(),-        category: value.category.clone(),-        reason: value.reason.clone(),-        description: value.description.clone(),-        loc: value-            .loc-            .as_ref()-            .map(|loc| diagnostic_location_from(source_text, loc)),-        details: value-            .details-            .iter()-            .map(|detail| diagnostic_detail_from(source_text, detail))-            .collect(),-    }-}--fn diagnostic_location_from(-    source_text: &str,-    value: &CoreDiagnosticLocation,-) -> DiagnosticLocation {-    DiagnosticLocation {-        start: diagnostic_position_from(source_text, &value.start),-        end: diagnostic_position_from(source_text, &value.end),-        filename: value.filename.clone(),-        identifier_name: value.identifier_name.clone(),-    }-}--/// Converts a byte-offset-based position into a UTF-16 code-unit-based one.-///-/// `swc_ecma_react_compiler`'s `DiagnosticPosition` (and the upstream-/// `Position` it's built from) is deliberately byte-based: it also feeds-/// `DiagnosticMessage.span`, which `@swc/core`'s existing react-compiler-/// transform-error path turns into a real `swc_common::Span`/`BytePos` for-/// terminal error rendering — that consumer genuinely needs byte offsets.-/// This napi package's `lint`/`lintSync` are a different consumer exposing-/// positions to JS/ESLint, whose string indexing is UTF-16-based. Rather-/// than changing the shared byte-based representation (and breaking the-/// unrelated transform-error consumer for any non-ASCII source), the-/// conversion happens here, at this package's own boundary.-///-/// For ASCII-only source text this is a no-op (byte count == UTF-16 code-/// unit count for ASCII); they diverge for any non-ASCII character-/// appearing before the position being converted.-fn diagnostic_position_from(-    source_text: &str,-    value: &CoreDiagnosticPosition,-) -> DiagnosticPosition {-    let line_text = source_text-        .split('\n')-        .nth(value.line.saturating_sub(1) as usize)-        .unwrap_or_default();-    let byte_column = value.column as usize;-    let column = line_text-        .get(..byte_column)-        .unwrap_or(line_text)-        .encode_utf16()-        .count() as u32;--    let index = value.index.map(|byte_index| {-        source_text-            .get(..byte_index as usize)-            .unwrap_or(source_text)-            .encode_utf16()-            .count() as u32-    });--    DiagnosticPosition {-        line: value.line,-        column,-        index,-    }-}--fn diagnostic_detail_from(source_text: &str, value: &CoreDiagnosticDetail) -> DiagnosticDetail {-    DiagnosticDetail {-        kind: value.kind.clone(),-        loc: value-            .loc-            .as_ref()-            .map(|loc| diagnostic_location_from(source_text, loc)),-        message: value.message.clone(),-    }-}--#[cfg(test)]-mod tests {-    use swc_ecma_react_compiler::diagnostics::{-        DiagnosticDetail as CoreDiagnosticDetail, DiagnosticLocation as CoreDiagnosticLocation,-        DiagnosticMessage, DiagnosticPosition as CoreDiagnosticPosition, Severity,-    };--    use super::diagnostic_from_message;--    // Line 3 (1-indexed) is `👋 const value = 1;` — a 4-byte emoji followed-    // by a space, so byte offsets and UTF-16 offsets diverge from column 0-    // onward on this line, and `index` (absolute, from file start) diverges-    // for every position after it.-    const SOURCE: &str = "line one\nline two\n👋 const value = 1;\n";--    fn sample_message() -> DiagnosticMessage {-        DiagnosticMessage {-            severity: Severity::Error,-            message: "[ReactCompiler] Refs: invalid ref access".into(),-            span: Some((1, 2)),-            rule_id: Some("refs".into()),-            category: Some("Refs".into()),-            reason: Some("invalid ref access".into()),-            description: Some("description".into()),-            // All of these are the BYTE-based values `swc_ecma_react_compiler`-            // would actually produce (what `diagnostic_from_message` takes as-            // input) — `value` on line 3 starts after "👋 const ", which is-            // 4 (the emoji, a 4-byte UTF-8 sequence) + 1 (space) + 6-            // ("const ") = 11 bytes. Lines 1-2 ("line one"/"line two") plus-            // their newlines are 8 + 1 + 8 + 1 = 18 bytes, so `value`'s-            // absolute byte index is 18 + 11 = 29.-            loc: Some(CoreDiagnosticLocation {-                start: CoreDiagnosticPosition {-                    line: 3,-                    column: 11,-                    index: Some(29),-                },-                end: CoreDiagnosticPosition {-                    line: 3,-                    column: 16, // 11 + "value".len()-                    index: Some(34),-                },-                filename: Some("input.tsx".into()),-                identifier_name: Some("value".into()),-            }),-            details: vec![CoreDiagnosticDetail {-                kind: "error".into(),-                loc: None,-                message: Some("detail".into()),-            }],-        }-    }--    #[test]-    fn converts_diagnostic_message_to_napi_shape() {-        let diagnostic = diagnostic_from_message(SOURCE, &sample_message());--        assert_eq!(diagnostic.severity, "error");-        assert_eq!(-            diagnostic.message,-            "[ReactCompiler] Refs: invalid ref access"-        );-        assert_eq!(diagnostic.rule_id.as_deref(), Some("refs"));-        assert_eq!(diagnostic.category.as_deref(), Some("Refs"));--        let loc = diagnostic.loc.expect("expected loc");-        assert_eq!(loc.start.line, 3);-        assert_eq!(loc.identifier_name.as_deref(), Some("value"));--        assert_eq!(diagnostic.details.len(), 1);-        assert_eq!(diagnostic.details[0].kind, "error");-    }--    #[test]-    fn converts_warning_severity() {-        let mut message = sample_message();-        message.severity = Severity::Warning;--        let diagnostic = diagnostic_from_message(SOURCE, &message);--        assert_eq!(diagnostic.severity, "warning");-    }--    #[test]-    fn converts_byte_offsets_to_utf16_code_units_across_non_ascii_text() {-        let diagnostic = diagnostic_from_message(SOURCE, &sample_message());-        let loc = diagnostic.loc.expect("expected loc");--        // Byte column (11) counts the 4-byte emoji as 4 bytes; UTF-16 column-        // counts it as 2 code units ('👋' is outside the BMP, so it's a-        // surrogate pair): "👋"(2) + " "(1) + "const "(6) = 9.-        assert_eq!(loc.start.column, 9);-        assert_eq!(loc.end.column, 9 + 5); // + "value".len()--        // Same divergence propagated into the absolute `index`. Lines 1-2-        // and their newlines are ASCII, so their UTF-16 length equals their-        // byte length (18); only line 3's emoji prefix diverges (9 UTF-16-        // units vs. 11 bytes), giving 18 + 9 = 27 instead of the byte-based-        // 29.-        assert_eq!(loc.start.index, Some(18 + 9));-        assert_eq!(loc.end.index, Some(18 + 9 + 5));-    }--    #[test]-    fn ascii_only_source_leaves_positions_unchanged() {-        let source = "line one\nfunction App() {\n    const value = 1;\n}\n";-        let message = DiagnosticMessage {-            loc: Some(CoreDiagnosticLocation {-                start: CoreDiagnosticPosition {-                    line: 3,-                    column: 10,-                    index: Some(9 + 17 + 10),-                },-                end: CoreDiagnosticPosition {-                    line: 3,-                    column: 15,-                    index: Some(9 + 17 + 15),-                },-                filename: None,-                identifier_name: None,-            }),-            ..sample_message()-        };--        let diagnostic = diagnostic_from_message(source, &message);-        let loc = diagnostic.loc.expect("expected loc");--        // For ASCII-only source, byte offsets and UTF-16 offsets coincide.-        assert_eq!(loc.start.column, 10);-        assert_eq!(loc.start.index, Some(9 + 17 + 10));-        assert_eq!(loc.end.column, 15);-        assert_eq!(loc.end.index, Some(9 + 17 + 15));-    }-}

deps/swc/bindings/binding_react_compiler_node/src/lib.rs

deleted file mode 100644@@ -1,25 +0,0 @@-#![recursion_limit = "2048"]-#![allow(dead_code)]--#[macro_use]-extern crate napi_derive;--extern crate swc_malloc;--use std::{env, panic::set_hook};--use backtrace::Backtrace;--mod diagnostics;-mod lint;-mod support;--#[napi_derive::module_init]-fn init() {-    if cfg!(debug_assertions) || env::var("SWC_DEBUG").unwrap_or_default() == "1" {-        set_hook(Box::new(|panic_info| {-            let backtrace = Backtrace::new();-            println!("Panic: {panic_info:?}\nBacktrace: {backtrace:?}");-        }));-    }-}

deps/swc/bindings/binding_react_compiler_node/src/lint.rs

deleted file mode 100644@@ -1,257 +0,0 @@-use napi::bindgen_prelude::*;-use swc_core::ecma::parser::Syntax;--use crate::diagnostics::{diagnostic_from_message, Diagnostic};--/// Matches `swc_ecma_parser::Syntax`'s own `Default` impl-/// (`Es(EsSyntax::default())` — plain ECMAScript, no JSX/TSX/decorators) rather-/// than any particular consumer's build settings. This package is-/// general-purpose; it must not silently assume one caller's parser-/// configuration for everyone else.-fn default_syntax() -> Syntax {-    Syntax::default()-}--/// Pure JSON decode, no napi types involved — this is the only part of-/// syntax parsing that unit tests may call directly. A `napi::Error` has a-/// non-trivial `Drop`/`ToNapiValue` impl that references live N-API C-/// functions (`napi_throw`, `napi_create_error`, ...), which only exist once-/// this cdylib is `dlopen`'d by a running Node process. If ANY function that-/// tests call constructs a `napi::Error` anywhere in its body — even in a-/// branch that specific test never executes — the whole function's compiled-/// object code references those unresolved symbols, and a standalone-/// `cargo test` binary (never loaded by Node) fails to link. Keep this-/// function's signature free of `napi::Error`/`napi::Result` so tests can-/// call it safely.-fn decode_syntax(bytes: &[u8]) -> std::result::Result<Syntax, serde_json::Error> {-    serde_json::from_slice(bytes)-}--/// Thin napi-facing wrapper — not unit tested (see `decode_syntax`'s doc-/// comment), matching this crate's existing convention of only testing the-/// pure logic behind a `#[napi]` function, never the function itself (see-/// `support.rs`'s `is_react_compiler_required(_sync)`, which have no tests-/// at all).-fn parse_syntax_option(syntax: Option<Buffer>) -> napi::Result<Syntax> {-    match syntax {-        Some(buf) => decode_syntax(buf.as_ref()).map_err(|err| {-            napi::Error::new(napi::Status::InvalidArg, format!("invalid `syntax`: {err}"))-        }),-        None => Ok(default_syntax()),-    }-}--fn lint_inner(code: &str, syntax: Syntax) -> Vec<Diagnostic> {-    let result = swc_ecma_react_compiler::lint_source(-        code,-        syntax,-        swc_ecma_react_compiler::default_plugin_options(),-    );--    result-        .diagnostics-        .iter()-        .map(|d| diagnostic_from_message(code, d))-        .collect()-}--struct LintTask {-    code: String,-    syntax: Syntax,-}--#[napi]-impl Task for LintTask {-    type JsValue = Vec<Diagnostic>;-    type Output = Vec<Diagnostic>;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        Ok(lint_inner(&self.code, self.syntax))-    }--    fn resolve(&mut self, _env: napi::Env, output: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(output)-    }-}--#[napi]-fn lint(-    code: String,-    syntax: Option<Buffer>,-    signal: Option<AbortSignal>,-) -> napi::Result<AsyncTask<LintTask>> {-    let syntax = parse_syntax_option(syntax)?;--    Ok(AsyncTask::with_optional_signal(-        LintTask { code, syntax },-        signal,-    ))-}--#[napi]-pub fn lint_sync(code: String, syntax: Option<Buffer>) -> napi::Result<Vec<Diagnostic>> {-    let syntax = parse_syntax_option(syntax)?;--    Ok(lint_inner(&code, syntax))-}--#[cfg(test)]-mod tests {-    use swc_core::ecma::parser::{EsSyntax, Syntax, TsSyntax};--    use super::{decode_syntax, default_syntax, lint_inner};--    /// Several documented React Compiler lint rules-    /// (https://react.dev/reference/eslint-plugin-react-hooks) only surface-    /// on JSX-bearing source, which `default_syntax()` (plain ECMAScript, no-    /// JSX) can't parse. Tests exercising those rules use this instead.-    fn tsx_syntax() -> Syntax {-        Syntax::Typescript(TsSyntax {-            tsx: true,-            decorators: true,-            ..Default::default()-        })-    }--    #[test]-    fn reports_ref_access_error_with_default_syntax() {-        let source = r#"-            import { useRef } from 'react';--            function App() {-                const ref = useRef(1);-                return ref.current;-            }-        "#;--        let diagnostics = lint_inner(source, default_syntax());--        assert_eq!(diagnostics.len(), 1);-        assert_eq!(diagnostics[0].severity, "error");-        assert_eq!(diagnostics[0].rule_id.as_deref(), Some("refs"));-        assert_eq!(diagnostics[0].category.as_deref(), Some("Refs"));-    }--    #[test]-    fn returns_empty_for_non_react_code() {-        let diagnostics = lint_inner("const x = 1;", default_syntax());--        assert!(diagnostics.is_empty());-    }--    /// One test per documented React Compiler lint rule-    /// (https://react.dev/reference/eslint-plugin-react-hooks) that a-    /// hand-written source snippet can reliably trigger. Every trigger-    /// condition here was verified empirically against the actual compiled-    /// binary before being written as a test — not guessed. Rules not-    /// covered below either require configuration this crate deliberately-    /// doesn't expose (`config`, `gating`: need explicit gating directives;-    /// `purity`: `validate_no_impure_functions_in_render` defaults to-    /// `false` upstream) or need more investigation to find a reliable-    /// trigger (`error-boundaries`, `static-components`,-    /// `set-state-in-effect`, `incompatible-library`).-    mod documented_rule_coverage {-        use super::{lint_inner, tsx_syntax};--        fn assert_fires(source: &str, expected_rule_id: &str) {-            let diagnostics = lint_inner(source, tsx_syntax());--            assert!(-                diagnostics-                    .iter()-                    .any(|d| d.rule_id.as_deref() == Some(expected_rule_id)),-                "expected a `{expected_rule_id}` diagnostic, got: {diagnostics:#?}"-            );-        }--        #[test]-        fn globals() {-            assert_fires(-                r#"-                let count = 0;-                function App() {-                    const [x] = useState(0);-                    count = count + 1;-                    return <div>{count}{x}</div>;-                }-                "#,-                "globals",-            );-        }--        #[test]-        fn immutability() {-            assert_fires(-                r#"-                function App(props) {-                    const [x, setX] = useState(0);-                    props.value = 1;-                    return <div onClick={() => setX(x + 1)}>{x}</div>;-                }-                "#,-                "immutability",-            );-        }--        #[test]-        fn use_memo() {-            assert_fires(-                r#"-                function App() {-                    const value = useMemo((extra) => extra, [1]);-                    return <div>{value}</div>;-                }-                "#,-                "use-memo",-            );-        }--        #[test]-        fn set_state_in_render() {-            assert_fires(-                r#"-                function App() {-                    const [state, setState] = useState(0);-                    setState(state + 1);-                    return <div>{state}</div>;-                }-                "#,-                "set-state-in-render",-            );-        }--        #[test]-        fn unsupported_syntax() {-            assert_fires(-                r#"-                function App() {-                    eval('1');-                    return <div />;-                }-                "#,-                "unsupported-syntax",-            );-        }-    }--    #[test]-    fn decode_syntax_decodes_ecmascript_json() {-        let syntax = decode_syntax(br#"{"syntax":"ecmascript","jsx":true}"#)-            .expect("valid ecmascript syntax JSON should decode");--        assert_eq!(-            syntax,-            Syntax::Es(EsSyntax {-                jsx: true,-                ..Default::default()-            })-        );-    }--    #[test]-    fn decode_syntax_rejects_invalid_json() {-        let result = decode_syntax(b"not json");--        assert!(result.is_err());-    }-}

deps/swc/bindings/binding_react_compiler_node/src/support.rs

deleted file mode 100644@@ -1,104 +0,0 @@-use napi::bindgen_prelude::*;-use swc_core::{-    common::{sync::Lrc, FileName, SourceMap},-    ecma::{ast::EsVersion, parser::Syntax},-};--struct IsReactCompilerRequiredTask {-    code: String,-}--#[napi]-impl Task for IsReactCompilerRequiredTask {-    type JsValue = bool;-    type Output = bool;--    fn compute(&mut self) -> napi::Result<Self::Output> {-        Ok(is_react_compiler_required_inner(&self.code))-    }--    fn resolve(&mut self, _env: napi::Env, output: Self::Output) -> napi::Result<Self::JsValue> {-        Ok(output)-    }-}--fn is_react_compiler_required_inner(code: &str) -> bool {-    let cm = Lrc::new(SourceMap::default());-    let fm = cm.new_source_file(FileName::Anon.into(), code.to_string());--    let mut recovered_errors = Vec::new();-    let program = swc_core::ecma::parser::parse_file_as_program(-        &fm,-        Syntax::Typescript(swc_core::ecma::parser::TsSyntax {-            decorators: true,-            tsx: true,-            ..Default::default()-        }),-        EsVersion::latest(),-        None,-        &mut recovered_errors,-    );--    let Ok(program) = program else {-        return true;-    };--    if !recovered_errors.is_empty() {-        return true;-    }--    swc_ecma_react_compiler::fast_check::is_required(&program)-}--#[napi]-fn is_react_compiler_required(-    code: Buffer,-    signal: Option<AbortSignal>,-) -> AsyncTask<IsReactCompilerRequiredTask> {-    let code = String::from_utf8_lossy(code.as_ref()).into_owned();--    let task = IsReactCompilerRequiredTask { code };--    AsyncTask::with_optional_signal(task, signal)-}--#[napi]-pub fn is_react_compiler_required_sync(code: Buffer) -> napi::Result<bool> {-    let code = String::from_utf8_lossy(code.as_ref()).into_owned();--    Ok(is_react_compiler_required_inner(&code))-}--#[cfg(test)]-mod tests {-    use super::*;--    #[test]-    fn recovered_parse_errors_are_conservative() {-        let code = "return 1;";-        let cm = Lrc::new(SourceMap::default());-        let fm = cm.new_source_file(FileName::Anon.into(), code.to_string());-        let mut recovered_errors = Vec::new();-        let program = swc_core::ecma::parser::parse_file_as_program(-            &fm,-            Syntax::Typescript(swc_core::ecma::parser::TsSyntax {-                decorators: true,-                tsx: true,-                ..Default::default()-            }),-            EsVersion::latest(),-            None,-            &mut recovered_errors,-        );--        assert!(-            program.is_ok(),-            "the regression requires a recovered rather than fatal parse error"-        );-        assert!(-            !recovered_errors.is_empty(),-            "the regression requires at least one recovered parse error"-        );-        assert!(is_react_compiler_required_inner(code));-    }-}

deps/swc/bindings/binding_typescript_wasm/.cargo/config.toml

deleted file mode 100644@@ -1,3 +0,0 @@-[target.wasm32-unknown-unknown]-# support more stack size due to issue: https://github.com/swc-project/swc/issues/10207-rustflags = ["-C", "link-args=-z stack-size=2097152"]

deps/swc/bindings/binding_typescript_wasm/Cargo.toml

deleted file mode 100644@@ -1,36 +0,0 @@-[package]-authors     = ["강동윤 <kdy1997.dev@gmail.com>"]-description = "wasm module for swc"-edition     = { workspace = true }-license     = { workspace = true }-name        = "binding_typescript_wasm"-publish     = false-repository  = { workspace = true }-version     = "1.16.18"--[lib]-bench      = false-crate-type = ["cdylib"]--[features]-nightly = ["swc_ts_fast_strip/nightly"]--[dependencies]-anyhow = { workspace = true }-js-sys = { workspace = true }-miette = { workspace = true }-owo-colors = { workspace = true }-serde = { workspace = true, features = ["derive"] }-serde-wasm-bindgen = { workspace = true }-swc_common = { path = "../../crates/swc_common" }-swc_error_reporters = { path = "../../crates/swc_error_reporters" }-swc_ts_fast_strip = { path = "../../crates/swc_ts_fast_strip", features = [-  "wasm-bindgen",-] }-tracing = { workspace = true, features = ["max_level_off"] }-unicode-width = { workspace = true }-wasm-bindgen = { workspace = true, features = ["enable-interning"] }-wasm-bindgen-futures = { workspace = true }--[package.metadata.wasm-pack.profile.release]-wasm-opt = false

deps/swc/bindings/binding_typescript_wasm/LICENSE

deleted file mode 100644@@ -1,201 +0,0 @@-                              Apache License-                        Version 2.0, January 2004-                     http://www.apache.org/licenses/--TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION--1. Definitions.--   "License" shall mean the terms and conditions for use, reproduction,-   and distribution as defined by Sections 1 through 9 of this document.--   "Licensor" shall mean the copyright owner or entity authorized by-   the copyright owner that is granting the License.--   "Legal Entity" shall mean the union of the acting entity and all-   other entities that control, are controlled by, or are under common-   control with that entity. For the purposes of this definition,-   "control" means (i) the power, direct or indirect, to cause the-   direction or management of such entity, whether by contract or-   otherwise, or (ii) ownership of fifty percent (50%) or more of the-   outstanding shares, or (iii) beneficial ownership of such entity.--   "You" (or "Your") shall mean an individual or Legal Entity-   exercising permissions granted by this License.--   "Source" form shall mean the preferred form for making modifications,-   including but not limited to software source code, documentation-   source, and configuration files.--   "Object" form shall mean any form resulting from mechanical-   transformation or translation of a Source form, including but-   not limited to compiled object code, generated documentation,-   and conversions to other media types.--   "Work" shall mean the work of authorship, whether in Source or-   Object form, made available under the License, as indicated by a-   copyright notice that is included in or attached to the work-   (an example is provided in the Appendix below).--   "Derivative Works" shall mean any work, whether in Source or Object-   form, that is based on (or derived from) the Work and for which the-   editorial revisions, annotations, elaborations, or other modifications-   represent, as a whole, an original work of authorship. For the purposes-   of this License, Derivative Works shall not include works that remain-   separable from, or merely link (or bind by name) to the interfaces of,-   the Work and Derivative Works thereof.--   "Contribution" shall mean any work of authorship, including-   the original version of the Work and any modifications or additions-   to that Work or Derivative Works thereof, that is intentionally-   submitted to Licensor for inclusion in the Work by the copyright owner-   or by an individual or Legal Entity authorized to submit on behalf of-   the copyright owner. For the purposes of this definition, "submitted"-   means any form of electronic, verbal, or written communication sent-   to the Licensor or its representatives, including but not limited to-   communication on electronic mailing lists, source code control systems,-   and issue tracking systems that are managed by, or on behalf of, the-   Licensor for the purpose of discussing and improving the Work, but-   excluding communication that is conspicuously marked or otherwise-   designated in writing by the copyright owner as "Not a Contribution."--   "Contributor" shall mean Licensor and any individual or Legal Entity-   on behalf of whom a Contribution has been received by Licensor and-   subsequently incorporated within the Work.--2. Grant of Copyright License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   copyright license to reproduce, prepare Derivative Works of,-   publicly display, publicly perform, sublicense, and distribute the-   Work and such Derivative Works in Source or Object form.--3. Grant of Patent License. Subject to the terms and conditions of-   this License, each Contributor hereby grants to You a perpetual,-   worldwide, non-exclusive, no-charge, royalty-free, irrevocable-   (except as stated in this section) patent license to make, have made,-   use, offer to sell, sell, import, and otherwise transfer the Work,-   where such license applies only to those patent claims licensable-   by such Contributor that are necessarily infringed by their-   Contribution(s) alone or by combination of their Contribution(s)-   with the Work to which such Contribution(s) was submitted. If You-   institute patent litigation against any entity (including a-   cross-claim or counterclaim in a lawsuit) alleging that the Work-   or a Contribution incorporated within the Work constitutes direct-   or contributory patent infringement, then any patent licenses-   granted to You under this License for that Work shall terminate-   as of the date such litigation is filed.--4. Redistribution. You may reproduce and distribute copies of the-   Work or Derivative Works thereof in any medium, with or without-   modifications, and in Source or Object form, provided that You-   meet the following conditions:--   (a) You must give any other recipients of the Work or-       Derivative Works a copy of this License; and--   (b) You must cause any modified files to carry prominent notices-       stating that You changed the files; and--   (c) You must retain, in the Source form of any Derivative Works-       that You distribute, all copyright, patent, trademark, and-       attribution notices from the Source form of the Work,-       excluding those notices that do not pertain to any part of-       the Derivative Works; and--   (d) If the Work includes a "NOTICE" text file as part of its-       distribution, then any Derivative Works that You distribute must-       include a readable copy of the attribution notices contained-       within such NOTICE file, excluding those notices that do not-       pertain to any part of the Derivative Works, in at least one-       of the following places: within a NOTICE text file distributed-       as part of the Derivative Works; within the Source form or-       documentation, if provided along with the Derivative Works; or,-       within a display generated by the Derivative Works, if and-       wherever such third-party notices normally appear. The contents-       of the NOTICE file are for informational purposes only and-       do not modify the License. You may add Your own attribution-       notices within Derivative Works that You distribute, alongside-       or as an addendum to the NOTICE text from the Work, provided-       that such additional attribution notices cannot be construed-       as modifying the License.--   You may add Your own copyright statement to Your modifications and-   may provide additional or different license terms and conditions-   for use, reproduction, or distribution of Your modifications, or-   for any such Derivative Works as a whole, provided Your use,-   reproduction, and distribution of the Work otherwise complies with-   the conditions stated in this License.--5. Submission of Contributions. Unless You explicitly state otherwise,-   any Contribution intentionally submitted for inclusion in the Work-   by You to the Licensor shall be under the terms and conditions of-   this License, without any additional terms or conditions.-   Notwithstanding the above, nothing herein shall supersede or modify-   the terms of any separate license agreement you may have executed-   with Licensor regarding such Contributions.--6. Trademarks. This License does not grant permission to use the trade-   names, trademarks, service marks, or product names of the Licensor,-   except as required for reasonable and customary use in describing the-   origin of the Work and reproducing the content of the NOTICE file.--7. Disclaimer of Warranty. Unless required by applicable law or-   agreed to in writing, Licensor provides the Work (and each-   Contributor provides its Contributions) on an "AS IS" BASIS,-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or-   implied, including, without limitation, any warranties or conditions-   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A-   PARTICULAR PURPOSE. You are solely responsible for determining the-   appropriateness of using or redistributing the Work and assume any-   risks associated with Your exercise of permissions under this License.--8. Limitation of Liability. In no event and under no legal theory,-   whether in tort (including negligence), contract, or otherwise,-   unless required by applicable law (such as deliberate and grossly-   negligent acts) or agreed to in writing, shall any Contributor be-   liable to You for damages, including any direct, indirect, special,-   incidental, or consequential damages of any character arising as a-   result of this License or out of the use or inability to use the-   Work (including but not limited to damages for loss of goodwill,-   work stoppage, computer failure or malfunction, or any and all-   other commercial damages or losses), even if such Contributor-   has been advised of the possibility of such damages.--9. Accepting Warranty or Additional Liability. While redistributing-   the Work or Derivative Works thereof, You may choose to offer,-   and charge a fee for, acceptance of support, warranty, indemnity,-   or other liability obligations and/or rights consistent with this-   License. However, in accepting such obligations, You may act only-   on Your own behalf and on Your sole responsibility, not on behalf-   of any other Contributor, and only if You agree to indemnify,-   defend, and hold each Contributor harmless for any liability-   incurred by, or claims asserted against, such Contributor by reason-   of your accepting any such warranty or additional liability.--END OF TERMS AND CONDITIONS--APPENDIX: How to apply the Apache License to your work.--   To apply the Apache License to your work, attach the following-   boilerplate notice, with the fields enclosed by brackets "[]"-   replaced with your own identifying information. (Don't include-   the brackets!)  The text should be enclosed in the appropriate-   comment syntax for the file format. We also recommend that a-   file or class name and description of purpose be included on the-   same "printed page" as the copyright notice for easier-   identification within third-party archives.--Copyright 2024 SWC contributors.--Licensed under the Apache License, Version 2.0 (the "License");-you may not use this file except in compliance with the License.-You may obtain a copy of the License at--	http://www.apache.org/licenses/LICENSE-2.0--Unless required by applicable law or agreed to in writing, software-distributed under the License is distributed on an "AS IS" BASIS,-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-See the License for the specific language governing permissions and-limitations under the License.\ No newline at end of file

deps/swc/bindings/binding_typescript_wasm/README.md

deleted file mode 100644@@ -1,13 +0,0 @@-# @swc/wasm-typescript--This package provides a Wasm binding for the TypeScript transform.--The supported TypeScript version is currently 5.5.4, except the stage 3 decorator proposal.--## Contributing--See [the main repository](https://github.com/swc-project/swc)'s contributing guide.--## License--Apache 2.0

deps/swc/bindings/binding_typescript_wasm/package.json

deleted file mode 100644@@ -1,5 +0,0 @@-{-    "devDependencies": {-        "@rstest/core": "^0.7.8"-    }-}

deps/swc/bindings/binding_typescript_wasm/rstest.config.mjs

deleted file mode 100644@@ -1,4 +0,0 @@-export default {-    include: ["__tests__/**/*.{js,jsx,ts,tsx}"],-    globals: true,-};

deps/swc/bindings/binding_typescript_wasm/scripts/build.sh

deleted file mode 100755@@ -1,9 +0,0 @@-#!/usr/bin/env bash-set -eux--export CARGO_PROFILE_RELEASE_LTO="fat"-export CARGO_PROFILE_RELEASE_OPT_LEVEL="z"-wasm-pack build --out-name wasm --release --scope=swc --target nodejs $@-ls -al ./pkg--node ./scripts/patch.mjs

deps/swc/bindings/binding_typescript_wasm/scripts/esm.mjs

deleted file mode 100755@@ -1,15 +0,0 @@-import fs from "node:fs/promises";--const pkgJsonFile = await fs.readFile("esm/package.json", "utf8");-const pkgJson = JSON.parse(pkgJsonFile);-pkgJson.name = '@swc/wasm-typescript-esm';-pkgJson.exports = {-    types: "./wasm.d.ts",-    node: "./wasm-node.js",-    default: "./wasm.js",-};--await Promise.all([-    fs.cp("src/wasm-node.js", "esm/wasm-node.js"),-    fs.writeFile("esm/package.json", JSON.stringify(pkgJson, null, 2)),-]);

deps/swc/bindings/binding_typescript_wasm/scripts/esm.sh

deleted file mode 100755@@ -1,2 +0,0 @@-wasm-pack build --out-name wasm --out-dir esm --release --scope=swc --target web-node ./scripts/esm.mjs

deps/swc/bindings/binding_typescript_wasm/scripts/patch.mjs

deleted file mode 100755@@ -1,26 +0,0 @@-import fs from 'node:fs/promises';---const rawWasmFile = await fs.readFile('pkg/wasm_bg.wasm');-const origJsFile = await fs.readFile('pkg/wasm.js', 'utf8');--const base64 = rawWasmFile.toString('base64');--const patchedJsFile = origJsFile-    .replace(`const path = require('path').join(__dirname, 'wasm_bg.wasm');`, '')-    .replace(', fatal: true', '')-    .replace(`const bytes = require('fs').readFileSync(path);`, `-const { Buffer } = require('node:buffer');-const bytes = Buffer.from('${base64}', 'base64');`)--await fs.writeFile('pkg/wasm.js', patchedJsFile);--// Remove wasm file-await fs.unlink('pkg/wasm_bg.wasm');--// Remove wasm from .files section of package.json-const pkgJsonFile = await fs.readFile('pkg/package.json', 'utf8');-const pkgJson = JSON.parse(pkgJsonFile);-pkgJson.name = '@swc/wasm-typescript';-pkgJson.files = pkgJson.files.filter(file => file !== 'wasm_bg.wasm');-await fs.writeFile('pkg/package.json', JSON.stringify(pkgJson, null, 2));\ No newline at end of file

deps/swc/bindings/binding_typescript_wasm/scripts/test.sh

deleted file mode 100755@@ -1,9 +0,0 @@-#!/usr/bin/env bash--set -eu--./scripts/build.sh-npx rstest $@--./scripts/build.sh --features nightly-npx rstest $@\ No newline at end of file

deps/swc/bindings/binding_typescript_wasm/src/error_reporter.rs

deleted file mode 100644@@ -1,881 +0,0 @@-use std::fmt::{self};--use miette::{-    Diagnostic, GraphicalTheme, LabeledSpan, ReportHandler, SourceCode, SourceSpan, ThemeCharacters,-};-use owo_colors::{OwoColorize, Style};-use unicode_width::UnicodeWidthChar;--/**-A [`ReportHandler`] that displays a given [`Report`](crate::Report) in a-quasi-graphical way, using terminal colors, unicode drawing characters, and-other such things.--This is the default reporter bundled with `miette`.--This printer can be customized by using [`new_themed()`](GraphicalReportHandler::new_themed) and handing it a-[`GraphicalTheme`] of your own creation (or using one of its own defaults!)--See [`set_hook()`](crate::set_hook) for more details on customizing your global-printer.-*/-#[derive(Debug, Clone)]-pub struct SwcReportHandler {-    pub(crate) theme: GraphicalTheme,-    pub(crate) context_lines: usize,-    pub(crate) tab_width: usize,-}--impl SwcReportHandler {-    /// Create a new `GraphicalReportHandler` with the default-    /// [`GraphicalTheme`]. This will use both unicode characters and colors.-    pub fn new() -> Self {-        Self {-            theme: GraphicalTheme::default(),-            context_lines: 1,-            tab_width: 4,-        }-    }--    /// Set a theme for this handler.-    pub fn with_theme(mut self, theme: GraphicalTheme) -> Self {-        self.theme = theme;-        self-    }-}--impl Default for SwcReportHandler {-    fn default() -> Self {-        Self::new()-    }-}--impl SwcReportHandler {-    /// Render a [`Diagnostic`]. This function is mostly internal and meant to-    /// be called by the toplevel [`ReportHandler`] handler, but is made public-    /// to make it easier (possible) to test in isolation from global state.-    pub fn render_report(-        &self,-        f: &mut impl fmt::Write,-        diagnostic: &dyn Diagnostic,-    ) -> fmt::Result {-        self.render_report_inner(f, diagnostic, diagnostic.source_code())-    }--    fn render_report_inner(-        &self,-        f: &mut impl fmt::Write,-        diagnostic: &dyn Diagnostic,-        parent_src: Option<&dyn SourceCode>,-    ) -> fmt::Result {-        let src = diagnostic.source_code().or(parent_src);-        self.render_snippets(f, diagnostic, src)?;--        Ok(())-    }--    fn render_snippets(-        &self,-        f: &mut impl fmt::Write,-        diagnostic: &dyn Diagnostic,-        opt_source: Option<&dyn SourceCode>,-    ) -> fmt::Result {-        let source = match opt_source {-            Some(source) => source,-            None => return Ok(()),-        };-        let labels = match diagnostic.labels() {-            Some(labels) => labels,-            None => return Ok(()),-        };--        let mut labels = labels.collect::<Vec<_>>();-        labels.sort_unstable_by_key(|l| l.inner().offset());--        let mut contexts = Vec::with_capacity(labels.len());-        for right in labels.iter().cloned() {-            let right_conts =-                match source.read_span(right.inner(), self.context_lines, self.context_lines) {-                    Ok(cont) => cont,-                    Err(err) => {-                        writeln!(-                            f,-                            "  [{} `{}` (offset: {}, length: {}): {:?}]",-                            "Failed to read contents for label".style(self.theme.styles.error),-                            right-                                .label()-                                .unwrap_or("<none>")-                                .style(self.theme.styles.link),-                            right.offset().style(self.theme.styles.link),-                            right.len().style(self.theme.styles.link),-                            err.style(self.theme.styles.warning)-                        )?;-                        return Ok(());-                    }-                };--            if contexts.is_empty() {-                contexts.push((right, right_conts));-                continue;-            }--            let (left, left_conts) = contexts.last().unwrap();-            if left_conts.line() + left_conts.line_count() >= right_conts.line() {-                // The snippets will overlap, so we create one Big Chunky Boi-                let left_end = left.offset() + left.len();-                let right_end = right.offset() + right.len();-                let new_end = std::cmp::max(left_end, right_end);--                let new_span = LabeledSpan::new(-                    left.label().map(String::from),-                    left.offset(),-                    new_end - left.offset(),-                );-                // Check that the two contexts can be combined-                if let Ok(new_conts) =-                    source.read_span(new_span.inner(), self.context_lines, self.context_lines)-                {-                    contexts.pop();-                    // We'll throw the contents away later-                    contexts.push((new_span, new_conts));-                    continue;-                }-            }--            contexts.push((right, right_conts));-        }-        for (ctx, _) in contexts {-            self.render_context(f, source, &ctx, &labels[..])?;-        }--        Ok(())-    }--    fn render_context(-        &self,-        f: &mut impl fmt::Write,-        source: &dyn SourceCode,-        context: &LabeledSpan,-        labels: &[LabeledSpan],-    ) -> fmt::Result {-        let lines = self.get_lines(source, context.inner())?;--        // sorting is your friend-        let labels = labels-            .iter()-            .zip(self.theme.styles.highlights.iter().cloned().cycle())-            .map(|(label, st)| FancySpan::new(label.label().map(String::from), *label.inner(), st))-            .collect::<Vec<_>>();--        // The max number of gutter-lines that will be active at any given-        // point. We need this to figure out indentation, so we do one loop-        // over the lines to see what the damage is gonna be.-        let mut max_gutter = 0usize;-        for line in &lines {-            let mut num_highlights = 0;-            for hl in &labels {-                if !line.span_line_only(hl) && line.span_applies_gutter(hl) {-                    num_highlights += 1;-                }-            }-            max_gutter = std::cmp::max(max_gutter, num_highlights);-        }--        // Now it's time for the fun part--actually rendering everything!-        for line in &lines {-            // Then, we need to print the gutter, along with any fly-bys We-            // have separate gutters depending on whether we're on the actual-            // line, or on one of the "highlight lines" below it.-            self.render_line_gutter(f, max_gutter, line, &labels)?;--            // And _now_ we can print out the line text itself!-            self.render_line_text(f, &line.text)?;--            // Next, we write all the highlights that apply to this particular line.-            let (single_line, multi_line): (Vec<_>, Vec<_>) = labels-                .iter()-                .filter(|hl| line.span_applies(hl))-                .partition(|hl| line.span_line_only(hl));-            if !single_line.is_empty() {-                // gutter _again_-                self.render_highlight_gutter(-                    f,-                    max_gutter,-                    line,-                    &labels,-                    LabelRenderMode::SingleLine,-                )?;-                self.render_single_line_highlights(f, line, max_gutter, &single_line, &labels)?;-            }-            for hl in multi_line {-                if hl.label().is_some() && line.span_ends(hl) && !line.span_starts(hl) {-                    self.render_multi_line_end(f, &labels, max_gutter, line, hl)?;-                }-            }-        }--        Ok(())-    }--    fn render_multi_line_end(-        &self,-        f: &mut impl fmt::Write,-        labels: &[FancySpan],-        max_gutter: usize,-        line: &Line,-        label: &FancySpan,-    ) -> fmt::Result {-        if let Some(label_parts) = label.label_parts() {-            // if it has a label, how long is it?-            let (first, rest) = label_parts.split_first().expect(-                "cannot crash because rest would have been None, see docs on the `label` field of \-                 FancySpan",-            );--            if rest.is_empty() {-                // gutter _again_-                self.render_highlight_gutter(-                    f,-                    max_gutter,-                    line,-                    labels,-                    LabelRenderMode::SingleLine,-                )?;--                self.render_multi_line_end_single(-                    f,-                    first,-                    label.style,-                    LabelRenderMode::SingleLine,-                )?;-            } else {-                // gutter _again_-                self.render_highlight_gutter(-                    f,-                    max_gutter,-                    line,-                    labels,-                    LabelRenderMode::MultiLineFirst,-                )?;--                self.render_multi_line_end_single(-                    f,-                    first,-                    label.style,-                    LabelRenderMode::MultiLineFirst,-                )?;-                for label_line in rest {-                    // gutter _again_-                    self.render_highlight_gutter(-                        f,-                        max_gutter,-                        line,-                        labels,-                        LabelRenderMode::MultiLineRest,-                    )?;-                    self.render_multi_line_end_single(-                        f,-                        label_line,-                        label.style,-                        LabelRenderMode::MultiLineRest,-                    )?;-                }-            }-        } else {-            // gutter _again_-            self.render_highlight_gutter(f, max_gutter, line, labels, LabelRenderMode::SingleLine)?;-            // has no label-            writeln!(f, "{}", self.theme.characters.hbar.style(label.style))?;-        }--        Ok(())-    }--    fn render_line_gutter(-        &self,-        f: &mut impl fmt::Write,-        max_gutter: usize,-        line: &Line,-        highlights: &[FancySpan],-    ) -> fmt::Result {-        if max_gutter == 0 {-            return Ok(());-        }-        let chars = &self.theme.characters;-        let mut gutter = String::new();-        let applicable = highlights.iter().filter(|hl| line.span_applies_gutter(hl));-        let mut arrow = false;-        for (i, hl) in applicable.enumerate() {-            if line.span_starts(hl) {-                gutter.push_str(&chars.ltop.style(hl.style).to_string());-                gutter.push_str(-                    &chars-                        .hbar-                        .to_string()-                        .repeat(max_gutter.saturating_sub(i))-                        .style(hl.style)-                        .to_string(),-                );-                gutter.push_str(&chars.rarrow.style(hl.style).to_string());-                arrow = true;-                break;-            } else if line.span_ends(hl) {-                if hl.label().is_some() {-                    gutter.push_str(&chars.lcross.style(hl.style).to_string());-                } else {-                    gutter.push_str(&chars.lbot.style(hl.style).to_string());-                }-                gutter.push_str(-                    &chars-                        .hbar-                        .to_string()-                        .repeat(max_gutter.saturating_sub(i))-                        .style(hl.style)-                        .to_string(),-                );-                gutter.push_str(&chars.rarrow.style(hl.style).to_string());-                arrow = true;-                break;-            } else if line.span_flyby(hl) {-                gutter.push_str(&chars.vbar.style(hl.style).to_string());-            } else {-                gutter.push(' ');-            }-        }-        write!(-            f,-            "{}{}",-            gutter,-            " ".repeat(-                if arrow { 1 } else { 3 } + max_gutter.saturating_sub(gutter.chars().count())-            )-        )?;-        Ok(())-    }--    fn render_highlight_gutter(-        &self,-        f: &mut impl fmt::Write,-        max_gutter: usize,-        line: &Line,-        highlights: &[FancySpan],-        render_mode: LabelRenderMode,-    ) -> fmt::Result {-        if max_gutter == 0 {-            return Ok(());-        }--        // keeps track of how many columns wide the gutter is-        // important for ansi since simply measuring the size of the final string-        // gives the wrong result when the string contains ansi codes.-        let mut gutter_cols = 0;--        let chars = &self.theme.characters;-        let mut gutter = String::new();-        let applicable = highlights.iter().filter(|hl| line.span_applies_gutter(hl));-        for (i, hl) in applicable.enumerate() {-            if !line.span_line_only(hl) && line.span_ends(hl) {-                if render_mode == LabelRenderMode::MultiLineRest {-                    // this is to make multiline labels work. We want to make the right amount-                    // of horizontal space for them, but not actually draw the lines-                    let horizontal_space = max_gutter.saturating_sub(i) + 2;-                    for _ in 0..horizontal_space {-                        gutter.push(' ');-                    }-                    // account for one more horizontal space, since in multiline mode-                    // we also add in the vertical line before the label like this:-                    // 2 │ ╭─▶   text-                    // 3 │ ├─▶     here-                    //   · ╰──┤ these two lines-                    //   ·    │ are the problem-                    //        ^this-                    gutter_cols += horizontal_space + 1;-                } else {-                    let num_repeat = max_gutter.saturating_sub(i) + 2;--                    gutter.push_str(&chars.lbot.style(hl.style).to_string());--                    gutter.push_str(-                        &chars-                            .hbar-                            .to_string()-                            .repeat(-                                num_repeat-                                    // if we are rendering a multiline label, then leave a bit of space for the-                                    // rcross character-                                    - if render_mode == LabelRenderMode::MultiLineFirst {-                                        1-                                    } else {-                                        0-                                    },-                            )-                            .style(hl.style)-                            .to_string(),-                    );--                    // we count 1 for the lbot char, and then a few more, the same number-                    // as we just repeated for. For each repeat we only add 1, even though-                    // due to ansi escape codes the number of bytes in the string could grow-                    // a lot each time.-                    gutter_cols += num_repeat + 1;-                }-                break;-            } else {-                gutter.push_str(&chars.vbar.style(hl.style).to_string());--                // we may push many bytes for the ansi escape codes style adds,-                // but we still only add a single character-width to the string in a terminal-                gutter_cols += 1;-            }-        }--        // now calculate how many spaces to add based on how many columns we just-        // created. it's the max width of the gutter, minus how many-        // character-widths we just generated capped at 0 (though this should-        // never go below in reality), and then we add 3 to account for-        // arrowheads when a gutter line ends-        let num_spaces = (max_gutter + 3).saturating_sub(gutter_cols);-        // we then write the gutter and as many spaces as we need-        write!(f, "{}{:width$}", gutter, "", width = num_spaces)?;-        Ok(())-    }--    /// Returns an iterator over the visual width of each character in a line.-    fn line_visual_char_width<'a>(&self, text: &'a str) -> impl Iterator<Item = usize> + 'a {-        let mut column = 0;-        let mut escaped = false;-        let tab_width = self.tab_width;-        text.chars().map(move |c| {-            let width = match (escaped, c) {-                // Round up to the next multiple of tab_width-                (false, '\t') => tab_width - column % tab_width,-                // start of ANSI escape-                (false, '\x1b') => {-                    escaped = true;-                    0-                }-                // use Unicode width for all other characters-                (false, c) => c.width().unwrap_or(0),-                // end of ANSI escape-                (true, 'm') => {-                    escaped = false;-                    0-                }-                // characters are zero width within escape sequence-                (true, _) => 0,-            };-            column += width;-            width-        })-    }--    /// Returns the visual column position of a byte offset on a specific line.-    ///-    /// If the offset occurs in the middle of a character, the returned column-    /// corresponds to that character's first column in `start` is true, or its-    /// last column if `start` is false.-    fn visual_offset(&self, line: &Line, offset: usize, start: bool) -> usize {-        let line_range = line.offset..=(line.offset + line.length);-        assert!(line_range.contains(&offset));--        let mut text_index = offset - line.offset;-        while text_index <= line.text.len() && !line.text.is_char_boundary(text_index) {-            if start {-                text_index -= 1;-            } else {-                text_index += 1;-            }-        }-        let text = &line.text[..text_index.min(line.text.len())];-        let text_width = self.line_visual_char_width(text).sum();-        if text_index > line.text.len() {-            // Spans extending past the end of the line are always rendered as-            // one column past the end of the visible line.-            //-            // This doesn't necessarily correspond to a specific byte-offset,-            // since a span extending past the end of the line could contain:-            //  - an actual \n character (1 byte)-            //  - a CRLF (2 bytes)-            //  - EOF (0 bytes)-            text_width + 1-        } else {-            text_width-        }-    }--    /// Renders a line to the output formatter, replacing tabs with spaces.-    fn render_line_text(&self, f: &mut impl fmt::Write, text: &str) -> fmt::Result {-        for (c, width) in text.chars().zip(self.line_visual_char_width(text)) {-            if c == '\t' {-                for _ in 0..width {-                    f.write_char(' ')?;-                }-            } else {-                f.write_char(c)?;-            }-        }-        f.write_char('\n')?;-        Ok(())-    }--    fn render_single_line_highlights(-        &self,-        f: &mut impl fmt::Write,-        line: &Line,-        max_gutter: usize,-        single_liners: &[&FancySpan],-        all_highlights: &[FancySpan],-    ) -> fmt::Result {-        let mut underlines = String::new();-        let mut highest = 0;--        let chars = &self.theme.characters;-        let vbar_offsets: Vec<_> = single_liners-            .iter()-            .map(|hl| {-                let byte_start = hl.offset();-                let byte_end = hl.offset() + hl.len();-                let start = self.visual_offset(line, byte_start, true).max(highest);-                let end = if hl.len() == 0 {-                    start + 1-                } else {-                    self.visual_offset(line, byte_end, false).max(start + 1)-                };--                let vbar_offset = (start + end) / 2;-                let num_left = vbar_offset - start;-                let num_right = end - vbar_offset - 1;-                underlines.push_str(-                    &format!(-                        "{:width$}{}{}{}",-                        "",-                        chars.underline.to_string().repeat(num_left),-                        if hl.len() == 0 {-                            chars.uarrow-                        } else if hl.label().is_some() {-                            chars.underbar-                        } else {-                            chars.underline-                        },-                        chars.underline.to_string().repeat(num_right),-                        width = start.saturating_sub(highest),-                    )-                    .style(hl.style)-                    .to_string(),-                );-                highest = std::cmp::max(highest, end);--                (hl, vbar_offset)-            })-            .collect();-        writeln!(f, "{underlines}")?;--        for hl in single_liners.iter().rev() {-            if let Some(label) = hl.label_parts() {-                if label.len() == 1 {-                    self.write_label_text(-                        f,-                        line,-                        max_gutter,-                        all_highlights,-                        chars,-                        &vbar_offsets,-                        hl,-                        &label[0],-                        LabelRenderMode::SingleLine,-                    )?;-                } else {-                    let mut first = true;-                    for label_line in &label {-                        self.write_label_text(-                            f,-                            line,-                            max_gutter,-                            all_highlights,-                            chars,-                            &vbar_offsets,-                            hl,-                            label_line,-                            if first {-                                LabelRenderMode::MultiLineFirst-                            } else {-                                LabelRenderMode::MultiLineRest-                            },-                        )?;-                        first = false;-                    }-                }-            }-        }-        Ok(())-    }--    // I know it's not good practice, but making this a function makes a lot of-    // sense and making a struct for this does not...-    #[allow(clippy::too_many_arguments)]-    fn write_label_text(-        &self,-        f: &mut impl fmt::Write,-        line: &Line,-        max_gutter: usize,-        all_highlights: &[FancySpan],-        chars: &ThemeCharacters,-        vbar_offsets: &[(&&FancySpan, usize)],-        hl: &&FancySpan,-        label: &str,-        render_mode: LabelRenderMode,-    ) -> fmt::Result {-        self.render_highlight_gutter(-            f,-            max_gutter,-            line,-            all_highlights,-            LabelRenderMode::SingleLine,-        )?;-        let mut curr_offset = 1usize;-        for (offset_hl, vbar_offset) in vbar_offsets {-            while curr_offset < *vbar_offset + 1 {-                write!(f, " ")?;-                curr_offset += 1;-            }-            if *offset_hl != hl {-                write!(f, "{}", chars.vbar.to_string().style(offset_hl.style))?;-                curr_offset += 1;-            } else {-                let lines = match render_mode {-                    LabelRenderMode::SingleLine => format!(-                        "{}{} {}",-                        chars.lbot,-                        chars.hbar.to_string().repeat(2),-                        label,-                    ),-                    LabelRenderMode::MultiLineFirst => {-                        format!("{}{}{} {}", chars.lbot, chars.hbar, chars.rcross, label,)-                    }-                    LabelRenderMode::MultiLineRest => {-                        format!("  {} {}", chars.vbar, label,)-                    }-                };-                writeln!(f, "{}", lines.style(hl.style))?;-                break;-            }-        }-        Ok(())-    }--    fn render_multi_line_end_single(-        &self,-        f: &mut impl fmt::Write,-        label: &str,-        style: Style,-        render_mode: LabelRenderMode,-    ) -> fmt::Result {-        match render_mode {-            LabelRenderMode::SingleLine => {-                writeln!(f, "{} {}", self.theme.characters.hbar.style(style), label)?;-            }-            LabelRenderMode::MultiLineFirst => {-                writeln!(f, "{} {}", self.theme.characters.rcross.style(style), label)?;-            }-            LabelRenderMode::MultiLineRest => {-                writeln!(f, "{} {}", self.theme.characters.vbar.style(style), label)?;-            }-        }--        Ok(())-    }--    fn get_lines<'a>(-        &'a self,-        source: &'a dyn SourceCode,-        context_span: &'a SourceSpan,-    ) -> Result<Vec<Line>, fmt::Error> {-        let context_data = source-            .read_span(context_span, self.context_lines, self.context_lines)-            .map_err(|_| fmt::Error)?;-        let context = String::from_utf8_lossy(context_data.data());-        let mut column = context_data.column();-        let mut offset = context_data.span().offset();-        let mut line_offset = offset;-        let mut line_str = String::with_capacity(context.len());-        let mut lines = Vec::with_capacity(1);-        let mut iter = context.chars().peekable();-        while let Some(ch) = iter.next() {-            offset += ch.len_utf8();-            match ch {-                '\r' if iter.next_if_eq(&'\n').is_some() => {-                    offset += 1;-                    column = 0;-                }-                '\r' => {-                    line_str.push(ch);-                    column += 1;-                }-                '\n' => {-                    column = 0;-                }-                _ => {-                    line_str.push(ch);-                    column += 1;-                }-            }--            if column == 0 || iter.peek().is_none() {-                lines.push(Line {-                    offset: line_offset,-                    length: offset - line_offset,-                    text: line_str.clone(),-                });-                line_str.clear();-                line_offset = offset;-            }-        }-        Ok(lines)-    }-}--impl ReportHandler for SwcReportHandler {-    fn debug(&self, diagnostic: &dyn Diagnostic, f: &mut fmt::Formatter<'_>) -> fmt::Result {-        if f.alternate() {-            return fmt::Debug::fmt(diagnostic, f);-        }--        self.render_report(f, diagnostic)-    }-}--/*-Support types-*/--#[derive(PartialEq, Debug)]-enum LabelRenderMode {-    /// we're rendering a single line label (or not rendering in any special-    /// way)-    SingleLine,-    /// we're rendering a multiline label-    MultiLineFirst,-    /// we're rendering the rest of a multiline label-    MultiLineRest,-}--#[derive(Debug)]-struct Line {-    offset: usize,-    length: usize,-    text: String,-}--impl Line {-    fn span_line_only(&self, span: &FancySpan) -> bool {-        span.offset() >= self.offset && span.offset() + span.len() <= self.offset + self.length-    }--    /// Returns whether `span` should be visible on this line, either in the-    /// gutter or under the text on this line-    fn span_applies(&self, span: &FancySpan) -> bool {-        let spanlen = if span.len() == 0 { 1 } else { span.len() };-        // Span starts in this line--        (span.offset() >= self.offset && span.offset() < self.offset + self.length)-            // Span passes through this line-            || (span.offset() < self.offset && span.offset() + spanlen > self.offset + self.length) //todo-            // Span ends on this line-            || (span.offset() + spanlen > self.offset && span.offset() + spanlen <= self.offset + self.length)-    }--    /// Returns whether `span` should be visible on this line in the gutter (so-    /// this excludes spans that are only visible on this line and do not-    /// span multiple lines)-    fn span_applies_gutter(&self, span: &FancySpan) -> bool {-        let spanlen = if span.len() == 0 { 1 } else { span.len() };-        // Span starts in this line-        self.span_applies(span)-            && !(-                // as long as it doesn't start *and* end on this line-                (span.offset() >= self.offset && span.offset() < self.offset + self.length)-                    && (span.offset() + spanlen > self.offset-                        && span.offset() + spanlen <= self.offset + self.length)-            )-    }--    // A 'flyby' is a multi-line span that technically covers this line, but-    // does not begin or end within the line itself. This method is used to-    // calculate gutters.-    fn span_flyby(&self, span: &FancySpan) -> bool {-        // The span itself starts before this line's starting offset (so, in a-        // prev line).-        span.offset() < self.offset-            // ...and it stops after this line's end.-            && span.offset() + span.len() > self.offset + self.length-    }--    // Does this line contain the *beginning* of this multiline span?-    // This assumes self.span_applies() is true already.-    fn span_starts(&self, span: &FancySpan) -> bool {-        span.offset() >= self.offset-    }--    // Does this line contain the *end* of this multiline span?-    // This assumes self.span_applies() is true already.-    fn span_ends(&self, span: &FancySpan) -> bool {-        span.offset() + span.len() >= self.offset-            && span.offset() + span.len() <= self.offset + self.length-    }-}--#[derive(Debug, Clone)]-struct FancySpan {-    /// this is deliberately an option of a vec because I wanted to be very-    /// explicit that there can also be *no* label. If there is a label, it-    /// can have multiple lines which is what the vec is for.-    label: Option<Vec<String>>,-    span: SourceSpan,-    style: Style,-}--impl PartialEq for FancySpan {-    fn eq(&self, other: &Self) -> bool {-        self.label == other.label && self.span == other.span-    }-}--fn split_label(v: String) -> Vec<String> {-    v.split('\n').map(|i| i.to_string()).collect()-}--impl FancySpan {-    fn new(label: Option<String>, span: SourceSpan, style: Style) -> Self {-        FancySpan {-            label: label.map(split_label),-            span,-            style,-        }-    }--    fn style(&self) -> Style {-        self.style-    }--    fn label(&self) -> Option<String> {-        self.label-            .as_ref()-            .map(|l| l.join("\n").style(self.style()).to_string())-    }--    fn label_parts(&self) -> Option<Vec<String>> {-        self.label.as_ref().map(|l| {-            l.iter()-                .map(|i| i.style(self.style()).to_string())-                .collect()-        })-    }--    fn offset(&self) -> usize {-        self.span.offset()-    }--    fn len(&self) -> usize {-        self.span.len()-    }-}

deps/swc/bindings/binding_typescript_wasm/src/lib.rs

deleted file mode 100644@@ -1,267 +0,0 @@-use std::{-    iter::once,-    mem::take,-    sync::{Arc, Mutex},-};--use anyhow::Error;-use error_reporter::SwcReportHandler;-use js_sys::Uint8Array;-use miette::{GraphicalTheme, LabeledSpan, ThemeCharacters, ThemeStyles};-use serde::Serialize;-use swc_common::{-    errors::{DiagnosticBuilder, DiagnosticId, Emitter, Handler, HANDLER},-    sync::Lrc,-    SourceMap, Span, GLOBALS,-};-use swc_error_reporters::{convert_span, to_pretty_source_code};-use swc_ts_fast_strip::{Options, TransformOutput};-use wasm_bindgen::prelude::*;-use wasm_bindgen_futures::{future_to_promise, js_sys::Promise};--mod error_reporter;--/// Custom interface definitions for the @swc/wasm's public interface instead of-/// auto generated one, which is not reflecting most of types in detail.-#[wasm_bindgen(typescript_custom_section)]-const INTERFACE_DEFINITIONS: &'static str = r#"-export declare function transform(src: string | Uint8Array, opts?: Options): Promise<TransformOutput>;-export declare function transformSync(src: string | Uint8Array, opts?: Options): TransformOutput;-export type { Options, TransformOutput };-"#;--#[wasm_bindgen(skip_typescript)]-pub fn transform(input: JsValue, options: JsValue) -> Promise {-    future_to_promise(async move { transform_sync(input, options) })-}--#[wasm_bindgen(js_name = "transformSync", skip_typescript)]-pub fn transform_sync(input: JsValue, options: JsValue) -> Result<JsValue, JsValue> {-    let options: Options = if options.is_falsy() {-        Default::default()-    } else {-        serde_wasm_bindgen::from_value(options)?-    };--    let input = match input.as_string() {-        Some(input) => input,-        None => {-            if input.is_instance_of::<Uint8Array>() {-                let input = input.unchecked_into::<Uint8Array>();-                match input.to_string().as_string() {-                    Some(input) => input,-                    None => return Err(JsValue::from_str("Input Uint8Array is not valid utf-8")),-                }-            } else {-                return Err(JsValue::from_str("Input is not a string or Uint8Array"));-            }-        }-    };--    let result = GLOBALS.set(&Default::default(), || operate(input, options));--    match result {-        Ok(v) => Ok(serde_wasm_bindgen::to_value(&v)?),-        Err(errors) => Err(serde_wasm_bindgen::to_value(&errors[0])?),-    }-}--fn operate(input: String, options: Options) -> Result<TransformOutput, Vec<JsonDiagnostic>> {-    let cm = Lrc::new(SourceMap::default());--    try_with_json_handler(cm.clone(), |handler| {-        swc_ts_fast_strip::operate(&cm, handler, input, options).map_err(anyhow::Error::new)-    })-}--#[derive(Clone)]-struct JsonErrorWriter {-    errors: Arc<Mutex<Vec<JsonDiagnostic>>>,-    /// Successful transforms never need the graphical diagnostic reporter.-    reporter: Option<SwcReportHandler>,-    cm: Lrc<SourceMap>,-}--fn try_with_json_handler<F, Ret>(cm: Lrc<SourceMap>, op: F) -> Result<Ret, Vec<JsonDiagnostic>>-where-    F: FnOnce(&Handler) -> Result<Ret, Error>,-{-    let wr = JsonErrorWriter {-        errors: Default::default(),-        reporter: None,-        cm,-    };-    let emitter: Box<dyn Emitter> = Box::new(wr.clone());--    let handler = Handler::with_emitter(true, false, emitter);--    let ret = HANDLER.set(&handler, || op(&handler));--    if handler.has_errors() {-        let mut lock = wr.errors.lock().unwrap();-        let error = take(&mut *lock);--        Err(error)-    } else {-        Ok(ret.expect("it should not fail without emitting errors to handler"))-    }-}--impl Emitter for JsonErrorWriter {-    fn emit(&mut self, db: &mut DiagnosticBuilder) {-        let d = &**db;--        let snippet = d.span.primary_span().and_then(|span| {-            let mut snippet = String::new();-            let reporter = self.reporter.get_or_insert_with(json_reporter);-            match reporter.render_report(-                &mut snippet,-                &Snippet {-                    source_code: &to_pretty_source_code(&self.cm, true),-                    span,-                },-            ) {-                Ok(()) => Some(snippet),-                Err(_) => None,-            }-        });--        let children = d-            .children-            .iter()-            .map(|d| todo!("json subdiagnostic: {d:?}"))-            .collect::<Vec<_>>();--        let error_code = match &d.code {-            Some(DiagnosticId::Error(s)) => Some(&**s),-            Some(DiagnosticId::Lint(s)) => Some(&**s),-            None => None,-        };--        let start = d-            .span-            .primary_span()-            .and_then(|span| self.cm.try_lookup_char_pos(span.lo()).ok());--        let end = d-            .span-            .primary_span()-            .and_then(|span| self.cm.try_lookup_char_pos(span.hi()).ok());--        let filename = start.as_ref().map(|loc| loc.file.name.to_string());--        let error = JsonDiagnostic {-            code: error_code.map(|s| s.to_string()),-            message: d.message[0].0.to_string(),-            snippet,-            filename,-            start_line: start.as_ref().map(|loc| loc.line),-            start_column: start.as_ref().map(|loc| loc.col_display),-            end_line: end.as_ref().map(|loc| loc.line),-            end_column: end.as_ref().map(|loc| loc.col_display),-            children,-        };--        self.errors.lock().unwrap().push(error);-    }--    fn take_diagnostics(&mut self) -> Vec<String> {-        Default::default()-    }-}--fn json_reporter() -> SwcReportHandler {-    SwcReportHandler::default().with_theme(GraphicalTheme {-        characters: ThemeCharacters {-            hbar: ' ',-            vbar: ' ',-            xbar: ' ',-            vbar_break: ' ',-            ltop: ' ',-            rtop: ' ',-            mtop: ' ',-            lbot: ' ',-            rbot: ' ',-            mbot: ' ',-            error: "".into(),-            warning: "".into(),-            advice: "".into(),-            ..ThemeCharacters::ascii()-        },-        styles: ThemeStyles::none(),-    })-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-struct JsonDiagnostic {-    /// Error code-    #[serde(skip_serializing_if = "Option::is_none")]-    code: Option<String>,-    message: String,--    #[serde(skip_serializing_if = "Option::is_none")]-    snippet: Option<String>,--    #[serde(skip_serializing_if = "Option::is_none")]-    filename: Option<String>,--    #[serde(skip_serializing_if = "Option::is_none")]-    start_line: Option<usize>,-    #[serde(skip_serializing_if = "Option::is_none")]-    start_column: Option<usize>,--    #[serde(skip_serializing_if = "Option::is_none")]-    end_line: Option<usize>,-    #[serde(skip_serializing_if = "Option::is_none")]-    end_column: Option<usize>,--    #[serde(skip_serializing_if = "Vec::is_empty")]-    children: Vec<JsonSubdiagnostic>,-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-struct JsonSubdiagnostic {-    message: String,-    #[serde(skip_serializing_if = "Option::is_none")]-    snippet: Option<String>,-    filename: String,-    line: usize,-}--struct Snippet<'a> {-    source_code: &'a dyn miette::SourceCode,-    span: Span,-}--impl miette::Diagnostic for Snippet<'_> {-    fn source_code(&self) -> Option<&dyn miette::SourceCode> {-        if self.span.lo().is_dummy() || self.span.hi().is_dummy() {-            return None;-        }--        Some(self.source_code)-    }--    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {-        Some(Box::new(once(LabeledSpan::new_with_span(-            None,-            convert_span(self.span),-        ))))-    }-}--impl std::error::Error for Snippet<'_> {}--impl std::fmt::Display for Snippet<'_> {-    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {-        Ok(())-    }-}--impl std::fmt::Debug for Snippet<'_> {-    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {-        Ok(())-    }-}

deps/swc/bindings/binding_typescript_wasm/src/wasm-node.js

deleted file mode 100644@@ -1,10 +0,0 @@-import fs from "node:fs/promises";-import initAsync from "./wasm.js";--const wasm = new URL("./wasm_bg.wasm", import.meta.url);--export default function (init = fs.readFile(wasm)) {-    return initAsync(init);-}--export * from "./wasm.js";

deps/swc/bindings/swc_cli/Cargo.toml

deleted file mode 100644@@ -1,23 +0,0 @@-[package]-authors     = ["강동윤 <kdy1997.dev@gmail.com>", "OJ Kwon <kwon.ohjoong@gmail.com>"]-description = "Commandline for SWC"-edition     = { workspace = true }-include     = ["Cargo.toml", "src/**/*.rs"]-license     = { workspace = true }-name        = "swc_cli"-repository  = { workspace = true }-version     = "0.127.7"--[[bin]]-bench = false-name  = "swc"-path  = "./src/main.rs"--[features]-default = ["swc_cli_impl/default"]-plugin  = ["swc_cli_impl/plugin"]--[dependencies]-anyhow       = { workspace = true }-par-core     = { workspace = true, features = ["chili"] }-swc_cli_impl = { version = "82.0.0", path = "../../crates/swc_cli_impl" }

deps/swc/bindings/swc_cli/src/main.rs

deleted file mode 100644@@ -1,3 +0,0 @@-fn main() -> anyhow::Result<()> {-    swc_cli_impl::run()-}