| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use anyhow::Context; |
| use napi::bindgen_prelude::*; |
| use swc_core::{ |
| base::{TransformOutput, config::JsMinifyOptions, try_with_handler}, |
| common::{FileName, GLOBALS, errors::ColorConfig}, |
| }; |
|
|
| use crate::{get_compiler, util::MapErr}; |
|
|
| pub struct MinifyTask { |
| c: swc_core::base::Compiler, |
| code: Option<String>, |
| opts: JsMinifyOptions, |
| } |
|
|
| #[napi] |
| impl Task for MinifyTask { |
| type Output = TransformOutput; |
|
|
| type JsValue = TransformOutput; |
|
|
| fn compute(&mut self) -> napi::Result<Self::Output> { |
| let code = self.code.take().unwrap_or_default(); |
|
|
| try_with_handler( |
| self.c.cm.clone(), |
| swc_core::base::HandlerOpts { |
| color: ColorConfig::Never, |
| skip_filename: true, |
| }, |
| |handler| { |
| GLOBALS.set(&Default::default(), || { |
| let fm = self.c.cm.new_source_file(FileName::Anon.into(), code); |
|
|
| self.c.minify(fm, handler, &self.opts, Default::default()) |
| }) |
| }, |
| ) |
| .map_err(|e| e.to_pretty_error()) |
| .convert_err() |
| } |
|
|
| fn resolve(&mut self, _: napi::Env, output: Self::Output) -> napi::Result<Self::JsValue> { |
| Ok(output) |
| } |
| } |
|
|
| #[napi] |
| pub fn minify( |
| input: Buffer, |
| opts: Buffer, |
| signal: Option<AbortSignal>, |
| ) -> napi::Result<AsyncTask<MinifyTask>> { |
| let code = String::from_utf8(input.into()) |
| .context("failed to convert input to string") |
| .convert_err()?; |
| let opts = serde_json::from_slice(&opts)?; |
|
|
| let c = get_compiler(); |
|
|
| let task = MinifyTask { |
| c, |
| code: Some(code), |
| opts, |
| }; |
|
|
| Ok(AsyncTask::with_optional_signal(task, signal)) |
| } |
|
|
| #[napi] |
| pub fn minify_sync(input: Buffer, opts: Buffer) -> napi::Result<TransformOutput> { |
| let code = String::from_utf8(input.into()) |
| .context("failed to convert input to string") |
| .convert_err()?; |
| let opts = serde_json::from_slice(&opts)?; |
|
|
| let c = get_compiler(); |
|
|
| let fm = c.cm.new_source_file(FileName::Anon.into(), code); |
|
|
| try_with_handler( |
| c.cm.clone(), |
| swc_core::base::HandlerOpts { |
| color: ColorConfig::Never, |
| skip_filename: true, |
| }, |
| |handler| { |
| GLOBALS.set(&Default::default(), || { |
| c.minify(fm, handler, &opts, Default::default()) |
| }) |
| }, |
| ) |
| .map_err(|e| e.to_pretty_error()) |
| .convert_err() |
| } |
|
|