forked from parcel-bundler/parcel
/
dependency_collector.rs
1372 lines (1243 loc) Β· 42.5 KB
/
dependency_collector.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use path_slash::PathBufExt;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::Path;
use serde::{Deserialize, Serialize};
use swc_atoms::JsWord;
use swc_common::{Mark, SourceMap, Span, DUMMY_SP};
use swc_ecmascript::ast::{self, Callee, Id, MemberProp};
use swc_ecmascript::visit::{Fold, FoldWith};
use crate::fold_member_expr_skip_prop;
use crate::utils::*;
use crate::Config;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
macro_rules! hash {
($str:expr) => {{
let mut hasher = DefaultHasher::new();
$str.hash(&mut hasher);
hasher.finish()
}};
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum DependencyKind {
Import,
Export,
DynamicImport,
Require,
WebWorker,
ServiceWorker,
Worklet,
Url,
File,
}
impl fmt::Display for DependencyKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DependencyDescriptor {
pub kind: DependencyKind,
pub loc: SourceLocation,
/// The text specifier associated with the import/export statement.
pub specifier: swc_atoms::JsWord,
pub attributes: Option<HashMap<swc_atoms::JsWord, bool>>,
pub is_optional: bool,
pub is_helper: bool,
pub source_type: Option<SourceType>,
pub placeholder: Option<String>,
}
/// This pass collects dependencies in a module and compiles references as needed to work with Parcel's JSRuntime.
pub fn dependency_collector<'a>(
source_map: &'a SourceMap,
items: &'a mut Vec<DependencyDescriptor>,
decls: &'a HashSet<Id>,
ignore_mark: swc_common::Mark,
unresolved_mark: swc_common::Mark,
config: &'a Config,
diagnostics: &'a mut Vec<Diagnostic>,
) -> impl Fold + 'a {
DependencyCollector {
source_map,
items,
in_try: false,
in_promise: false,
require_node: None,
decls,
ignore_mark,
unresolved_mark,
config,
diagnostics,
import_meta: None,
}
}
struct DependencyCollector<'a> {
source_map: &'a SourceMap,
items: &'a mut Vec<DependencyDescriptor>,
in_try: bool,
in_promise: bool,
require_node: Option<ast::CallExpr>,
decls: &'a HashSet<Id>,
ignore_mark: swc_common::Mark,
unresolved_mark: swc_common::Mark,
config: &'a Config,
diagnostics: &'a mut Vec<Diagnostic>,
import_meta: Option<ast::VarDecl>,
}
impl<'a> DependencyCollector<'a> {
fn add_dependency(
&mut self,
specifier: JsWord,
span: swc_common::Span,
kind: DependencyKind,
attributes: Option<HashMap<swc_atoms::JsWord, bool>>,
is_optional: bool,
source_type: SourceType,
) -> Option<JsWord> {
// For normal imports/requires, the specifier will remain unchanged.
// For other types of dependencies, the specifier will be changed to a hash
// that also contains the dependency kind. This way, multiple kinds of dependencies
// to the same specifier can be used within the same file.
let placeholder = match kind {
DependencyKind::Import | DependencyKind::Export | DependencyKind::Require => None,
_ => Some(format!(
"{:x}",
hash!(format!("{}:{}:{}", self.config.filename, specifier, kind))
)),
};
self.items.push(DependencyDescriptor {
kind,
loc: SourceLocation::from(self.source_map, span),
specifier,
attributes,
is_optional,
is_helper: span.is_dummy(),
source_type: Some(source_type),
placeholder: placeholder.clone(),
});
placeholder.map(|p| p.into())
}
fn add_url_dependency(
&mut self,
specifier: JsWord,
span: swc_common::Span,
kind: DependencyKind,
source_type: SourceType,
) -> ast::Expr {
// If not a library, replace with a require call pointing to a runtime that will resolve the url dynamically.
if !self.config.is_library {
let placeholder =
self.add_dependency(specifier.clone(), span, kind, None, false, source_type);
let specifier = if let Some(placeholder) = placeholder {
placeholder
} else {
specifier
};
return ast::Expr::Call(self.create_require(specifier));
}
// For library builds, we need to create something that can be statically analyzed by another bundler,
// so rather than replacing with a require call that is resolved by a runtime, replace with a `new URL`
// call with a placeholder for the relative path to be replaced during packaging.
let placeholder = format!(
"{:x}",
hash!(format!(
"parcel_url:{}:{}:{}",
self.config.filename, specifier, kind
))
);
self.items.push(DependencyDescriptor {
kind,
loc: SourceLocation::from(self.source_map, span),
specifier,
attributes: None,
is_optional: false,
is_helper: span.is_dummy(),
source_type: Some(source_type),
placeholder: Some(placeholder.clone()),
});
create_url_constructor(
ast::Expr::Lit(ast::Lit::Str(placeholder.into())),
self.config.is_esm_output,
)
}
fn create_require(&mut self, specifier: JsWord) -> ast::CallExpr {
let mut res = create_require(specifier);
// For scripts, we replace with __parcel__require__, which is later replaced
// by a real parcelRequire of the resolved asset in the packager.
if self.config.source_type == SourceType::Script {
res.callee = ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Ident::new(
"__parcel__require__".into(),
DUMMY_SP,
))));
}
res
}
fn add_script_error(&mut self, span: Span) {
// Only add the diagnostic for imports/exports in scripts once.
if self.diagnostics.iter().any(|d| d.message == "SCRIPT_ERROR") {
return;
}
self.diagnostics.push(Diagnostic {
message: "SCRIPT_ERROR".to_string(),
code_highlights: Some(vec![CodeHighlight {
message: None,
loc: SourceLocation::from(self.source_map, span),
}]),
hints: None,
show_environment: true,
severity: DiagnosticSeverity::Error,
documentation_url: Some(String::from(
"https://parceljs.org/languages/javascript/#classic-scripts",
)),
});
}
}
fn rewrite_require_specifier(node: ast::CallExpr) -> ast::CallExpr {
if let Some(arg) = node.args.get(0) {
if let Some((value, _)) = match_str(&*arg.expr) {
if value.starts_with("node:") {
// create_require will take care of replacing the node: prefix...
return create_require(value);
}
}
}
node
}
impl<'a> Fold for DependencyCollector<'a> {
fn fold_module(&mut self, node: ast::Module) -> ast::Module {
let mut res = node.fold_children_with(self);
if let Some(decl) = self.import_meta.take() {
res.body.insert(
0,
ast::ModuleItem::Stmt(ast::Stmt::Decl(ast::Decl::Var(decl))),
);
}
res
}
fn fold_module_decl(&mut self, node: ast::ModuleDecl) -> ast::ModuleDecl {
// If an import or export is seen within a script, flag it to throw an error from JS.
if self.config.source_type == SourceType::Script {
match node {
ast::ModuleDecl::Import(ast::ImportDecl { span, .. })
| ast::ModuleDecl::ExportAll(ast::ExportAll { span, .. })
| ast::ModuleDecl::ExportDecl(ast::ExportDecl { span, .. })
| ast::ModuleDecl::ExportDefaultDecl(ast::ExportDefaultDecl { span, .. })
| ast::ModuleDecl::ExportDefaultExpr(ast::ExportDefaultExpr { span, .. })
| ast::ModuleDecl::ExportNamed(ast::NamedExport { span, .. }) => {
self.add_script_error(span)
}
_ => {}
}
return node;
}
node.fold_children_with(self)
}
fn fold_import_decl(&mut self, node: ast::ImportDecl) -> ast::ImportDecl {
if node.type_only {
return node;
}
self.add_dependency(
node.src.value.clone(),
node.src.span,
DependencyKind::Import,
None,
false,
self.config.source_type,
);
node
}
fn fold_named_export(&mut self, node: ast::NamedExport) -> ast::NamedExport {
if let Some(src) = &node.src {
if node.type_only {
return node;
}
self.add_dependency(
src.value.clone(),
src.span,
DependencyKind::Export,
None,
false,
self.config.source_type,
);
}
node
}
fn fold_export_all(&mut self, node: ast::ExportAll) -> ast::ExportAll {
self.add_dependency(
node.src.value.clone(),
node.src.span,
DependencyKind::Export,
None,
false,
self.config.source_type,
);
node
}
fn fold_try_stmt(&mut self, node: ast::TryStmt) -> ast::TryStmt {
// Track if we're inside a try block to mark dependencies as optional.
self.in_try = true;
let block = node.block.fold_with(self);
self.in_try = false;
let handler = node.handler.map(|handler| handler.fold_with(self));
let finalizer = node.finalizer.map(|finalizer| finalizer.fold_with(self));
ast::TryStmt {
span: node.span,
block,
handler,
finalizer,
}
}
fn fold_call_expr(&mut self, node: ast::CallExpr) -> ast::CallExpr {
use ast::{Expr::*, Ident};
let kind = match &node.callee {
Callee::Import(_) => DependencyKind::DynamicImport,
Callee::Expr(expr) => {
match &**expr {
Ident(ident) => {
// Bail if defined in scope
if self.decls.contains(&ident.to_id()) {
return node.fold_children_with(self);
}
match ident.sym.to_string().as_str() {
"require" => {
if self.in_promise {
DependencyKind::DynamicImport
} else {
DependencyKind::Require
}
}
"importScripts" => {
if self.config.is_worker {
let (msg, span) = if self.config.source_type == SourceType::Script {
// Ignore if argument is not a string literal.
let span = if let Some(ast::ExprOrSpread { expr, .. }) = node.args.get(0) {
match &**expr {
Lit(ast::Lit::Str(ast::Str { value, span, .. })) => {
// Ignore absolute URLs.
if value.starts_with("http:")
|| value.starts_with("https:")
|| value.starts_with("//")
{
return node.fold_children_with(self);
}
span
}
_ => {
return node.fold_children_with(self);
}
}
} else {
return node.fold_children_with(self);
};
(
"Argument to importScripts() must be a fully qualified URL.",
*span,
)
} else {
(
"importScripts() is not supported in module workers.",
node.span,
)
};
self.diagnostics.push(Diagnostic {
message: msg.to_string(),
code_highlights: Some(vec![CodeHighlight {
message: None,
loc: SourceLocation::from(self.source_map, span),
}]),
hints: Some(vec![String::from(
"Use a static `import`, or dynamic `import()` instead.",
)]),
show_environment: self.config.source_type == SourceType::Script,
severity: DiagnosticSeverity::Error,
documentation_url: Some(String::from(
"https://parceljs.org/languages/javascript/#classic-script-workers",
)),
});
}
return node.fold_children_with(self);
}
"__parcel__require__" => {
let mut call = node.fold_children_with(self);
call.callee = ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Ident::new(
"require".into(),
DUMMY_SP.apply_mark(self.ignore_mark),
))));
return call;
}
"__parcel__import__" => {
let mut call = node.fold_children_with(self);
call.callee = ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Ident::new(
"import".into(),
DUMMY_SP.apply_mark(self.ignore_mark),
))));
return call;
}
"__parcel__importScripts__" => {
let mut call = node.fold_children_with(self);
call.callee = ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Ident::new(
"importScripts".into(),
DUMMY_SP.apply_mark(self.ignore_mark),
))));
return call;
}
_ => return node.fold_children_with(self),
}
}
Member(member) => {
if match_member_expr(member, vec!["module", "require"], self.decls) {
DependencyKind::Require
} else if self.config.is_browser
&& match_member_expr(
member,
vec!["navigator", "serviceWorker", "register"],
self.decls,
)
{
DependencyKind::ServiceWorker
} else if self.config.is_browser
&& match_member_expr(member, vec!["CSS", "paintWorklet", "addModule"], self.decls)
{
DependencyKind::Worklet
} else {
let was_in_promise = self.in_promise;
// Match compiled dynamic imports (Parcel)
// Promise.resolve(require('foo'))
if match_member_expr(member, vec!["Promise", "resolve"], self.decls) {
if let Some(expr) = node.args.get(0) {
if match_require(&*expr.expr, self.decls, Mark::fresh(Mark::root())).is_some() {
self.in_promise = true;
let node = node.fold_children_with(self);
self.in_promise = was_in_promise;
return node;
}
}
}
// Match compiled dynamic imports (TypeScript)
// Promise.resolve().then(() => require('foo'))
// Promise.resolve().then(() => { return require('foo') })
// Promise.resolve().then(function () { return require('foo') })
// but not
// Promise.resolve(require('foo'))
if let Call(call) = &*member.obj {
if let Callee::Expr(e) = &call.callee {
if let Member(m) = &**e {
if match_member_expr(m, vec!["Promise", "resolve"], self.decls) &&
// Make sure the arglist is empty.
// I.e. do not proceed with the below unless Promise.resolve has an empty arglist
// because build_promise_chain() will not work in this case.
call.args.is_empty()
{
if let MemberProp::Ident(id) = &member.prop {
if id.sym.to_string().as_str() == "then" {
if let Some(arg) = node.args.get(0) {
match &*arg.expr {
Fn(_) | Arrow(_) => {
self.in_promise = true;
let node =
swc_ecmascript::visit::fold_call_expr(self, node.clone());
self.in_promise = was_in_promise;
// Transform Promise.resolve().then(() => __importStar(require('foo')))
// => Promise.resolve().then(() => require('foo')).then(res => __importStar(res))
if let Some(require_node) = self.require_node.clone() {
self.require_node = None;
return build_promise_chain(node, require_node);
}
}
_ => {}
}
}
}
}
}
}
}
}
return node.fold_children_with(self);
}
}
_ => return node.fold_children_with(self),
}
}
_ => return node.fold_children_with(self),
};
// Convert import attributes for dynamic import
let mut attributes = None;
if kind == DependencyKind::DynamicImport {
if let Some(arg) = node.args.get(1) {
if let Object(arg) = &*arg.expr {
let mut attrs = HashMap::new();
for key in &arg.props {
let prop = match key {
ast::PropOrSpread::Prop(prop) => prop,
_ => continue,
};
let kv = match &**prop {
ast::Prop::KeyValue(kv) => kv,
_ => continue,
};
let k = match &kv.key {
ast::PropName::Ident(Ident { sym, .. })
| ast::PropName::Str(ast::Str { value: sym, .. }) => sym.clone(),
_ => continue,
};
let v = match &*kv.value {
Lit(ast::Lit::Bool(ast::Bool { value, .. })) => *value,
_ => continue,
};
attrs.insert(k, v);
}
attributes = Some(attrs);
}
}
}
let node = if let Some(arg) = node.args.get(0) {
if kind == DependencyKind::ServiceWorker || kind == DependencyKind::Worklet {
let (source_type, opts) = if kind == DependencyKind::ServiceWorker {
match_worker_type(node.args.get(1))
} else {
// Worklets are always modules
(SourceType::Module, None)
};
let mut node = node.clone();
let (specifier, span) = if let Some(s) = self.match_new_url(&*arg.expr, self.decls) {
s
} else if let Lit(ast::Lit::Str(str_)) = &*arg.expr {
let (msg, docs) = if kind == DependencyKind::ServiceWorker {
(
"Registering service workers with a string literal is not supported.",
"https://parceljs.org/languages/javascript/#service-workers",
)
} else {
(
"Registering worklets with a string literal is not supported.",
"https://parceljs.org/languages/javascript/#worklets",
)
};
self.diagnostics.push(Diagnostic {
message: msg.to_string(),
code_highlights: Some(vec![CodeHighlight {
message: None,
loc: SourceLocation::from(self.source_map, str_.span),
}]),
hints: Some(vec![format!(
"Replace with: new URL('{}', import.meta.url)",
str_.value,
)]),
show_environment: false,
severity: DiagnosticSeverity::Error,
documentation_url: Some(String::from(docs)),
});
return node;
} else {
return node;
};
node.args[0].expr = Box::new(self.add_url_dependency(specifier, span, kind, source_type));
match opts {
Some(opts) => {
node.args[1] = opts;
}
None => {
node.args.truncate(1);
}
}
return node;
}
if let Some((specifier, span)) = match_str(&*arg.expr) {
// require() calls aren't allowed in scripts, flag as an error.
if kind == DependencyKind::Require && self.config.source_type == SourceType::Script {
self.add_script_error(node.span);
return node;
}
let placeholder = self.add_dependency(
specifier,
span,
kind.clone(),
attributes,
kind == DependencyKind::Require && self.in_try,
self.config.source_type,
);
if let Some(placeholder) = placeholder {
let mut node = node.clone();
node.args[0].expr = Box::new(ast::Expr::Lit(ast::Lit::Str(ast::Str {
value: placeholder,
span,
raw: None,
})));
node
} else {
node
}
} else {
node
}
} else {
node
};
// Replace import() with require()
if kind == DependencyKind::DynamicImport {
let mut call = node;
if !self.config.scope_hoist {
let name = match &self.config.source_type {
SourceType::Module => "require",
SourceType::Script => "__parcel__require__",
};
call.callee = ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Ident::new(
name.into(),
DUMMY_SP,
))));
}
// Drop import attributes
call.args.truncate(1);
// Track the returned require call to be replaced with a promise chain.
let rewritten_call = rewrite_require_specifier(call);
self.require_node = Some(rewritten_call.clone());
rewritten_call
} else if kind == DependencyKind::Require {
// Don't continue traversing so that the `require` isn't replaced with undefined
rewrite_require_specifier(node)
} else {
node.fold_children_with(self)
}
}
fn fold_unary_expr(&mut self, node: ast::UnaryExpr) -> ast::UnaryExpr {
// Don't traverse `typeof require` further to not replace `require` with undefined
if let ast::UnaryExpr {
op: ast::UnaryOp::TypeOf,
arg,
..
} = &node
{
if let ast::Expr::Ident(ast::Ident { sym, .. }) = &**arg {
if sym == &js_word!("require") && !self.decls.contains(&(sym.clone(), node.span.ctxt())) {
return node;
}
}
}
node.fold_children_with(self)
}
fn fold_new_expr(&mut self, node: ast::NewExpr) -> ast::NewExpr {
use ast::Expr::*;
let matched = match &*node.callee {
Ident(id) => {
match &id.sym {
&js_word!("Worker") | &js_word!("SharedWorker") => {
// Bail if defined in scope
self.config.is_browser && !self.decls.contains(&id.to_id())
}
&js_word!("Promise") => {
// Match requires inside promises (e.g. Rollup compiled dynamic imports)
// new Promise(resolve => resolve(require('foo')))
// new Promise(resolve => { resolve(require('foo')) })
// new Promise(function (resolve) { resolve(require('foo')) })
return self.fold_new_promise(node);
}
sym => {
if sym == "__parcel__URL__" {
// new __parcel__URL__(url) -> new URL(url, import.meta.url)
if let Some(args) = &node.args {
if let ast::Expr::New(new) = create_url_constructor(
*args[0].expr.clone().fold_with(self),
self.config.is_esm_output,
) {
return new;
}
}
unreachable!();
}
false
}
}
}
_ => false,
};
if !matched {
return node.fold_children_with(self);
}
if let Some(args) = &node.args {
if !args.is_empty() {
let (specifier, span) = if let Some(s) = self.match_new_url(&*args[0].expr, self.decls) {
s
} else if let Lit(ast::Lit::Str(str_)) = &*args[0].expr {
let constructor = match &*node.callee {
Ident(id) => id.sym.to_string(),
_ => "Worker".to_string(),
};
self.diagnostics.push(Diagnostic {
message: format!(
"Constructing a {} with a string literal is not supported.",
constructor
),
code_highlights: Some(vec![CodeHighlight {
message: None,
loc: SourceLocation::from(self.source_map, str_.span),
}]),
hints: Some(vec![format!(
"Replace with: new URL('{}', import.meta.url)",
str_.value
)]),
show_environment: false,
severity: DiagnosticSeverity::Error,
documentation_url: Some(String::from(
"https://parceljs.org/languages/javascript/#web-workers",
)),
});
return node;
} else {
return node;
};
let (source_type, opts) = match_worker_type(args.get(1));
let placeholder =
self.add_url_dependency(specifier, span, DependencyKind::WebWorker, source_type);
// Replace argument with a require call to resolve the URL at runtime.
let mut node = node.clone();
if let Some(mut args) = node.args.clone() {
args[0].expr = Box::new(placeholder);
// If module workers aren't supported natively, remove the `type: 'module'` option.
// If no other options are passed, remove the argument entirely.
if !self.config.supports_module_workers {
match opts {
None => {
args.truncate(1);
}
Some(opts) => {
args[1] = opts;
}
}
}
node.args = Some(args);
}
return node;
}
}
node.fold_children_with(self)
}
fold_member_expr_skip_prop! {}
fn fold_expr(&mut self, node: ast::Expr) -> ast::Expr {
use ast::*;
if self.is_import_meta(&node) {
return self.get_import_meta();
}
if self.is_import_meta_url(&node) {
return self.get_import_meta_url();
}
if let Some((specifier, span)) = self.match_new_url(&node, self.decls) {
let url = self.add_url_dependency(
specifier,
span,
DependencyKind::Url,
self.config.source_type,
);
// If this is a library, we will already have a URL object. Otherwise, we need to
// construct one from the string returned by the JSRuntime.
if !self.config.is_library {
return Expr::New(NewExpr {
span: DUMMY_SP,
callee: Box::new(Expr::Ident(Ident::new(js_word!("URL"), DUMMY_SP))),
args: Some(vec![ExprOrSpread {
expr: Box::new(url),
spread: None,
}]),
type_args: None,
});
}
return url;
}
let is_require = match &node {
Expr::Ident(Ident { sym, span, .. }) => {
// Free `require` -> undefined
sym == &js_word!("require") && !self.decls.contains(&(sym.clone(), span.ctxt()))
}
Expr::Member(MemberExpr { obj: expr, .. }) => {
// e.g. `require.extensions` -> undefined
if let Expr::Ident(Ident { sym, span, .. }) = &**expr {
sym == &js_word!("require") && !self.decls.contains(&(sym.clone(), span.ctxt()))
} else {
false
}
}
_ => false,
};
if is_require {
return ast::Expr::Ident(get_undefined_ident(self.unresolved_mark));
}
node.fold_children_with(self)
}
}
impl<'a> DependencyCollector<'a> {
fn fold_new_promise(&mut self, node: ast::NewExpr) -> ast::NewExpr {
use ast::Expr::*;
// Match requires inside promises (e.g. Rollup compiled dynamic imports)
// new Promise(resolve => resolve(require('foo')))
// new Promise(resolve => { resolve(require('foo')) })
// new Promise(function (resolve) { resolve(require('foo')) })
// new Promise(function (resolve) { return resolve(require('foo')) })
if let Some(args) = &node.args {
if let Some(arg) = args.get(0) {
let (resolve, expr) = match &*arg.expr {
Fn(f) => {
let param = f.function.params.get(0).map(|param| ¶m.pat);
let body = if let Some(body) = &f.function.body {
self.match_block_stmt_expr(body)
} else {
None
};
(param, body)
}
Arrow(f) => {
let param = f.params.get(0);
let body = match &f.body {
ast::BlockStmtOrExpr::Expr(expr) => Some(&**expr),
ast::BlockStmtOrExpr::BlockStmt(block) => self.match_block_stmt_expr(block),
};
(param, body)
}
_ => (None, None),
};
let resolve_id = match resolve {
Some(ast::Pat::Ident(id)) => id.to_id(),
_ => return node.fold_children_with(self),
};
if let Some(ast::Expr::Call(call)) = expr {
if let ast::Callee::Expr(callee) = &call.callee {
if let ast::Expr::Ident(id) = &**callee {
if id.to_id() == resolve_id {
if let Some(arg) = call.args.get(0) {
if match_require(&*arg.expr, self.decls, Mark::fresh(Mark::root())).is_some() {
let was_in_promise = self.in_promise;
self.in_promise = true;
let node = node.fold_children_with(self);
self.in_promise = was_in_promise;
return node;
}
}
}
}
}
}
}
}
node.fold_children_with(self)
}
fn match_block_stmt_expr<'x>(&self, block: &'x ast::BlockStmt) -> Option<&'x ast::Expr> {
match block.stmts.last() {
Some(ast::Stmt::Expr(ast::ExprStmt { expr, .. })) => Some(&**expr),
Some(ast::Stmt::Return(ast::ReturnStmt { arg, .. })) => {
if let Some(arg) = arg {
Some(&**arg)
} else {
None
}
}
_ => None,
}
}
}
// If the `require` call is not immediately returned (e.g. wrapped in another function),
// then transform the AST to create a promise chain so that the require is by itself.
// This is because the require will return a promise rather than the module synchronously.
// For example, TypeScript generates the following with the esModuleInterop flag:
// Promise.resolve().then(() => __importStar(require('./foo')));
// This is transformed into:
// Promise.resolve().then(() => require('./foo')).then(res => __importStar(res));
fn build_promise_chain(node: ast::CallExpr, require_node: ast::CallExpr) -> ast::CallExpr {
let mut transformer = PromiseTransformer {
require_node: Some(require_node),
};
let node = node.fold_with(&mut transformer);
if let Some(require_node) = &transformer.require_node {
if let Some(f) = node.args.get(0) {
// Add `res` as an argument to the original function
let f = match &*f.expr {
ast::Expr::Fn(f) => {
let mut f = f.clone();
f.function.params.insert(
0,
ast::Param {
pat: ast::Pat::Ident(ast::BindingIdent::from(ast::Ident::new(
"res".into(),
DUMMY_SP,
))),
decorators: vec![],
span: DUMMY_SP,
},
);
ast::Expr::Fn(f)
}
ast::Expr::Arrow(f) => {
let mut f = f.clone();
f.params.insert(
0,
ast::Pat::Ident(ast::BindingIdent::from(ast::Ident::new(
"res".into(),
DUMMY_SP,
))),
);
ast::Expr::Arrow(f)
}
_ => return node,
};
return ast::CallExpr {
callee: ast::Callee::Expr(Box::new(ast::Expr::Member(ast::MemberExpr {
span: DUMMY_SP,
obj: (Box::new(ast::Expr::Call(ast::CallExpr {
callee: node.callee,
args: vec![ast::ExprOrSpread {
expr: Box::new(ast::Expr::Fn(ast::FnExpr {
ident: None,
function: ast::Function {
body: Some(ast::BlockStmt {
span: DUMMY_SP,
stmts: vec![ast::Stmt::Return(ast::ReturnStmt {
span: DUMMY_SP,
arg: Some(Box::new(ast::Expr::Call(require_node.clone()))),
})],
}),
params: vec![],
decorators: vec![],
is_async: false,
is_generator: false,
return_type: None,
type_params: None,
span: DUMMY_SP,
},
})),
spread: None,
}],
span: DUMMY_SP,
type_args: None,
}))),
prop: MemberProp::Ident(ast::Ident::new("then".into(), DUMMY_SP)),