-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
Copy pathlib.rs
1109 lines (1013 loc) · 35.5 KB
/
lib.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
// Needed for swc visit_ macros
#![allow(non_local_definitions)]
#![feature(box_patterns)]
#![feature(min_specialization)]
#![feature(iter_intersperse)]
#![feature(int_roundings)]
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![recursion_limit = "256"]
pub mod analyzer;
pub mod annotations;
pub mod async_chunk;
pub mod chunk;
pub mod code_gen;
mod errors;
pub mod magic_identifier;
pub mod manifest;
pub mod minify;
pub mod parse;
mod path_visitor;
pub mod references;
pub mod runtime_functions;
pub mod side_effect_optimization;
pub(crate) mod special_cases;
pub(crate) mod static_code;
mod swc_comments;
pub mod text;
pub(crate) mod transform;
pub mod tree_shake;
pub mod typescript;
pub mod utils;
pub mod webpack;
pub mod worker_chunk;
use std::{
fmt::{Display, Formatter},
mem::take,
sync::Arc,
};
use anyhow::Result;
use chunk::EcmascriptChunkItem;
use code_gen::{CodeGeneration, CodeGenerationHoistedStmt};
use either::Either;
use parse::{parse, ParseResult};
use path_visitor::ApplyVisitors;
use references::esm::UrlRewriteBehavior;
pub use references::{AnalyzeEcmascriptModuleResult, TURBOPACK_HELPER};
use serde::{Deserialize, Serialize};
pub use static_code::StaticEcmascriptCode;
use swc_core::{
common::{comments::Comments, util::take::Take, Globals, Mark, GLOBALS},
ecma::{
ast::{self, ModuleItem, Program, Script},
codegen::{text_writer::JsWriter, Emitter},
visit::{VisitMutWith, VisitMutWithAstPath},
},
};
use tracing::Instrument;
pub use transform::{
CustomTransformer, EcmascriptInputTransform, EcmascriptInputTransforms, TransformContext,
TransformPlugin, UnsupportedServerActionIssue,
};
use turbo_rcstr::RcStr;
use turbo_tasks::{
trace::TraceRawVcs, FxIndexMap, NonLocalValue, ReadRef, ResolvedVc, TaskInput, TryJoinIterExt,
Value, ValueToString, Vc,
};
use turbo_tasks_fs::{glob::Glob, rope::Rope, FileJsonContent, FileSystemPath};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{
AsyncModuleInfo, ChunkItem, ChunkType, ChunkableModule, ChunkingContext, EvaluatableAsset,
},
compile_time_info::CompileTimeInfo,
context::AssetContext,
ident::AssetIdent,
module::{Module, OptionModule},
module_graph::ModuleGraph,
reference::ModuleReferences,
reference_type::InnerAssets,
resolve::{
find_context_file, origin::ResolveOrigin, package_json, parse::Request,
FindContextFileResult,
},
source::Source,
source_map::OptionStringifiedSourceMap,
};
// TODO remove this
pub use turbopack_resolve::ecmascript as resolve;
use self::chunk::{EcmascriptChunkItemContent, EcmascriptChunkType, EcmascriptExports};
use crate::{
chunk::{placeable::is_marked_as_side_effect_free, EcmascriptChunkPlaceable},
code_gen::CodeGens,
parse::generate_js_source_map,
references::{
analyse_ecmascript_module, async_module::OptionAsyncModule, esm::base::EsmAssetReferences,
},
transform::remove_shebang,
};
#[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Hash, Debug, Clone, Copy, Default, TaskInput)]
pub enum SpecifiedModuleType {
#[default]
Automatic,
CommonJs,
EcmaScript,
}
#[derive(
PartialOrd,
Ord,
PartialEq,
Eq,
Hash,
Debug,
Clone,
Copy,
Default,
Serialize,
Deserialize,
TraceRawVcs,
NonLocalValue,
)]
#[serde(rename_all = "kebab-case")]
pub enum TreeShakingMode {
#[default]
ModuleFragments,
ReexportsOnly,
}
#[turbo_tasks::value(transparent)]
pub struct OptionTreeShaking(pub Option<TreeShakingMode>);
#[turbo_tasks::value(shared, serialization = "auto_for_input")]
#[derive(Hash, Debug, Default, Copy, Clone)]
pub struct EcmascriptOptions {
pub refresh: bool,
/// variant of tree shaking to use
pub tree_shaking_mode: Option<TreeShakingMode>,
/// module is forced to a specific type (happens e. g. for .cjs and .mjs)
pub specified_module_type: SpecifiedModuleType,
/// Determines how to treat `new URL(...)` rewrites.
/// This allows to construct url depends on the different building context,
/// e.g. SSR, CSR, or Node.js.
pub url_rewrite_behavior: Option<UrlRewriteBehavior>,
/// External imports should used `__turbopack_import__` instead of
/// `__turbopack_require__` and become async module references.
pub import_externals: bool,
/// Ignore very dynamic requests which doesn't have any static known part.
/// If false, they will reference the whole directory. If true, they won't
/// reference anything and lead to an runtime error instead.
pub ignore_dynamic_requests: bool,
/// If true, it reads a sourceMappingURL comment from the end of the file,
/// reads and generates a source map.
pub extract_source_map: bool,
/// If true, it stores the last successful parse result in state and keeps using it when
/// parsing fails. This is useful to keep the module graph structure intact when syntax errors
/// are temporarily introduced.
pub keep_last_successful_parse: bool,
}
#[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Hash, Debug, Copy, Clone)]
pub enum EcmascriptModuleAssetType {
/// Module with EcmaScript code
Ecmascript,
/// Module with TypeScript code without types
Typescript {
// parse JSX syntax.
tsx: bool,
// follow references to imported types.
analyze_types: bool,
},
/// Module with TypeScript declaration code
TypescriptDeclaration,
}
impl Display for EcmascriptModuleAssetType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
EcmascriptModuleAssetType::Ecmascript => write!(f, "ecmascript"),
EcmascriptModuleAssetType::Typescript { tsx, analyze_types } => {
write!(f, "typescript")?;
if *tsx {
write!(f, "with JSX")?;
}
if *analyze_types {
write!(f, "with types")?;
}
Ok(())
}
EcmascriptModuleAssetType::TypescriptDeclaration => write!(f, "typescript declaration"),
}
}
}
#[turbo_tasks::function]
fn modifier() -> Vc<RcStr> {
Vc::cell("ecmascript".into())
}
#[derive(Clone)]
pub struct EcmascriptModuleAssetBuilder {
source: ResolvedVc<Box<dyn Source>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
ty: EcmascriptModuleAssetType,
transforms: ResolvedVc<EcmascriptInputTransforms>,
options: ResolvedVc<EcmascriptOptions>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
inner_assets: Option<ResolvedVc<InnerAssets>>,
}
impl EcmascriptModuleAssetBuilder {
pub fn with_inner_assets(mut self, inner_assets: ResolvedVc<InnerAssets>) -> Self {
self.inner_assets = Some(inner_assets);
self
}
pub fn with_type(mut self, ty: EcmascriptModuleAssetType) -> Self {
self.ty = ty;
self
}
pub fn build(self) -> Vc<EcmascriptModuleAsset> {
if let Some(inner_assets) = self.inner_assets {
EcmascriptModuleAsset::new_with_inner_assets(
*self.source,
*self.asset_context,
Value::new(self.ty),
*self.transforms,
*self.options,
*self.compile_time_info,
*inner_assets,
)
} else {
EcmascriptModuleAsset::new(
*self.source,
*self.asset_context,
Value::new(self.ty),
*self.transforms,
*self.options,
*self.compile_time_info,
)
}
}
}
#[turbo_tasks::value]
pub struct EcmascriptModuleAsset {
pub source: ResolvedVc<Box<dyn Source>>,
pub asset_context: ResolvedVc<Box<dyn AssetContext>>,
pub ty: EcmascriptModuleAssetType,
pub transforms: ResolvedVc<EcmascriptInputTransforms>,
pub options: ResolvedVc<EcmascriptOptions>,
pub compile_time_info: ResolvedVc<CompileTimeInfo>,
pub inner_assets: Option<ResolvedVc<InnerAssets>>,
#[turbo_tasks(debug_ignore)]
last_successful_parse: turbo_tasks::TransientState<ReadRef<ParseResult>>,
}
impl core::fmt::Debug for EcmascriptModuleAsset {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("EcmascriptModuleAsset")
.field("source", &self.source)
.field("asset_context", &self.asset_context)
.field("ty", &self.ty)
.field("transforms", &self.transforms)
.field("options", &self.options)
.field("compile_time_info", &self.compile_time_info)
.field("inner_assets", &self.inner_assets)
.finish()
}
}
#[turbo_tasks::value_trait]
pub trait EcmascriptParsable {
fn failsafe_parse(self: Vc<Self>) -> Result<Vc<ParseResult>>;
fn parse_original(self: Vc<Self>) -> Result<Vc<ParseResult>>;
fn ty(self: Vc<Self>) -> Result<Vc<EcmascriptModuleAssetType>>;
}
#[turbo_tasks::value_trait]
pub trait EcmascriptAnalyzable {
fn analyze(self: Vc<Self>) -> Vc<AnalyzeEcmascriptModuleResult>;
/// Generates module contents without an analysis pass. This is useful for
/// transforming code that is not a module, e.g. runtime code.
async fn module_content_without_analysis(
self: Vc<Self>,
generate_source_map: bool,
) -> Result<Vc<EcmascriptModuleContent>>;
async fn module_content(
self: Vc<Self>,
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<EcmascriptModuleContent>>;
}
impl EcmascriptModuleAsset {
pub fn builder(
source: ResolvedVc<Box<dyn Source>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
transforms: ResolvedVc<EcmascriptInputTransforms>,
options: ResolvedVc<EcmascriptOptions>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
) -> EcmascriptModuleAssetBuilder {
EcmascriptModuleAssetBuilder {
source,
asset_context,
ty: EcmascriptModuleAssetType::Ecmascript,
transforms,
options,
compile_time_info,
inner_assets: None,
}
}
}
#[turbo_tasks::value]
#[derive(Copy, Clone)]
pub(crate) struct ModuleTypeResult {
pub module_type: SpecifiedModuleType,
pub referenced_package_json: Option<ResolvedVc<FileSystemPath>>,
}
#[turbo_tasks::value_impl]
impl ModuleTypeResult {
#[turbo_tasks::function]
fn new(module_type: SpecifiedModuleType) -> Vc<Self> {
Self::cell(ModuleTypeResult {
module_type,
referenced_package_json: None,
})
}
#[turbo_tasks::function]
fn new_with_package_json(
module_type: SpecifiedModuleType,
package_json: ResolvedVc<FileSystemPath>,
) -> Vc<Self> {
Self::cell(ModuleTypeResult {
module_type,
referenced_package_json: Some(package_json),
})
}
}
#[turbo_tasks::value_impl]
impl EcmascriptParsable for EcmascriptModuleAsset {
#[turbo_tasks::function]
async fn failsafe_parse(self: Vc<Self>) -> Result<Vc<ParseResult>> {
let real_result = self.parse();
let this = self.await?;
if this.options.await?.keep_last_successful_parse {
let real_result_value = real_result.await?;
let result_value = if matches!(*real_result_value, ParseResult::Ok { .. }) {
this.last_successful_parse.set(real_result_value.clone());
real_result_value
} else {
let state_ref = this.last_successful_parse.get();
state_ref.as_ref().unwrap_or(&real_result_value).clone()
};
Ok(ReadRef::cell(result_value))
} else {
Ok(real_result)
}
}
#[turbo_tasks::function]
fn parse_original(self: Vc<Self>) -> Vc<ParseResult> {
self.failsafe_parse()
}
#[turbo_tasks::function]
fn ty(&self) -> Vc<EcmascriptModuleAssetType> {
self.ty.cell()
}
}
#[turbo_tasks::value_impl]
impl EcmascriptAnalyzable for EcmascriptModuleAsset {
#[turbo_tasks::function]
fn analyze(self: Vc<Self>) -> Vc<AnalyzeEcmascriptModuleResult> {
analyse_ecmascript_module(self, None)
}
/// Generates module contents without an analysis pass. This is useful for
/// transforming code that is not a module, e.g. runtime code.
#[turbo_tasks::function]
async fn module_content_without_analysis(
self: Vc<Self>,
generate_source_map: bool,
) -> Result<Vc<EcmascriptModuleContent>> {
let this = self.await?;
let parsed = self.parse();
Ok(EcmascriptModuleContent::new_without_analysis(
parsed,
self.ident(),
this.options.await?.specified_module_type,
generate_source_map,
))
}
#[turbo_tasks::function]
async fn module_content(
self: Vc<Self>,
module_graph: ResolvedVc<ModuleGraph>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
async_module_info: Option<ResolvedVc<AsyncModuleInfo>>,
) -> Result<Vc<EcmascriptModuleContent>> {
let parsed = self.parse().to_resolved().await?;
let analyze = self.analyze();
let analyze_ref = analyze.await?;
let module_type_result = *self.determine_module_type().await?;
let generate_source_map = *chunking_context
.reference_module_source_maps(Vc::upcast(self))
.await?;
Ok(EcmascriptModuleContent::new(
EcmascriptModuleContentOptions {
parsed,
ident: self.ident().to_resolved().await?,
specified_module_type: module_type_result.module_type,
module_graph,
chunking_context,
references: analyze.references().to_resolved().await?,
esm_references: analyze_ref.esm_references,
code_generation: analyze_ref.code_generation,
async_module: analyze_ref.async_module,
generate_source_map,
original_source_map: analyze_ref.source_map,
exports: analyze_ref.exports,
async_module_info,
},
))
}
}
#[turbo_tasks::function]
async fn determine_module_type_for_directory(
context_path: Vc<FileSystemPath>,
) -> Result<Vc<ModuleTypeResult>> {
let find_package_json =
find_context_file(context_path, package_json().resolve().await?).await?;
let FindContextFileResult::Found(package_json, _) = *find_package_json else {
return Ok(ModuleTypeResult::new(SpecifiedModuleType::Automatic));
};
// analysis.add_reference(PackageJsonReference::new(package_json));
if let FileJsonContent::Content(content) = &*package_json.read_json().await? {
if let Some(r#type) = content.get("type") {
return Ok(ModuleTypeResult::new_with_package_json(
match r#type.as_str() {
Some("module") => SpecifiedModuleType::EcmaScript,
Some("commonjs") => SpecifiedModuleType::CommonJs,
_ => SpecifiedModuleType::Automatic,
},
*package_json,
));
}
}
Ok(ModuleTypeResult::new_with_package_json(
SpecifiedModuleType::Automatic,
*package_json,
))
}
#[turbo_tasks::value_impl]
impl EcmascriptModuleAsset {
#[turbo_tasks::function]
pub fn new(
source: ResolvedVc<Box<dyn Source>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
ty: Value<EcmascriptModuleAssetType>,
transforms: ResolvedVc<EcmascriptInputTransforms>,
options: ResolvedVc<EcmascriptOptions>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
) -> Vc<Self> {
Self::cell(EcmascriptModuleAsset {
source,
asset_context,
ty: ty.into_value(),
transforms,
options,
compile_time_info,
inner_assets: None,
last_successful_parse: Default::default(),
})
}
#[turbo_tasks::function]
pub fn new_with_inner_assets(
source: ResolvedVc<Box<dyn Source>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
ty: Value<EcmascriptModuleAssetType>,
transforms: ResolvedVc<EcmascriptInputTransforms>,
options: ResolvedVc<EcmascriptOptions>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
inner_assets: ResolvedVc<InnerAssets>,
) -> Vc<Self> {
Self::cell(EcmascriptModuleAsset {
source,
asset_context,
ty: ty.into_value(),
transforms,
options,
compile_time_info,
inner_assets: Some(inner_assets),
last_successful_parse: Default::default(),
})
}
#[turbo_tasks::function]
pub fn source(&self) -> Vc<Box<dyn Source>> {
*self.source
}
#[turbo_tasks::function]
pub fn analyze(self: Vc<Self>) -> Vc<AnalyzeEcmascriptModuleResult> {
analyse_ecmascript_module(self, None)
}
#[turbo_tasks::function]
pub fn options(&self) -> Vc<EcmascriptOptions> {
*self.options
}
#[turbo_tasks::function]
pub fn parse(&self) -> Vc<ParseResult> {
parse(*self.source, Value::new(self.ty), *self.transforms)
}
}
impl EcmascriptModuleAsset {
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn determine_module_type(self: Vc<Self>) -> Result<ReadRef<ModuleTypeResult>> {
let this = self.await?;
match this.options.await?.specified_module_type {
SpecifiedModuleType::EcmaScript => {
return ModuleTypeResult::new(SpecifiedModuleType::EcmaScript).await
}
SpecifiedModuleType::CommonJs => {
return ModuleTypeResult::new(SpecifiedModuleType::CommonJs).await
}
SpecifiedModuleType::Automatic => {}
}
determine_module_type_for_directory(
self.origin_path()
.resolve()
.await?
.parent()
.resolve()
.await?,
)
.await
}
}
#[turbo_tasks::value_impl]
impl Module for EcmascriptModuleAsset {
#[turbo_tasks::function]
async fn ident(&self) -> Result<Vc<AssetIdent>> {
if let Some(inner_assets) = self.inner_assets {
let mut ident = self.source.ident().owned().await?;
for (name, asset) in inner_assets.await?.iter() {
ident.add_asset(
ResolvedVc::cell(name.to_string().into()),
asset.ident().to_resolved().await?,
);
}
ident.add_modifier(modifier().to_resolved().await?);
ident.layer = Some(self.asset_context.layer().to_resolved().await?);
Ok(AssetIdent::new(Value::new(ident)))
} else {
Ok(self
.source
.ident()
.with_modifier(modifier())
.with_layer(self.asset_context.layer()))
}
}
#[turbo_tasks::function]
async fn references(self: Vc<Self>) -> Result<Vc<ModuleReferences>> {
Ok(self.analyze().references())
}
#[turbo_tasks::function]
async fn is_self_async(self: Vc<Self>) -> Result<Vc<bool>> {
if let Some(async_module) = *self.get_async_module().await? {
Ok(async_module.is_self_async(self.references()))
} else {
Ok(Vc::cell(false))
}
}
}
#[turbo_tasks::value_impl]
impl Asset for EcmascriptModuleAsset {
#[turbo_tasks::function]
fn content(&self) -> Vc<AssetContent> {
self.source.content()
}
}
#[turbo_tasks::value_impl]
impl ChunkableModule for EcmascriptModuleAsset {
#[turbo_tasks::function]
fn as_chunk_item(
self: ResolvedVc<Self>,
module_graph: ResolvedVc<ModuleGraph>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
) -> Vc<Box<dyn ChunkItem>> {
Vc::upcast(ModuleChunkItem::cell(ModuleChunkItem {
module: self,
module_graph,
chunking_context,
}))
}
}
#[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for EcmascriptModuleAsset {
#[turbo_tasks::function]
async fn get_exports(self: Vc<Self>) -> Result<Vc<EcmascriptExports>> {
Ok(*self.analyze().await?.exports)
}
#[turbo_tasks::function]
async fn get_async_module(self: Vc<Self>) -> Result<Vc<OptionAsyncModule>> {
Ok(*self.analyze().await?.async_module)
}
#[turbo_tasks::function]
async fn is_marked_as_side_effect_free(
self: Vc<Self>,
side_effect_free_packages: Vc<Glob>,
) -> Result<Vc<bool>> {
// Check package.json first, so that we can skip parsing the module if it's marked that way.
let pkg_side_effect_free =
is_marked_as_side_effect_free(self.ident().path(), side_effect_free_packages);
Ok(if *pkg_side_effect_free.await? {
pkg_side_effect_free
} else {
Vc::cell(self.analyze().await?.has_side_effect_free_directive)
})
}
}
#[turbo_tasks::value_impl]
impl EvaluatableAsset for EcmascriptModuleAsset {}
#[turbo_tasks::value_impl]
impl ResolveOrigin for EcmascriptModuleAsset {
#[turbo_tasks::function]
fn origin_path(&self) -> Vc<FileSystemPath> {
self.source.ident().path()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
*self.asset_context
}
#[turbo_tasks::function]
async fn get_inner_asset(&self, request: Vc<Request>) -> Result<Vc<OptionModule>> {
Ok(Vc::cell(if let Some(inner_assets) = &self.inner_assets {
if let Some(request) = request.await?.request() {
inner_assets.await?.get(&request).copied()
} else {
None
}
} else {
None
}))
}
}
#[turbo_tasks::value]
struct ModuleChunkItem {
module: ResolvedVc<EcmascriptModuleAsset>,
module_graph: ResolvedVc<ModuleGraph>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
}
#[turbo_tasks::value_impl]
impl ChunkItem for ModuleChunkItem {
#[turbo_tasks::function]
fn asset_ident(&self) -> Vc<AssetIdent> {
self.module.ident()
}
#[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context)
}
#[turbo_tasks::function]
async fn ty(&self) -> Result<Vc<Box<dyn ChunkType>>> {
Ok(Vc::upcast(
Vc::<EcmascriptChunkType>::default().resolve().await?,
))
}
#[turbo_tasks::function]
fn module(&self) -> Vc<Box<dyn Module>> {
*ResolvedVc::upcast(self.module)
}
}
#[turbo_tasks::value_impl]
impl EcmascriptChunkItem for ModuleChunkItem {
#[turbo_tasks::function]
fn content(self: Vc<Self>) -> Vc<EcmascriptChunkItemContent> {
panic!("content() should not be called");
}
#[turbo_tasks::function]
async fn content_with_async_module_info(
self: Vc<Self>,
async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<EcmascriptChunkItemContent>> {
let this = self.await?;
let _span = tracing::info_span!(
"code generation",
module = self.asset_ident().to_string().await?.to_string()
)
.entered();
let async_module_options = this
.module
.get_async_module()
.module_options(async_module_info);
// TODO check if we need to pass async_module_info at all
let content = this.module.module_content(
*this.module_graph,
*this.chunking_context,
async_module_info,
);
Ok(EcmascriptChunkItemContent::new(
content,
*this.chunking_context,
this.module.options(),
async_module_options,
))
}
}
/// The transformed contents of an Ecmascript module.
#[turbo_tasks::value]
pub struct EcmascriptModuleContent {
pub inner_code: Rope,
pub source_map: Option<Rope>,
pub is_esm: bool,
// pub refresh: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TaskInput, TraceRawVcs)]
pub struct EcmascriptModuleContentOptions {
parsed: ResolvedVc<ParseResult>,
ident: ResolvedVc<AssetIdent>,
specified_module_type: SpecifiedModuleType,
module_graph: ResolvedVc<ModuleGraph>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
references: ResolvedVc<ModuleReferences>,
esm_references: ResolvedVc<EsmAssetReferences>,
code_generation: ResolvedVc<CodeGens>,
async_module: ResolvedVc<OptionAsyncModule>,
generate_source_map: bool,
original_source_map: ResolvedVc<OptionStringifiedSourceMap>,
exports: ResolvedVc<EcmascriptExports>,
async_module_info: Option<ResolvedVc<AsyncModuleInfo>>,
}
#[turbo_tasks::value_impl]
impl EcmascriptModuleContent {
/// Creates a new [`Vc<EcmascriptModuleContent>`].
#[turbo_tasks::function]
pub async fn new(input: EcmascriptModuleContentOptions) -> Result<Vc<Self>> {
let EcmascriptModuleContentOptions {
parsed,
ident,
specified_module_type,
module_graph,
chunking_context,
references,
esm_references,
code_generation,
async_module,
generate_source_map,
original_source_map,
exports,
async_module_info,
} = input;
let (esm_code_gens, additional_code_gens, code_gens) = async {
let additional_code_gens = [
if let Some(async_module) = &*async_module.await? {
Some(
async_module
.code_generation(
async_module_info.map(|info| *info),
*references,
*chunking_context,
)
.await?,
)
} else {
None
},
if let EcmascriptExports::EsmExports(exports) = *exports.await? {
Some(
exports
.code_generation(*module_graph, *chunking_context, *parsed)
.await?,
)
} else {
None
},
];
let esm_code_gens = esm_references
.await?
.iter()
.map(|r| r.code_generation(*chunking_context))
.try_join()
.await?;
let code_gens = code_generation
.await?
.iter()
.map(|c| c.code_generation(*module_graph, *chunking_context))
.try_join()
.await?;
anyhow::Ok((esm_code_gens, additional_code_gens, code_gens))
}
.instrument(tracing::info_span!("precompute code generation"))
.await?;
let code_gens = esm_code_gens
.iter()
.chain(additional_code_gens.iter().flatten())
.chain(code_gens.iter());
gen_content_with_code_gens(
parsed,
*ident,
specified_module_type,
code_gens,
generate_source_map,
original_source_map,
)
.instrument(tracing::info_span!("gen content with code gens"))
.await
}
/// Creates a new [`Vc<EcmascriptModuleContent>`] without an analysis pass.
#[turbo_tasks::function]
pub async fn new_without_analysis(
parsed: Vc<ParseResult>,
ident: Vc<AssetIdent>,
specified_module_type: SpecifiedModuleType,
generate_source_map: bool,
) -> Result<Vc<Self>> {
gen_content_with_code_gens(
parsed.to_resolved().await?,
ident,
specified_module_type,
&[],
generate_source_map,
OptionStringifiedSourceMap::none().to_resolved().await?,
)
.await
}
}
async fn gen_content_with_code_gens(
parsed: ResolvedVc<ParseResult>,
ident: Vc<AssetIdent>,
specified_module_type: SpecifiedModuleType,
code_gens: impl IntoIterator<Item = &CodeGeneration>,
generate_source_map: bool,
original_source_map: ResolvedVc<OptionStringifiedSourceMap>,
) -> Result<Vc<EcmascriptModuleContent>> {
let parsed = parsed.final_read_hint().await?;
match &*parsed {
ParseResult::Ok { .. } => {
// We need a mutable version of the AST. We try to avoid cloning it by unwrapping the
// ReadRef.
let mut parsed = ReadRef::try_unwrap(parsed);
let (mut program, source_map, globals, eval_context, comments) = match &mut parsed {
Ok(ParseResult::Ok {
program,
source_map,
globals,
eval_context,
comments,
}) => (
program.take(),
&*source_map,
&*globals,
&*eval_context,
match Arc::try_unwrap(take(comments)) {
Ok(comments) => Either::Left(comments),
Err(comments) => Either::Right(comments),
},
),
Err(parsed) => {
let ParseResult::Ok {
program,
source_map,
globals,
eval_context,
comments,
} = &**parsed
else {
unreachable!();
};
(
program.clone(),
source_map,
globals,
eval_context,
Either::Right(comments.clone()),
)
}
_ => unreachable!(),
};
process_content_with_code_gens(
&mut program,
globals,
Some(eval_context.top_level_mark),
code_gens,
);
let mut bytes: Vec<u8> = vec![];
// TODO: Insert this as a sourceless segment so that sourcemaps aren't affected.
// = format!("/* {} */\n", self.module.path().to_string().await?).into_bytes();
let mut mappings = vec![];
{
let comments = match comments {
Either::Left(comments) => Either::Left(comments.into_consumable()),
Either::Right(ref comments) => Either::Right(comments.consumable()),
};
let comments: &dyn Comments = match &comments {
Either::Left(comments) => comments,
Either::Right(comments) => comments,
};
let mut emitter = Emitter {
cfg: swc_core::ecma::codegen::Config::default(),
cm: source_map.clone(),
comments: Some(&comments),
wr: JsWriter::new(
source_map.clone(),
"\n",
&mut bytes,
generate_source_map.then_some(&mut mappings),
),
};
emitter.emit_program(&program)?;
}
let source_map = if generate_source_map {
Some(generate_js_source_map(
source_map.clone(),
mappings,
original_source_map.await?.as_ref(),
)?)
} else {
None
};
Ok(EcmascriptModuleContent {
inner_code: bytes.into(),
source_map,
is_esm: eval_context.is_esm(specified_module_type),
}