File size: 6,680 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use bytes_str::BytesStr;
use swc_core::{
base::try_with_handler,
common::{
BytePos, FileName, FilePathMapping, GLOBALS, LineCol, Mark, SourceMap as SwcSourceMap,
comments::{Comments, SingleThreadedComments},
},
ecma::{
self,
ast::{EsVersion, Program},
codegen::{
Emitter,
text_writer::{self, JsWriter, WriteJs},
},
minifier::option::{CompressOptions, ExtraOptions, MangleOptions, MinifyOptions},
parser::{Parser, StringInput, Syntax, lexer::Lexer},
transforms::base::{
fixer::paren_remover,
hygiene::{self, hygiene_with_config},
},
},
};
use tracing::{Level, instrument};
use turbopack_core::{
chunk::MangleType,
code_builder::{Code, CodeBuilder},
};
use crate::parse::generate_js_source_map;
#[instrument(level = Level::INFO, skip_all)]
pub fn minify(code: Code, source_maps: bool, mangle: Option<MangleType>) -> Result<Code> {
let source_maps = source_maps
.then(|| code.generate_source_map_ref())
.transpose()?;
let source_code = BytesStr::from_utf8(code.into_source_code().into_bytes())?;
let cm = Arc::new(SwcSourceMap::new(FilePathMapping::empty()));
let (src, mut src_map_buf) = {
let fm = cm.new_source_file(FileName::Anon.into(), source_code);
// Collect all comments and pass to the minifier so that `PURE` comments are respected.
let comments = SingleThreadedComments::default();
let lexer = Lexer::new(
Syntax::default(),
EsVersion::latest(),
StringInput::from(&*fm),
Some(&comments),
);
let mut parser = Parser::new_from(lexer);
let program = try_with_handler(cm.clone(), Default::default(), |handler| {
GLOBALS.set(&Default::default(), || {
let program = match parser.parse_program() {
Ok(program) => program,
Err(err) => {
err.into_diagnostic(handler).emit();
bail!("failed to parse source code\n{}", fm.src)
}
};
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
let program = program.apply(paren_remover(Some(&comments)));
let mut program = program.apply(swc_core::ecma::transforms::base::resolver(
unresolved_mark,
top_level_mark,
false,
));
program = swc_core::ecma::minifier::optimize(
program,
cm.clone(),
Some(&comments),
None,
&MinifyOptions {
compress: Some(CompressOptions {
// Only run 2 passes, this is a tradeoff between performance and
// compression size. Default is 3 passes.
passes: 2,
keep_classnames: mangle.is_none(),
keep_fnames: mangle.is_none(),
..Default::default()
}),
mangle: mangle.map(|mangle| {
let reserved = vec!["AbortSignal".into()];
match mangle {
MangleType::OptimalSize => MangleOptions {
reserved,
..Default::default()
},
MangleType::Deterministic => MangleOptions {
reserved,
disable_char_freq: true,
..Default::default()
},
}
}),
..Default::default()
},
&ExtraOptions {
top_level_mark,
unresolved_mark,
mangle_name_cache: None,
},
);
if mangle.is_none() {
program.mutate(hygiene_with_config(hygiene::Config {
top_level_mark,
..Default::default()
}));
}
Ok(program.apply(ecma::transforms::base::fixer::fixer(Some(
&comments as &dyn Comments,
))))
})
})
.map_err(|e| e.to_pretty_error())?;
print_program(cm.clone(), program, source_maps.is_some())?
};
let mut builder = CodeBuilder::new(source_maps.is_some());
if let Some(original_map) = source_maps.as_ref() {
src_map_buf.shrink_to_fit();
builder.push_source(
&src.into(),
Some(generate_js_source_map(
&*cm,
src_map_buf,
Some(original_map),
true,
// We do not inline source contents.
// We provide a synthesized value to `cm.new_source_file` above, so it cannot be
// the value user expect anyway.
false,
)?),
);
} else {
builder.push_source(&src.into(), None);
}
Ok(builder.build())
}
// From https://github.com/swc-project/swc/blob/11efd4e7c5e8081f8af141099d3459c3534c1e1d/crates/swc/src/lib.rs#L523-L560
fn print_program(
cm: Arc<SwcSourceMap>,
program: Program,
source_maps: bool,
) -> Result<(String, Vec<(BytePos, LineCol)>)> {
let mut src_map_buf = vec![];
let src = {
let mut buf = vec![];
{
let wr = Box::new(text_writer::omit_trailing_semi(Box::new(JsWriter::new(
cm.clone(),
"\n",
&mut buf,
source_maps.then_some(&mut src_map_buf),
)))) as Box<dyn WriteJs>;
let mut emitter = Emitter {
cfg: swc_core::ecma::codegen::Config::default().with_minify(true),
comments: None,
cm: cm.clone(),
wr,
};
emitter
.emit_program(&program)
.context("failed to emit module")?;
}
// Invalid utf8 is valid in javascript world.
// SAFETY: SWC generates valid utf8.
unsafe { String::from_utf8_unchecked(buf) }
};
Ok((src, src_map_buf))
}
|