-
Notifications
You must be signed in to change notification settings - Fork 28.1k
/
Copy pathminify.rs
181 lines (162 loc) · 6.09 KB
/
minify.rs
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
use std::{io::Write, sync::Arc};
use anyhow::{bail, Context, Result};
use swc_core::{
base::try_with_handler,
common::{
comments::{Comments, SingleThreadedComments},
BytePos, FileName, FilePathMapping, LineCol, Mark, SourceMap as SwcSourceMap, GLOBALS,
},
ecma::{
self,
ast::{EsVersion, Program},
codegen::{
text_writer::{self, JsWriter, WriteJs},
Emitter,
},
minifier::option::{CompressOptions, ExtraOptions, MangleOptions, MinifyOptions},
parser::{lexer::Lexer, Parser, StringInput, Syntax},
transforms::base::{
fixer::paren_remover,
hygiene::{self, hygiene_with_config},
},
},
};
use tracing::{instrument, Level};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::code_builder::{Code, CodeBuilder};
use crate::parse::generate_js_source_map;
#[instrument(level = Level::INFO, skip_all)]
pub fn minify(path: &FileSystemPath, code: &Code, source_maps: bool, mangle: bool) -> Result<Code> {
let source_maps = source_maps
.then(|| code.generate_source_map_ref())
.transpose()?;
let cm = Arc::new(SwcSourceMap::new(FilePathMapping::empty()));
let (src, mut src_map_buf) = {
let fm = cm.new_source_file(
FileName::Custom(path.path.to_string()).into(),
code.source_code().to_str()?.into_owned(),
);
let lexer = Lexer::new(
Syntax::default(),
EsVersion::latest(),
StringInput::from(&*fm),
None,
);
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{}",
code.source_code().to_str()?
)
}
};
let comments = SingleThreadedComments::default();
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,
..Default::default()
}),
mangle: if mangle {
Some(MangleOptions {
reserved: vec!["AbortSignal".into()],
..Default::default()
})
} else {
None
},
..Default::default()
},
&ExtraOptions {
top_level_mark,
unresolved_mark,
mangle_name_cache: None,
},
);
if !mangle {
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,
))))
})
})?;
print_program(cm.clone(), program, source_maps.is_some())?
};
let mut builder = CodeBuilder::default();
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))?),
);
write!(
builder,
// findSourceMapURL assumes this co-located sourceMappingURL,
// and needs to be adjusted in case this is ever changed.
"\n//# sourceMappingURL={}.map",
urlencoding::encode(path.file_name())
)?;
} 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")?;
}
if source_maps {
// end with a new line when we have a source map comment
buf.push(b'\n');
}
// Invalid utf8 is valid in javascript world.
// SAFETY: SWC generates valid utf8.
unsafe { String::from_utf8_unchecked(buf) }
};
Ok((src, src_map_buf))
}