-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
fs.rs
324 lines (299 loc) Β· 9.13 KB
/
fs.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use crate::dependency_collector::{DependencyDescriptor, DependencyKind};
use crate::hoist::{Collect, Import};
use crate::id;
use crate::utils::{IdentId, SourceLocation};
use data_encoding::{BASE64, HEXLOWER};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use swc_atoms::JsWord;
use swc_common::{Mark, Span, DUMMY_SP};
use swc_ecmascript::ast::*;
use swc_ecmascript::visit::{Fold, FoldWith, VisitWith};
pub fn inline_fs<'a>(
filename: &str,
source_map: swc_common::sync::Lrc<swc_common::SourceMap>,
decls: HashSet<IdentId>,
global_mark: Mark,
project_root: &'a str,
deps: &'a mut Vec<DependencyDescriptor>,
) -> impl Fold + 'a {
InlineFS {
filename: Path::new(filename).to_path_buf(),
collect: Collect::new(
source_map,
decls,
Mark::fresh(Mark::root()),
global_mark,
false,
),
global_mark,
project_root,
deps,
}
}
struct InlineFS<'a> {
filename: PathBuf,
collect: Collect,
global_mark: Mark,
project_root: &'a str,
deps: &'a mut Vec<DependencyDescriptor>,
}
impl<'a> Fold for InlineFS<'a> {
fn fold_module(&mut self, node: Module) -> Module {
node.visit_with(&mut self.collect);
node.fold_children_with(self)
}
fn fold_expr(&mut self, node: Expr) -> Expr {
if let Expr::Call(call) = &node {
if let Callee::Expr(expr) = &call.callee {
if let Some((source, specifier)) = self.match_module_reference(expr) {
if &source == "fs" && &specifier == "readFileSync" {
if let Some(arg) = call.args.get(0) {
if let Some(res) = self.evaluate_fs_arg(&*arg.expr, call.args.get(1), call.span) {
return res;
}
}
}
}
}
}
node.fold_children_with(self)
}
}
impl<'a> InlineFS<'a> {
fn match_module_reference(&self, node: &Expr) -> Option<(JsWord, JsWord)> {
match node {
Expr::Ident(ident) => {
if let Some(Import {
source, specifier, ..
}) = self.collect.imports.get(&id!(ident))
{
return Some((source.clone(), specifier.clone()));
}
}
Expr::Member(member) => {
let prop = match &member.prop {
MemberProp::Ident(ident) => ident.sym.clone(),
MemberProp::Computed(ComputedPropName { expr, .. }) => {
if let Expr::Lit(Lit::Str(str_)) = &**expr {
str_.value.clone()
} else {
return None;
}
}
_ => return None,
};
if let Some(source) = self.collect.match_require(&*member.obj) {
return Some((source, prop));
}
if let Expr::Ident(ident) = &*member.obj {
if let Some(Import {
source, specifier, ..
}) = self.collect.imports.get(&id!(ident))
{
if specifier == "default" || specifier == "*" {
return Some((source.clone(), prop));
}
}
}
}
_ => {}
}
None
}
fn evaluate_fs_arg(
&mut self,
node: &Expr,
encoding: Option<&ExprOrSpread>,
span: Span,
) -> Option<Expr> {
let mut evaluator = Evaluator { inline: self };
let res = node.clone().fold_with(&mut evaluator);
match res {
Expr::Lit(Lit::Str(str_)) => {
// Ignore if outside the project root
let path = match dunce::canonicalize(Path::new(&str_.value.to_string())) {
Ok(path) => path,
Err(_err) => return None,
};
if !path.starts_with(&self.project_root) {
return None;
}
let encoding = match encoding {
Some(e) => match &*e.expr {
Expr::Lit(Lit::Str(str_)) => &str_.value,
_ => "buffer",
},
None => "buffer",
};
// TODO: this should probably happen in JS so we use Parcel's file system
// rather than only the real FS. Will need when we convert to WASM.
let contents = match encoding {
"base64" | "buffer" => {
if let Ok(contents) = std::fs::read(&path) {
BASE64.encode(&contents)
} else {
return None;
}
}
"hex" => {
if let Ok(contents) = std::fs::read(&path) {
HEXLOWER.encode(&contents)
} else {
return None;
}
}
"utf8" | "utf-8" => {
if let Ok(contents) = std::fs::read_to_string(&path) {
contents
} else {
return None;
}
}
_ => return None,
};
let contents = Expr::Lit(Lit::Str(Str {
value: contents.into(),
kind: StrKind::Synthesized,
has_escape: false,
span: DUMMY_SP,
}));
// Add a file dependency so the cache is invalidated when this file changes.
self.deps.push(DependencyDescriptor {
kind: DependencyKind::File,
loc: SourceLocation::from(&self.collect.source_map, span),
specifier: path.to_str().unwrap().into(),
attributes: None,
is_optional: false,
is_helper: false,
source_type: None,
placeholder: None,
});
// If buffer, wrap in Buffer.from(base64String, 'base64')
if encoding == "buffer" {
Some(Expr::Call(CallExpr {
callee: Callee::Expr(Box::new(Expr::Member(MemberExpr {
obj: Box::new(Expr::Ident(Ident::new(
"Buffer".into(),
DUMMY_SP.apply_mark(self.global_mark),
))),
prop: MemberProp::Ident(Ident::new("from".into(), DUMMY_SP)),
span: DUMMY_SP,
}))),
args: vec![
ExprOrSpread {
expr: Box::new(contents),
spread: None,
},
ExprOrSpread {
expr: Box::new(Expr::Lit(Lit::Str(Str {
value: "base64".into(),
kind: StrKind::Synthesized,
has_escape: false,
span: DUMMY_SP,
}))),
spread: None,
},
],
span: DUMMY_SP,
type_args: None,
}))
} else {
Some(contents)
}
}
_ => None,
}
}
}
struct Evaluator<'a> {
inline: &'a InlineFS<'a>,
}
impl<'a> Fold for Evaluator<'a> {
fn fold_expr(&mut self, node: Expr) -> Expr {
let node = node.fold_children_with(self);
match &node {
Expr::Ident(ident) => match ident.sym.to_string().as_str() {
"__dirname" => Expr::Lit(Lit::Str(Str {
value: self
.inline
.filename
.parent()
.unwrap()
.to_str()
.unwrap()
.into(),
kind: StrKind::Synthesized,
has_escape: false,
span: DUMMY_SP,
})),
"__filename" => Expr::Lit(Lit::Str(Str {
value: self.inline.filename.to_str().unwrap().into(),
kind: StrKind::Synthesized,
has_escape: false,
span: DUMMY_SP,
})),
_ => node,
},
Expr::Bin(bin) => match bin.op {
BinaryOp::Add => {
let left = match &*bin.left {
Expr::Lit(Lit::Str(str_)) => str_.value.clone(),
_ => return node,
};
let right = match &*bin.right {
Expr::Lit(Lit::Str(str_)) => str_.value.clone(),
_ => return node,
};
Expr::Lit(Lit::Str(Str {
value: format!("{}{}", left, right).into(),
kind: StrKind::Synthesized,
has_escape: false,
span: DUMMY_SP,
}))
}
_ => node,
},
Expr::Call(call) => {
let callee = match &call.callee {
Callee::Expr(expr) => &*expr,
_ => return node,
};
if let Some((source, specifier)) = self.inline.match_module_reference(callee) {
match (source.to_string().as_str(), specifier.to_string().as_str()) {
("path", "join") => {
let mut path = PathBuf::new();
for arg in call.args.clone() {
let s = match &*arg.expr {
Expr::Lit(Lit::Str(str_)) => str_.value.clone(),
_ => return node,
};
if path.as_os_str().is_empty() {
path.push(s.to_string());
} else {
let s = s.to_string();
let mut p = Path::new(s.as_str());
// Node's path.join ignores separators at the start of path components.
// Rust's does not, so we need to strip them.
if let Ok(stripped) = p.strip_prefix("/") {
p = stripped;
}
path.push(p);
}
}
return Expr::Lit(Lit::Str(Str {
value: path.to_str().unwrap().into(),
kind: StrKind::Synthesized,
has_escape: false,
span: DUMMY_SP,
}));
}
_ => return node,
}
}
node
}
_ => node,
}
}
}