-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathmodule_graph.rs
2631 lines (2472 loc) · 85.7 KB
/
module_graph.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
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::ast;
use crate::ast::parse;
use crate::ast::transpile_module;
use crate::ast::BundleHook;
use crate::ast::Location;
use crate::ast::ParsedModule;
use crate::colors;
use crate::diagnostics::Diagnostics;
use crate::import_map::ImportMap;
use crate::info::ModuleGraphInfo;
use crate::info::ModuleInfo;
use crate::info::ModuleInfoMap;
use crate::info::ModuleInfoMapItem;
use crate::lockfile::Lockfile;
use crate::media_type::MediaType;
use crate::specifier_handler::CachedModule;
use crate::specifier_handler::Dependency;
use crate::specifier_handler::DependencyMap;
use crate::specifier_handler::Emit;
use crate::specifier_handler::FetchFuture;
use crate::specifier_handler::SpecifierHandler;
use crate::tsc;
use crate::tsc_config::IgnoredCompilerOptions;
use crate::tsc_config::TsConfig;
use crate::version;
use deno_core::error::AnyError;
use deno_core::error::anyhow;
use deno_core::error::custom_error;
use deno_core::error::get_custom_error_class;
use deno_core::error::Context;
use deno_core::futures::stream::FuturesUnordered;
use deno_core::futures::stream::StreamExt;
use deno_core::serde::Deserialize;
use deno_core::serde::Deserializer;
use deno_core::serde::Serialize;
use deno_core::serde::Serializer;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ModuleResolutionError;
use deno_core::ModuleSource;
use deno_core::ModuleSpecifier;
use regex::Regex;
use std::collections::HashSet;
use std::collections::{BTreeSet, HashMap};
use std::error::Error;
use std::fmt;
use std::path::PathBuf;
use std::rc::Rc;
use std::result;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Instant;
lazy_static! {
/// Matched the `@deno-types` pragma.
static ref DENO_TYPES_RE: Regex =
Regex::new(r#"(?i)^\s*@deno-types\s*=\s*(?:["']([^"']+)["']|(\S+))"#)
.unwrap();
/// Matches a `/// <reference ... />` comment reference.
static ref TRIPLE_SLASH_REFERENCE_RE: Regex =
Regex::new(r"(?i)^/\s*<reference\s.*?/>").unwrap();
/// Matches a path reference, which adds a dependency to a module
static ref PATH_REFERENCE_RE: Regex =
Regex::new(r#"(?i)\spath\s*=\s*["']([^"']*)["']"#).unwrap();
/// Matches a types reference, which for JavaScript files indicates the
/// location of types to use when type checking a program that includes it as
/// a dependency.
static ref TYPES_REFERENCE_RE: Regex =
Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap();
}
/// A group of errors that represent errors that can occur when interacting with
/// a module graph.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum GraphError {
/// A module using the HTTPS protocol is trying to import a module with an
/// HTTP schema.
InvalidDowngrade(ModuleSpecifier, Location),
/// A remote module is trying to import a local module.
InvalidLocalImport(ModuleSpecifier, Location),
/// The source code is invalid, as it does not match the expected hash in the
/// lockfile.
InvalidSource(ModuleSpecifier, PathBuf),
/// An unexpected dependency was requested for a module.
MissingDependency(ModuleSpecifier, String),
/// An unexpected specifier was requested.
MissingSpecifier(ModuleSpecifier),
/// The current feature is not supported.
NotSupported(String),
/// A unsupported media type was attempted to be imported as a module.
UnsupportedImportType(ModuleSpecifier, MediaType),
}
impl fmt::Display for GraphError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
GraphError::InvalidDowngrade(ref specifier, ref location) => write!(f, "Modules imported via https are not allowed to import http modules.\n Importing: {}\n at {}", specifier, location),
GraphError::InvalidLocalImport(ref specifier, ref location) => write!(f, "Remote modules are not allowed to import local modules. Consider using a dynamic import instead.\n Importing: {}\n at {}", specifier, location),
GraphError::InvalidSource(ref specifier, ref lockfile) => write!(f, "The source code is invalid, as it does not match the expected hash in the lock file.\n Specifier: {}\n Lock file: {}", specifier, lockfile.to_str().unwrap()),
GraphError::MissingDependency(ref referrer, specifier) => write!(
f,
"The graph is missing a dependency.\n Specifier: {} from {}",
specifier, referrer
),
GraphError::MissingSpecifier(ref specifier) => write!(
f,
"The graph is missing a specifier.\n Specifier: {}",
specifier
),
GraphError::NotSupported(ref msg) => write!(f, "{}", msg),
GraphError::UnsupportedImportType(ref specifier, ref media_type) => write!(f, "An unsupported media type was attempted to be imported as a module.\n Specifier: {}\n MediaType: {}", specifier, media_type),
}
}
}
impl Error for GraphError {}
/// A structure for handling bundle loading, which is implemented here, to
/// avoid a circular dependency with `ast`.
struct BundleLoader<'a> {
cm: Rc<swc_common::SourceMap>,
emit_options: &'a ast::EmitOptions,
globals: &'a swc_common::Globals,
graph: &'a Graph,
}
impl<'a> BundleLoader<'a> {
pub fn new(
graph: &'a Graph,
emit_options: &'a ast::EmitOptions,
globals: &'a swc_common::Globals,
cm: Rc<swc_common::SourceMap>,
) -> Self {
BundleLoader {
cm,
emit_options,
globals,
graph,
}
}
}
impl swc_bundler::Load for BundleLoader<'_> {
fn load(
&self,
file: &swc_common::FileName,
) -> Result<swc_bundler::ModuleData, AnyError> {
match file {
swc_common::FileName::Custom(filename) => {
let specifier = ModuleSpecifier::resolve_url_or_path(filename)
.context("Failed to convert swc FileName to ModuleSpecifier.")?;
if let Some(src) = self.graph.get_source(&specifier) {
let media_type = self
.graph
.get_media_type(&specifier)
.context("Looking up media type during bundling.")?;
let (source_file, module) = transpile_module(
filename,
&src,
&media_type,
self.emit_options,
self.globals,
self.cm.clone(),
)?;
Ok(swc_bundler::ModuleData {
fm: source_file,
module,
helpers: Default::default(),
})
} else {
Err(
GraphError::MissingDependency(specifier, "<bundle>".to_string())
.into(),
)
}
}
_ => unreachable!("Received request for unsupported filename {:?}", file),
}
}
}
/// An enum which represents the parsed out values of references in source code.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TypeScriptReference {
Path(String),
Types(String),
}
/// Determine if a comment contains a triple slash reference and optionally
/// return its kind and value.
pub fn parse_ts_reference(comment: &str) -> Option<TypeScriptReference> {
if !TRIPLE_SLASH_REFERENCE_RE.is_match(comment) {
None
} else if let Some(captures) = PATH_REFERENCE_RE.captures(comment) {
Some(TypeScriptReference::Path(
captures.get(1).unwrap().as_str().to_string(),
))
} else if let Some(captures) = TYPES_REFERENCE_RE.captures(comment) {
Some(TypeScriptReference::Types(
captures.get(1).unwrap().as_str().to_string(),
))
} else {
None
}
}
/// Determine if a comment contains a `@deno-types` pragma and optionally return
/// its value.
pub fn parse_deno_types(comment: &str) -> Option<String> {
if let Some(captures) = DENO_TYPES_RE.captures(comment) {
if let Some(m) = captures.get(1) {
Some(m.as_str().to_string())
} else if let Some(m) = captures.get(2) {
Some(m.as_str().to_string())
} else {
panic!("unreachable");
}
} else {
None
}
}
/// A hashing function that takes the source code, version and optionally a
/// user provided config and generates a string hash which can be stored to
/// determine if the cached emit is valid or not.
fn get_version(source: &str, version: &str, config: &[u8]) -> String {
crate::checksum::gen(&[source.as_bytes(), version.as_bytes(), config])
}
/// A logical representation of a module within a graph.
#[derive(Debug, Clone)]
pub struct Module {
pub dependencies: DependencyMap,
is_dirty: bool,
is_parsed: bool,
maybe_emit: Option<Emit>,
maybe_emit_path: Option<(PathBuf, Option<PathBuf>)>,
maybe_import_map: Option<Arc<Mutex<ImportMap>>>,
maybe_types: Option<(String, ModuleSpecifier)>,
maybe_version: Option<String>,
media_type: MediaType,
specifier: ModuleSpecifier,
source: String,
source_path: PathBuf,
}
impl Default for Module {
fn default() -> Self {
Module {
dependencies: HashMap::new(),
is_dirty: false,
is_parsed: false,
maybe_emit: None,
maybe_emit_path: None,
maybe_import_map: None,
maybe_types: None,
maybe_version: None,
media_type: MediaType::Unknown,
specifier: ModuleSpecifier::resolve_url("file:///example.js").unwrap(),
source: "".to_string(),
source_path: PathBuf::new(),
}
}
}
impl Module {
pub fn new(
cached_module: CachedModule,
is_root: bool,
maybe_import_map: Option<Arc<Mutex<ImportMap>>>,
) -> Self {
// If this is a local root file, and its media type is unknown, set the
// media type to JavaScript. This allows easier ability to create "shell"
// scripts with Deno.
let media_type = if is_root
&& !cached_module.is_remote
&& cached_module.media_type == MediaType::Unknown
{
MediaType::JavaScript
} else {
cached_module.media_type
};
let mut module = Module {
specifier: cached_module.specifier,
maybe_import_map,
media_type,
source: cached_module.source,
source_path: cached_module.source_path,
maybe_emit: cached_module.maybe_emit,
maybe_emit_path: cached_module.maybe_emit_path,
maybe_version: cached_module.maybe_version,
is_dirty: false,
..Self::default()
};
if module.maybe_import_map.is_none() {
if let Some(dependencies) = cached_module.maybe_dependencies {
module.dependencies = dependencies;
module.is_parsed = true;
}
}
module.maybe_types = if let Some(ref specifier) = cached_module.maybe_types
{
Some((
specifier.clone(),
module
.resolve_import(&specifier, None)
.expect("could not resolve module"),
))
} else {
None
};
module
}
/// Return `true` if the current hash of the module matches the stored
/// version.
pub fn is_emit_valid(&self, config: &[u8]) -> bool {
if let Some(version) = self.maybe_version.clone() {
version == get_version(&self.source, &version::deno(), config)
} else {
false
}
}
/// Parse a module, populating the structure with data retrieved from the
/// source of the module.
pub fn parse(&mut self) -> Result<ParsedModule, AnyError> {
let parsed_module =
parse(self.specifier.as_str(), &self.source, &self.media_type)?;
// parse out any triple slash references
for comment in parsed_module.get_leading_comments().iter() {
if let Some(ts_reference) = parse_ts_reference(&comment.text) {
let location = parsed_module.get_location(&comment.span);
match ts_reference {
TypeScriptReference::Path(import) => {
let specifier =
self.resolve_import(&import, Some(location.clone()))?;
let dep = self
.dependencies
.entry(import)
.or_insert_with(|| Dependency::new(location));
dep.maybe_code = Some(specifier);
}
TypeScriptReference::Types(import) => {
let specifier =
self.resolve_import(&import, Some(location.clone()))?;
if self.media_type == MediaType::JavaScript
|| self.media_type == MediaType::JSX
{
// TODO(kitsonk) we need to specifically update the cache when
// this value changes
self.maybe_types = Some((import.clone(), specifier));
} else {
let dep = self
.dependencies
.entry(import)
.or_insert_with(|| Dependency::new(location));
dep.maybe_type = Some(specifier);
}
}
}
}
}
// Parse out all the syntactical dependencies for a module
let dependencies = parsed_module.analyze_dependencies();
for desc in dependencies.iter().filter(|desc| {
desc.kind != swc_ecmascript::dep_graph::DependencyKind::Require
}) {
let location = Location {
filename: self.specifier.to_string(),
col: desc.col,
line: desc.line,
};
// In situations where there is a potential issue with resolving the
// import specifier, that ends up being a module resolution error for a
// code dependency, we should not throw in the `ModuleGraph` but instead
// wait until runtime and throw there, as with dynamic imports they need
// to be catchable, which means they need to be resolved at runtime.
let maybe_specifier =
match self.resolve_import(&desc.specifier, Some(location.clone())) {
Ok(specifier) => Some(specifier),
Err(any_error) => {
match any_error.downcast_ref::<ModuleResolutionError>() {
Some(ModuleResolutionError::ImportPrefixMissing(_, _)) => None,
_ => {
return Err(any_error);
}
}
}
};
// Parse out any `@deno-types` pragmas and modify dependency
let maybe_type = if !desc.leading_comments.is_empty() {
let comment = desc.leading_comments.last().unwrap();
if let Some(deno_types) = parse_deno_types(&comment.text).as_ref() {
Some(self.resolve_import(deno_types, Some(location.clone()))?)
} else {
None
}
} else {
None
};
let dep = self
.dependencies
.entry(desc.specifier.to_string())
.or_insert_with(|| Dependency::new(location));
dep.is_dynamic = desc.is_dynamic;
if let Some(specifier) = maybe_specifier {
if desc.kind == swc_ecmascript::dep_graph::DependencyKind::ExportType
|| desc.kind == swc_ecmascript::dep_graph::DependencyKind::ImportType
{
dep.maybe_type = Some(specifier);
} else {
dep.maybe_code = Some(specifier);
}
}
// If the dependency wasn't a type only dependency already, and there is
// a `@deno-types` comment, then we will set the `maybe_type` dependency.
if maybe_type.is_some() && dep.maybe_type.is_none() {
dep.maybe_type = maybe_type;
}
}
Ok(parsed_module)
}
fn resolve_import(
&self,
specifier: &str,
maybe_location: Option<Location>,
) -> Result<ModuleSpecifier, AnyError> {
let maybe_resolve = if let Some(import_map) = self.maybe_import_map.clone()
{
import_map
.lock()
.unwrap()
.resolve(specifier, self.specifier.as_str())?
} else {
None
};
let mut remapped_import = false;
let specifier = if let Some(module_specifier) = maybe_resolve {
remapped_import = true;
module_specifier
} else {
ModuleSpecifier::resolve_import(specifier, self.specifier.as_str())?
};
let referrer_scheme = self.specifier.as_url().scheme();
let specifier_scheme = specifier.as_url().scheme();
let location = maybe_location.unwrap_or(Location {
filename: self.specifier.to_string(),
line: 0,
col: 0,
});
// Disallow downgrades from HTTPS to HTTP
if referrer_scheme == "https" && specifier_scheme == "http" {
return Err(
GraphError::InvalidDowngrade(specifier.clone(), location).into(),
);
}
// Disallow a remote URL from trying to import a local URL, unless it is a
// remapped import via the import map
if (referrer_scheme == "https" || referrer_scheme == "http")
&& !(specifier_scheme == "https" || specifier_scheme == "http")
&& !remapped_import
{
return Err(
GraphError::InvalidLocalImport(specifier.clone(), location).into(),
);
}
Ok(specifier)
}
pub fn set_emit(&mut self, code: String, maybe_map: Option<String>) {
self.maybe_emit = Some(Emit::Cli((code, maybe_map)));
}
/// Calculate the hashed version of the module and update the `maybe_version`.
pub fn set_version(&mut self, config: &[u8]) {
self.maybe_version =
Some(get_version(&self.source, &version::deno(), config))
}
pub fn size(&self) -> usize {
self.source.as_bytes().len()
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Stats(pub Vec<(String, u32)>);
impl<'de> Deserialize<'de> for Stats {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let items: Vec<(String, u32)> = Deserialize::deserialize(deserializer)?;
Ok(Stats(items))
}
}
impl Serialize for Stats {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Serialize::serialize(&self.0, serializer)
}
}
impl fmt::Display for Stats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "Compilation statistics:")?;
for (key, value) in self.0.clone() {
writeln!(f, " {}: {}", key, value)?;
}
Ok(())
}
}
/// A structure that provides information about a module graph result.
#[derive(Debug, Default)]
pub struct ResultInfo {
/// A structure which provides diagnostic information (usually from `tsc`)
/// about the code in the module graph.
pub diagnostics: Diagnostics,
/// A map of specifiers to the result of their resolution in the module graph.
pub loadable_modules:
HashMap<ModuleSpecifier, Result<ModuleSource, AnyError>>,
/// Optionally ignored compiler options that represent any options that were
/// ignored if there was a user provided configuration.
pub maybe_ignored_options: Option<IgnoredCompilerOptions>,
/// A structure providing key metrics around the operation performed, in
/// milliseconds.
pub stats: Stats,
}
/// Represents the "default" type library that should be used when type
/// checking the code in the module graph. Note that a user provided config
/// of `"lib"` would override this value.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TypeLib {
DenoWindow,
DenoWorker,
UnstableDenoWindow,
UnstableDenoWorker,
}
impl Default for TypeLib {
fn default() -> Self {
TypeLib::DenoWindow
}
}
impl Serialize for TypeLib {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value = match self {
TypeLib::DenoWindow => vec!["deno.window".to_string()],
TypeLib::DenoWorker => vec!["deno.worker".to_string()],
TypeLib::UnstableDenoWindow => {
vec!["deno.window".to_string(), "deno.unstable".to_string()]
}
TypeLib::UnstableDenoWorker => {
vec!["deno.worker".to_string(), "deno.unstable".to_string()]
}
};
Serialize::serialize(&value, serializer)
}
}
#[derive(Debug, Default)]
pub struct BundleOptions {
/// If `true` then debug logging will be output from the isolate.
pub debug: bool,
/// An optional string that points to a user supplied TypeScript configuration
/// file that augments the the default configuration passed to the TypeScript
/// compiler.
pub maybe_config_path: Option<String>,
}
#[derive(Debug, Default)]
pub struct CheckOptions {
/// If `true` then debug logging will be output from the isolate.
pub debug: bool,
/// Utilise the emit from `tsc` to update the emitted code for modules.
pub emit: bool,
/// The base type libraries that should be used when type checking.
pub lib: TypeLib,
/// An optional string that points to a user supplied TypeScript configuration
/// file that augments the the default configuration passed to the TypeScript
/// compiler.
pub maybe_config_path: Option<String>,
/// Ignore any previously emits and ensure that all files are emitted from
/// source.
pub reload: bool,
}
#[derive(Debug, Eq, PartialEq)]
pub enum BundleType {
/// Return the emitted contents of the program as a single "flattened" ES
/// module.
Esm,
// TODO(@kitsonk) once available in swc
// Iife,
/// Do not bundle the emit, instead returning each of the modules that are
/// part of the program as individual files.
None,
}
impl Default for BundleType {
fn default() -> Self {
BundleType::None
}
}
#[derive(Debug, Default)]
pub struct EmitOptions {
/// If true, then code will be type checked, otherwise type checking will be
/// skipped. If false, then swc will be used for the emit, otherwise tsc will
/// be used.
pub check: bool,
/// Indicate the form the result of the emit should take.
pub bundle_type: BundleType,
/// If `true` then debug logging will be output from the isolate.
pub debug: bool,
/// An optional map that contains user supplied TypeScript compiler
/// configuration options that are passed to the TypeScript compiler.
pub maybe_user_config: Option<HashMap<String, Value>>,
}
/// A structure which provides options when transpiling modules.
#[derive(Debug, Default)]
pub struct TranspileOptions {
/// If `true` then debug logging will be output from the isolate.
pub debug: bool,
/// An optional string that points to a user supplied TypeScript configuration
/// file that augments the the default configuration passed to the TypeScript
/// compiler.
pub maybe_config_path: Option<String>,
/// Ignore any previously emits and ensure that all files are emitted from
/// source.
pub reload: bool,
}
#[derive(Debug, Clone)]
enum ModuleSlot {
/// The module fetch resulted in a non-recoverable error.
Err(Arc<AnyError>),
/// The the fetch resulted in a module.
Module(Box<Module>),
/// Used to denote a module that isn't part of the graph.
None,
/// The fetch of the module is pending.
Pending,
}
/// A dependency graph of modules, were the modules that have been inserted via
/// the builder will be loaded into the graph. Also provides an interface to
/// be able to manipulate and handle the graph.
#[derive(Debug, Clone)]
pub struct Graph {
/// A reference to the specifier handler that will retrieve and cache modules
/// for the graph.
handler: Arc<Mutex<dyn SpecifierHandler>>,
/// Optional TypeScript build info that will be passed to `tsc` if `tsc` is
/// invoked.
maybe_tsbuildinfo: Option<String>,
/// The modules that are part of the graph.
modules: HashMap<ModuleSpecifier, ModuleSlot>,
/// A map of redirects, where a module specifier is redirected to another
/// module specifier by the handler. All modules references should be
/// resolved internally via this, before attempting to access the module via
/// the handler, to make sure the correct modules is being dealt with.
redirects: HashMap<ModuleSpecifier, ModuleSpecifier>,
/// The module specifiers that have been uniquely added to the graph, which
/// does not include any transient dependencies.
roots: Vec<ModuleSpecifier>,
/// If all of the root modules are dynamically imported, then this is true.
/// This is used to ensure correct `--reload` behavior, where subsequent
/// calls to a module graph where the emit is already valid do not cause the
/// graph to re-emit.
roots_dynamic: bool,
// A reference to lock file that will be used to check module integrity.
maybe_lockfile: Option<Arc<Mutex<Lockfile>>>,
}
/// Convert a specifier and a module slot in a result to the module source which
/// is needed by Deno core for loading the module.
fn to_module_result(
(specifier, module_slot): (&ModuleSpecifier, &ModuleSlot),
) -> (ModuleSpecifier, Result<ModuleSource, AnyError>) {
match module_slot {
ModuleSlot::Err(err) => (specifier.clone(), Err(anyhow!(err.to_string()))),
ModuleSlot::Module(module) => (
specifier.clone(),
if let Some(emit) = &module.maybe_emit {
match emit {
Emit::Cli((code, _)) => Ok(ModuleSource {
code: code.clone(),
module_url_found: module.specifier.to_string(),
module_url_specified: specifier.to_string(),
}),
}
} else {
match module.media_type {
MediaType::JavaScript | MediaType::Unknown => Ok(ModuleSource {
code: module.source.clone(),
module_url_found: module.specifier.to_string(),
module_url_specified: specifier.to_string(),
}),
_ => Err(custom_error(
"NotFound",
format!("Compiled module not found \"{}\"", specifier),
)),
}
},
),
_ => (
specifier.clone(),
Err(anyhow!("Module \"{}\" unavailable.", specifier)),
),
}
}
impl Graph {
/// Create a new instance of a graph, ready to have modules loaded it.
///
/// The argument `handler` is an instance of a structure that implements the
/// `SpecifierHandler` trait.
///
pub fn new(
handler: Arc<Mutex<dyn SpecifierHandler>>,
maybe_lockfile: Option<Arc<Mutex<Lockfile>>>,
) -> Self {
Graph {
handler,
maybe_tsbuildinfo: None,
modules: HashMap::new(),
redirects: HashMap::new(),
roots: Vec::new(),
roots_dynamic: true,
maybe_lockfile,
}
}
/// Transform the module graph into a single JavaScript module which is
/// returned as a `String` in the result.
pub fn bundle(
&self,
options: BundleOptions,
) -> Result<(String, Stats, Option<IgnoredCompilerOptions>), AnyError> {
if self.roots.is_empty() || self.roots.len() > 1 {
return Err(GraphError::NotSupported(format!("Bundling is only supported when there is a single root module in the graph. Found: {}", self.roots.len())).into());
}
let start = Instant::now();
let root_specifier = self.roots[0].clone();
let mut ts_config = TsConfig::new(json!({
"checkJs": false,
"emitDecoratorMetadata": false,
"inlineSourceMap": true,
"jsx": "react",
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
}));
let maybe_ignored_options =
ts_config.merge_tsconfig(options.maybe_config_path)?;
let s = self.emit_bundle(&root_specifier, &ts_config.into())?;
let stats = Stats(vec![
("Files".to_string(), self.modules.len() as u32),
("Total time".to_string(), start.elapsed().as_millis() as u32),
]);
Ok((s, stats, maybe_ignored_options))
}
/// Type check the module graph, corresponding to the options provided.
pub fn check(self, options: CheckOptions) -> Result<ResultInfo, AnyError> {
let mut config = TsConfig::new(json!({
"allowJs": true,
// TODO(@kitsonk) is this really needed?
"esModuleInterop": true,
// Enabled by default to align to transpile/swc defaults
"experimentalDecorators": true,
"incremental": true,
"isolatedModules": true,
"lib": options.lib,
"module": "esnext",
"strict": true,
"target": "esnext",
"tsBuildInfoFile": "deno:///.tsbuildinfo",
}));
if options.emit {
config.merge(&json!({
// TODO(@kitsonk) consider enabling this by default
// see: https://github.com/denoland/deno/issues/7732
"emitDecoratorMetadata": false,
"jsx": "react",
"inlineSourceMap": true,
"outDir": "deno://",
"removeComments": true,
}));
} else {
config.merge(&json!({
"noEmit": true,
}));
}
let maybe_ignored_options =
config.merge_tsconfig(options.maybe_config_path)?;
// Short circuit if none of the modules require an emit, or all of the
// modules that require an emit have a valid emit. There is also an edge
// case where there are multiple imports of a dynamic module during a
// single invocation, if that is the case, even if there is a reload, we
// will simply look at if the emit is invalid, to avoid two checks for the
// same programme.
if !self.needs_emit(&config)
|| (self.is_emit_valid(&config)
&& (!options.reload || self.roots_dynamic))
{
debug!("graph does not need to be checked or emitted.");
return Ok(ResultInfo {
maybe_ignored_options,
loadable_modules: self.get_loadable_modules(),
..Default::default()
});
}
// TODO(@kitsonk) not totally happy with this here, but this is the first
// point where we know we are actually going to check the program. If we
// moved it out of here, we wouldn't know until after the check has already
// happened, which isn't informative to the users.
for specifier in &self.roots {
info!("{} {}", colors::green("Check"), specifier);
}
let root_names = self.get_root_names(!config.get_check_js())?;
let maybe_tsbuildinfo = self.maybe_tsbuildinfo.clone();
let hash_data =
vec![config.as_bytes(), version::deno().as_bytes().to_owned()];
let graph = Arc::new(Mutex::new(self));
let response = tsc::exec(tsc::Request {
config: config.clone(),
debug: options.debug,
graph: graph.clone(),
hash_data,
maybe_tsbuildinfo,
root_names,
})?;
let mut graph = graph.lock().unwrap();
graph.maybe_tsbuildinfo = response.maybe_tsbuildinfo;
// Only process changes to the graph if there are no diagnostics and there
// were files emitted.
if response.diagnostics.is_empty() {
if !response.emitted_files.is_empty() {
let mut codes = HashMap::new();
let mut maps = HashMap::new();
let check_js = config.get_check_js();
for emit in &response.emitted_files {
if let Some(specifiers) = &emit.maybe_specifiers {
assert!(specifiers.len() == 1, "Unexpected specifier length");
// The specifier emitted might not be the redirected specifier, and
// therefore we need to ensure it is the correct one.
let specifier = graph.resolve_specifier(&specifiers[0]);
// Sometimes if tsc sees a CommonJS file it will _helpfully_ output it
// to ESM, which we don't really want unless someone has enabled the
// check_js option.
if !check_js
&& graph.get_media_type(&specifier) == Some(MediaType::JavaScript)
{
debug!("skipping emit for {}", specifier);
continue;
}
match emit.media_type {
MediaType::JavaScript => {
codes.insert(specifier.clone(), emit.data.clone());
}
MediaType::SourceMap => {
maps.insert(specifier.clone(), emit.data.clone());
}
_ => unreachable!(),
}
}
}
let config = config.as_bytes();
for (specifier, code) in codes.iter() {
if let ModuleSlot::Module(module) =
graph.get_module_mut(specifier).unwrap()
{
module.set_emit(code.clone(), maps.get(specifier).cloned());
module.set_version(&config);
module.is_dirty = true;
} else {
return Err(GraphError::MissingSpecifier(specifier.clone()).into());
}
}
}
graph.flush()?;
}
Ok(ResultInfo {
diagnostics: response.diagnostics,
loadable_modules: graph.get_loadable_modules(),
maybe_ignored_options,
stats: response.stats,
})
}
/// Emit the module graph in a specific format. This is specifically designed
/// to be an "all-in-one" API for access by the runtime, allowing both
/// emitting single modules as well as bundles, using Deno module resolution
/// or supplied sources.
pub fn emit(
mut self,
options: EmitOptions,
) -> Result<(HashMap<String, String>, ResultInfo), AnyError> {
let mut config = TsConfig::new(json!({
"allowJs": true,
"checkJs": false,
// TODO(@kitsonk) consider enabling this by default
// see: https://github.com/denoland/deno/issues/7732
"emitDecoratorMetadata": false,
"esModuleInterop": true,
"experimentalDecorators": true,
"inlineSourceMap": false,
"isolatedModules": true,
"jsx": "react",
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
"lib": TypeLib::DenoWindow,
"module": "esnext",
"strict": true,
"target": "esnext",
}));
let opts = match options.bundle_type {
BundleType::Esm => json!({
"noEmit": true,
}),
BundleType::None => json!({
"outDir": "deno://",
"removeComments": true,
"sourceMap": true,
}),
};
config.merge(&opts);
let maybe_ignored_options =
if let Some(user_options) = &options.maybe_user_config {
config.merge_user_config(user_options)?
} else {
None
};
if !options.check && config.get_declaration() {
return Err(anyhow!("The option of `check` is false, but the compiler option of `declaration` is true which is not currently supported."));
}
if options.bundle_type != BundleType::None && config.get_declaration() {
return Err(anyhow!("The bundle option is set, but the compiler option of `declaration` is true which is not currently supported."));
}
let mut emitted_files = HashMap::new();
if options.check {
let root_names = self.get_root_names(!config.get_check_js())?;
let hash_data =
vec![config.as_bytes(), version::deno().as_bytes().to_owned()];
let graph = Arc::new(Mutex::new(self));
let response = tsc::exec(tsc::Request {
config: config.clone(),
debug: options.debug,
graph: graph.clone(),
hash_data,
maybe_tsbuildinfo: None,
root_names,
})?;
let graph = graph.lock().unwrap();
match options.bundle_type {
BundleType::Esm => {
assert!(
response.emitted_files.is_empty(),
"No files should have been emitted from tsc."
);
assert_eq!(
graph.roots.len(),