2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-08-31 14:12:24 -04:00
|
|
|
|
2020-09-14 08:27:44 -04:00
|
|
|
use crate::ast::parse;
|
|
|
|
use crate::ast::Location;
|
2020-09-12 05:53:57 -04:00
|
|
|
use crate::diagnostics::Diagnostics;
|
2019-07-17 18:15:30 -04:00
|
|
|
use crate::disk_cache::DiskCache;
|
2019-07-31 07:58:41 -04:00
|
|
|
use crate::file_fetcher::SourceFile;
|
|
|
|
use crate::file_fetcher::SourceFileFetcher;
|
2020-06-30 07:10:51 -04:00
|
|
|
use crate::flags::Flags;
|
2020-09-11 09:18:49 -04:00
|
|
|
use crate::js;
|
2020-09-15 10:33:14 -04:00
|
|
|
use crate::media_type::MediaType;
|
2020-06-19 06:27:15 -04:00
|
|
|
use crate::module_graph::ModuleGraph;
|
2020-05-18 06:59:29 -04:00
|
|
|
use crate::module_graph::ModuleGraphLoader;
|
2020-05-11 07:13:27 -04:00
|
|
|
use crate::permissions::Permissions;
|
2020-10-13 07:35:35 -04:00
|
|
|
use crate::program_state::ProgramState;
|
2020-08-31 14:12:24 -04:00
|
|
|
use crate::tsc_config;
|
2019-07-17 18:15:30 -04:00
|
|
|
use crate::version;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::generic_error;
|
|
|
|
use deno_core::error::AnyError;
|
2020-09-26 10:33:25 -04:00
|
|
|
use deno_core::error::JsError;
|
|
|
|
use deno_core::json_op_sync;
|
2020-09-21 12:36:37 -04:00
|
|
|
use deno_core::serde_json;
|
|
|
|
use deno_core::serde_json::json;
|
|
|
|
use deno_core::serde_json::Value;
|
2020-09-16 14:28:07 -04:00
|
|
|
use deno_core::url::Url;
|
2020-09-26 10:33:25 -04:00
|
|
|
use deno_core::JsRuntime;
|
2020-01-05 11:56:18 -05:00
|
|
|
use deno_core::ModuleSpecifier;
|
2020-09-26 10:33:25 -04:00
|
|
|
use deno_core::RuntimeOptions;
|
2020-06-24 05:58:23 -04:00
|
|
|
use log::debug;
|
2019-08-17 12:53:34 -04:00
|
|
|
use regex::Regex;
|
2020-05-05 12:23:15 -04:00
|
|
|
use serde::Deserialize;
|
2020-05-16 15:47:26 -04:00
|
|
|
use serde::Serialize;
|
2020-09-15 10:33:14 -04:00
|
|
|
use serde::Serializer;
|
2020-05-12 11:44:25 -04:00
|
|
|
use sourcemap::SourceMap;
|
2020-01-08 09:17:44 -05:00
|
|
|
use std::collections::HashMap;
|
2019-07-17 18:15:30 -04:00
|
|
|
use std::collections::HashSet;
|
|
|
|
use std::fs;
|
2019-09-20 10:19:51 -04:00
|
|
|
use std::io;
|
2020-02-06 21:24:51 -05:00
|
|
|
use std::ops::Deref;
|
2019-06-24 13:10:21 -04:00
|
|
|
use std::path::PathBuf;
|
2019-02-18 10:42:15 -05:00
|
|
|
use std::str;
|
2020-02-06 21:24:51 -05:00
|
|
|
use std::sync::Arc;
|
2019-07-17 18:15:30 -04:00
|
|
|
use std::sync::Mutex;
|
2020-09-03 11:11:30 -04:00
|
|
|
use swc_common::comments::Comment;
|
2020-07-31 10:59:22 -04:00
|
|
|
use swc_common::comments::CommentKind;
|
2020-09-09 09:35:40 -04:00
|
|
|
use swc_ecmascript::dep_graph;
|
2019-01-09 12:59:46 -05:00
|
|
|
|
2020-05-29 10:32:15 -04:00
|
|
|
pub const AVAILABLE_LIBS: &[&str] = &[
|
|
|
|
"deno.ns",
|
|
|
|
"deno.window",
|
|
|
|
"deno.worker",
|
|
|
|
"deno.shared_globals",
|
|
|
|
"deno.unstable",
|
|
|
|
"dom",
|
|
|
|
"dom.iterable",
|
|
|
|
"es5",
|
|
|
|
"es6",
|
|
|
|
"esnext",
|
|
|
|
"es2020",
|
|
|
|
"es2020.full",
|
|
|
|
"es2019",
|
|
|
|
"es2019.full",
|
|
|
|
"es2018",
|
|
|
|
"es2018.full",
|
|
|
|
"es2017",
|
|
|
|
"es2017.full",
|
|
|
|
"es2016",
|
|
|
|
"es2016.full",
|
|
|
|
"es2015",
|
|
|
|
"es2015.collection",
|
|
|
|
"es2015.core",
|
|
|
|
"es2015.generator",
|
|
|
|
"es2015.iterable",
|
|
|
|
"es2015.promise",
|
|
|
|
"es2015.proxy",
|
|
|
|
"es2015.reflect",
|
|
|
|
"es2015.symbol",
|
|
|
|
"es2015.symbol.wellknown",
|
|
|
|
"es2016.array.include",
|
|
|
|
"es2017.intl",
|
|
|
|
"es2017.object",
|
|
|
|
"es2017.sharedmemory",
|
|
|
|
"es2017.string",
|
|
|
|
"es2017.typedarrays",
|
|
|
|
"es2018.asyncgenerator",
|
|
|
|
"es2018.asynciterable",
|
|
|
|
"es2018.intl",
|
|
|
|
"es2018.promise",
|
|
|
|
"es2018.regexp",
|
|
|
|
"es2019.array",
|
|
|
|
"es2019.object",
|
|
|
|
"es2019.string",
|
|
|
|
"es2019.symbol",
|
|
|
|
"es2020.bigint",
|
|
|
|
"es2020.promise",
|
|
|
|
"es2020.string",
|
|
|
|
"es2020.symbol.wellknown",
|
|
|
|
"esnext.array",
|
|
|
|
"esnext.asynciterable",
|
|
|
|
"esnext.bigint",
|
|
|
|
"esnext.intl",
|
|
|
|
"esnext.promise",
|
|
|
|
"esnext.string",
|
|
|
|
"esnext.symbol",
|
2020-10-21 06:57:01 -04:00
|
|
|
"esnext.weakref",
|
2020-05-29 10:32:15 -04:00
|
|
|
"scripthost",
|
|
|
|
"webworker",
|
|
|
|
"webworker.importscripts",
|
|
|
|
];
|
2020-05-18 06:59:29 -04:00
|
|
|
|
2020-05-08 10:18:00 -04:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct CompiledModule {
|
|
|
|
pub code: String,
|
|
|
|
pub name: String,
|
|
|
|
}
|
|
|
|
|
2019-08-17 12:53:34 -04:00
|
|
|
lazy_static! {
|
2020-09-04 04:44:31 -04:00
|
|
|
/// Matches the `@deno-types` pragma.
|
2020-07-11 12:30:30 -04:00
|
|
|
static ref DENO_TYPES_RE: Regex =
|
2020-09-04 04:44:31 -04:00
|
|
|
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
|
2020-07-11 12:30:30 -04:00
|
|
|
static ref PATH_REFERENCE_RE: Regex =
|
2020-09-04 04:44:31 -04:00
|
|
|
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.
|
2020-07-11 12:30:30 -04:00
|
|
|
static ref TYPES_REFERENCE_RE: Regex =
|
2020-09-04 04:44:31 -04:00
|
|
|
Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap();
|
|
|
|
/// Matches a lib reference.
|
2020-07-11 12:30:30 -04:00
|
|
|
static ref LIB_REFERENCE_RE: Regex =
|
2020-09-04 04:44:31 -04:00
|
|
|
Regex::new(r#"(?i)\slib\s*=\s*["']([^"']*)["']"#).unwrap();
|
2019-08-17 12:53:34 -04:00
|
|
|
}
|
|
|
|
|
2020-10-26 15:56:00 -04:00
|
|
|
#[derive(Clone, Eq, PartialEq)]
|
2020-01-29 12:54:23 -05:00
|
|
|
pub enum TargetLib {
|
|
|
|
Main,
|
|
|
|
Worker,
|
|
|
|
}
|
|
|
|
|
2019-07-31 13:16:03 -04:00
|
|
|
/// Struct which represents the state of the compiler
|
|
|
|
/// configuration where the first is canonical name for the configuration file,
|
|
|
|
/// second is a vector of the bytes of the contents of the configuration file,
|
|
|
|
/// third is bytes of the hash of contents.
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct CompilerConfig {
|
|
|
|
pub path: Option<PathBuf>,
|
2020-08-31 14:12:24 -04:00
|
|
|
pub options: Value,
|
|
|
|
pub maybe_ignored_options: Option<tsc_config::IgnoredCompilerOptions>,
|
|
|
|
pub hash: String,
|
2019-08-17 12:53:34 -04:00
|
|
|
pub compile_js: bool,
|
2019-07-31 13:16:03 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl CompilerConfig {
|
|
|
|
/// Take the passed flag and resolve the file name relative to the cwd.
|
2020-09-14 12:48:57 -04:00
|
|
|
pub fn load(maybe_config_path: Option<String>) -> Result<Self, AnyError> {
|
2020-08-31 14:12:24 -04:00
|
|
|
if maybe_config_path.is_none() {
|
|
|
|
return Ok(Self {
|
|
|
|
path: Some(PathBuf::new()),
|
|
|
|
options: json!({}),
|
|
|
|
maybe_ignored_options: None,
|
|
|
|
hash: "".to_string(),
|
|
|
|
compile_js: false,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
let raw_config_path = maybe_config_path.unwrap();
|
|
|
|
debug!("Compiler config file: {}", raw_config_path);
|
|
|
|
let cwd = std::env::current_dir().unwrap();
|
|
|
|
let config_file = cwd.join(raw_config_path);
|
2019-07-31 13:16:03 -04:00
|
|
|
|
|
|
|
// Convert the PathBuf to a canonicalized string. This is needed by the
|
|
|
|
// compiler to properly deal with the configuration.
|
2020-08-31 14:12:24 -04:00
|
|
|
let config_path = config_file.canonicalize().map_err(|_| {
|
|
|
|
io::Error::new(
|
|
|
|
io::ErrorKind::InvalidInput,
|
|
|
|
format!(
|
|
|
|
"Could not find the config file: {}",
|
|
|
|
config_file.to_string_lossy()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
})?;
|
2019-07-31 13:16:03 -04:00
|
|
|
|
|
|
|
// Load the contents of the configuration file
|
2020-08-31 14:12:24 -04:00
|
|
|
debug!("Attempt to load config: {}", config_path.to_str().unwrap());
|
|
|
|
let config_bytes = fs::read(&config_file)?;
|
|
|
|
let config_hash = crate::checksum::gen(&[&config_bytes]);
|
|
|
|
let config_str = String::from_utf8(config_bytes)?;
|
2019-07-31 13:16:03 -04:00
|
|
|
|
2020-08-31 14:12:24 -04:00
|
|
|
let (options, maybe_ignored_options) = if config_str.is_empty() {
|
|
|
|
(json!({}), None)
|
|
|
|
} else {
|
2020-09-29 03:16:12 -04:00
|
|
|
tsc_config::parse_config(&config_str, &config_path)?
|
2019-07-31 13:16:03 -04:00
|
|
|
};
|
|
|
|
|
2019-08-17 12:53:34 -04:00
|
|
|
// If `checkJs` is set to true in `compilerOptions` then we're gonna be compiling
|
|
|
|
// JavaScript files as well
|
2020-08-31 14:12:24 -04:00
|
|
|
let compile_js = options["checkJs"].as_bool().unwrap_or(false);
|
2019-08-17 12:53:34 -04:00
|
|
|
|
2020-08-31 14:12:24 -04:00
|
|
|
Ok(Self {
|
|
|
|
path: Some(config_path),
|
|
|
|
options,
|
|
|
|
maybe_ignored_options,
|
2019-07-31 13:16:03 -04:00
|
|
|
hash: config_hash,
|
2019-08-17 12:53:34 -04:00
|
|
|
compile_js,
|
2020-08-31 14:12:24 -04:00
|
|
|
})
|
2019-07-31 13:16:03 -04:00
|
|
|
}
|
|
|
|
}
|
2019-07-17 18:15:30 -04:00
|
|
|
|
|
|
|
/// Information associated with compiled file in cache.
|
|
|
|
/// version_hash is used to validate versions of the file
|
|
|
|
/// and could be used to remove stale file in cache.
|
2020-05-16 15:47:26 -04:00
|
|
|
#[derive(Deserialize, Serialize)]
|
2019-07-17 18:15:30 -04:00
|
|
|
pub struct CompiledFileMetadata {
|
|
|
|
pub version_hash: String,
|
2019-01-09 12:59:46 -05:00
|
|
|
}
|
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
impl CompiledFileMetadata {
|
2020-01-04 05:20:52 -05:00
|
|
|
pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
|
2020-05-16 15:47:26 -04:00
|
|
|
serde_json::to_string(self)
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
}
|
2020-05-16 15:47:26 -04:00
|
|
|
|
2019-08-28 18:58:42 -04:00
|
|
|
/// Emit a SHA256 hash based on source code, deno version and TS config.
|
2019-07-17 18:15:30 -04:00
|
|
|
/// Used to check if a recompilation for source code is needed.
|
2020-06-30 07:10:51 -04:00
|
|
|
fn source_code_version_hash(
|
2019-07-17 18:15:30 -04:00
|
|
|
source_code: &[u8],
|
|
|
|
version: &str,
|
|
|
|
config_hash: &[u8],
|
|
|
|
) -> String {
|
2020-06-29 08:17:37 -04:00
|
|
|
crate::checksum::gen(&[source_code, version.as_bytes(), config_hash])
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
2020-02-06 21:24:51 -05:00
|
|
|
pub struct TsCompilerInner {
|
2019-07-31 07:58:41 -04:00
|
|
|
pub file_fetcher: SourceFileFetcher,
|
2020-06-30 07:10:51 -04:00
|
|
|
pub flags: Flags,
|
2019-07-17 18:15:30 -04:00
|
|
|
pub config: CompilerConfig,
|
|
|
|
pub disk_cache: DiskCache,
|
|
|
|
/// Set of all URLs that have been compiled. This prevents double
|
|
|
|
/// compilation of module.
|
|
|
|
pub compiled: Mutex<HashSet<Url>>,
|
|
|
|
/// This setting is controlled by `--reload` flag. Unless the flag
|
|
|
|
/// is provided disk cache is used.
|
|
|
|
pub use_disk_cache: bool,
|
2019-07-31 13:16:03 -04:00
|
|
|
/// This setting is controlled by `compilerOptions.checkJs`
|
|
|
|
pub compile_js: bool,
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
2020-02-06 21:24:51 -05:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct TsCompiler(Arc<TsCompilerInner>);
|
|
|
|
|
|
|
|
impl Deref for TsCompiler {
|
|
|
|
type Target = TsCompilerInner;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-24 10:59:12 -04:00
|
|
|
#[derive(Deserialize, Debug)]
|
2020-06-24 05:58:23 -04:00
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct Stat {
|
|
|
|
key: String,
|
|
|
|
value: f64,
|
|
|
|
}
|
|
|
|
|
2020-05-05 12:23:15 -04:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct EmittedSource {
|
|
|
|
filename: String,
|
|
|
|
contents: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): possible deduplicate once TS refactor is stabilized
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
#[allow(unused)]
|
|
|
|
struct RuntimeBundleResponse {
|
2020-09-12 05:53:57 -04:00
|
|
|
diagnostics: Diagnostics,
|
2020-05-05 12:23:15 -04:00
|
|
|
output: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct RuntimeCompileResponse {
|
2020-09-12 05:53:57 -04:00
|
|
|
diagnostics: Diagnostics,
|
2020-05-05 12:23:15 -04:00
|
|
|
emit_map: HashMap<String, EmittedSource>,
|
|
|
|
}
|
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
impl TsCompiler {
|
|
|
|
pub fn new(
|
2019-07-31 07:58:41 -04:00
|
|
|
file_fetcher: SourceFileFetcher,
|
2020-06-30 07:10:51 -04:00
|
|
|
flags: Flags,
|
2019-07-31 07:58:41 -04:00
|
|
|
disk_cache: DiskCache,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Self, AnyError> {
|
2020-06-30 07:10:51 -04:00
|
|
|
let config = CompilerConfig::load(flags.config_path.clone())?;
|
|
|
|
let use_disk_cache = !flags.reload;
|
|
|
|
|
2020-02-06 21:24:51 -05:00
|
|
|
Ok(TsCompiler(Arc::new(TsCompilerInner {
|
2019-07-31 07:58:41 -04:00
|
|
|
file_fetcher,
|
2020-06-30 07:10:51 -04:00
|
|
|
flags,
|
2019-07-31 07:58:41 -04:00
|
|
|
disk_cache,
|
2019-08-17 12:53:34 -04:00
|
|
|
compile_js: config.compile_js,
|
2019-07-31 13:16:03 -04:00
|
|
|
config,
|
2019-07-17 18:15:30 -04:00
|
|
|
compiled: Mutex::new(HashSet::new()),
|
|
|
|
use_disk_cache,
|
2020-02-06 21:24:51 -05:00
|
|
|
})))
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
2020-02-03 18:08:44 -05:00
|
|
|
/// Mark given module URL as compiled to avoid multiple compilations of same
|
|
|
|
/// module in single run.
|
2019-07-17 18:15:30 -04:00
|
|
|
fn mark_compiled(&self, url: &Url) {
|
|
|
|
let mut c = self.compiled.lock().unwrap();
|
|
|
|
c.insert(url.clone());
|
|
|
|
}
|
|
|
|
|
2020-05-05 12:23:15 -04:00
|
|
|
fn cache_emitted_files(
|
|
|
|
&self,
|
|
|
|
emit_map: HashMap<String, EmittedSource>,
|
|
|
|
) -> std::io::Result<()> {
|
|
|
|
for (emitted_name, source) in emit_map.iter() {
|
|
|
|
let specifier = ModuleSpecifier::resolve_url(&source.filename)
|
|
|
|
.expect("Should be a valid module specifier");
|
|
|
|
|
2020-05-29 10:32:15 -04:00
|
|
|
let source_file = self
|
|
|
|
.file_fetcher
|
|
|
|
.fetch_cached_source_file(&specifier, Permissions::allow_all())
|
|
|
|
.expect("Source file not found");
|
|
|
|
|
|
|
|
// NOTE: JavaScript files are only cached to disk if `checkJs`
|
|
|
|
// option in on
|
2020-09-15 10:33:14 -04:00
|
|
|
if source_file.media_type == MediaType::JavaScript && !self.compile_js {
|
2020-05-29 10:32:15 -04:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2020-05-05 12:23:15 -04:00
|
|
|
if emitted_name.ends_with(".map") {
|
|
|
|
self.cache_source_map(&specifier, &source.contents)?;
|
|
|
|
} else if emitted_name.ends_with(".js") {
|
2020-05-29 10:32:15 -04:00
|
|
|
self.cache_compiled_file(&specifier, source_file, &source.contents)?;
|
2020-05-05 12:23:15 -04:00
|
|
|
} else {
|
|
|
|
panic!("Trying to cache unknown file type {}", emitted_name);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
/// Save compiled JS file for given TS module to on-disk cache.
|
|
|
|
///
|
|
|
|
/// Along compiled file a special metadata file is saved as well containing
|
|
|
|
/// hash that can be validated to avoid unnecessary recompilation.
|
2020-04-15 23:14:28 -04:00
|
|
|
fn cache_compiled_file(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-07-17 18:15:30 -04:00
|
|
|
module_specifier: &ModuleSpecifier,
|
2020-05-29 10:32:15 -04:00
|
|
|
source_file: SourceFile,
|
2019-07-17 18:15:30 -04:00
|
|
|
contents: &str,
|
|
|
|
) -> std::io::Result<()> {
|
|
|
|
let js_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(module_specifier.as_url(), "js");
|
2020-02-19 17:51:10 -05:00
|
|
|
self.disk_cache.set(&js_key, contents.as_bytes())?;
|
|
|
|
self.mark_compiled(module_specifier.as_url());
|
|
|
|
|
|
|
|
let version_hash = source_code_version_hash(
|
2020-08-03 17:39:48 -04:00
|
|
|
&source_file.source_code.as_bytes(),
|
2020-02-19 17:51:10 -05:00
|
|
|
version::DENO,
|
2020-08-31 14:12:24 -04:00
|
|
|
&self.config.hash.as_bytes(),
|
2020-02-19 17:51:10 -05:00
|
|
|
);
|
2019-07-17 18:15:30 -04:00
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
let compiled_file_metadata = CompiledFileMetadata { version_hash };
|
2020-02-19 17:51:10 -05:00
|
|
|
let meta_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(module_specifier.as_url(), "meta");
|
|
|
|
self.disk_cache.set(
|
|
|
|
&meta_key,
|
|
|
|
compiled_file_metadata.to_json_string()?.as_bytes(),
|
|
|
|
)
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Save source map file for given TS module to on-disk cache.
|
|
|
|
fn cache_source_map(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-07-17 18:15:30 -04:00
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
contents: &str,
|
|
|
|
) -> std::io::Result<()> {
|
2020-05-12 11:44:25 -04:00
|
|
|
let js_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(module_specifier.as_url(), "js");
|
|
|
|
let js_path = self.disk_cache.location.join(js_key);
|
|
|
|
let js_file_url =
|
|
|
|
Url::from_file_path(js_path).expect("Bad file URL for file");
|
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
let source_map_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(module_specifier.as_url(), "js.map");
|
2020-05-12 11:44:25 -04:00
|
|
|
|
|
|
|
let mut sm = SourceMap::from_slice(contents.as_bytes())
|
|
|
|
.expect("Invalid source map content");
|
|
|
|
sm.set_file(Some(&js_file_url.to_string()));
|
|
|
|
sm.set_source(0, &module_specifier.to_string());
|
|
|
|
|
|
|
|
let mut output: Vec<u8> = vec![];
|
|
|
|
sm.to_writer(&mut output)
|
|
|
|
.expect("Failed to write source map");
|
|
|
|
|
|
|
|
self.disk_cache.set(&source_map_key, &output)
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
2019-04-05 00:04:06 -04:00
|
|
|
}
|
|
|
|
|
2020-10-01 06:33:15 -04:00
|
|
|
#[derive(Debug, Deserialize)]
|
|
|
|
struct CreateHashArgs {
|
|
|
|
data: String,
|
|
|
|
}
|
|
|
|
|
2020-09-26 10:33:25 -04:00
|
|
|
fn execute_in_tsc(
|
2020-10-13 07:35:35 -04:00
|
|
|
program_state: Arc<ProgramState>,
|
2020-07-23 09:29:36 -04:00
|
|
|
req: String,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<String, AnyError> {
|
2020-09-26 10:33:25 -04:00
|
|
|
let mut js_runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
startup_snapshot: Some(js::compiler_isolate_init()),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
2020-10-13 07:35:35 -04:00
|
|
|
let debug_flag = program_state
|
2020-09-26 10:33:25 -04:00
|
|
|
.flags
|
|
|
|
.log_level
|
|
|
|
.map_or(false, |l| l == log::Level::Debug);
|
|
|
|
let response = Arc::new(Mutex::new(None));
|
|
|
|
|
|
|
|
{
|
|
|
|
js_runtime.register_op(
|
|
|
|
"op_fetch_asset",
|
|
|
|
crate::op_fetch_asset::op_fetch_asset(HashMap::default()),
|
|
|
|
);
|
|
|
|
let res = response.clone();
|
|
|
|
js_runtime.register_op(
|
|
|
|
"op_compiler_respond",
|
|
|
|
json_op_sync(move |_state, args, _bufs| {
|
|
|
|
let mut response_slot = res.lock().unwrap();
|
|
|
|
let replaced_value = response_slot.replace(args.to_string());
|
|
|
|
assert!(
|
|
|
|
replaced_value.is_none(),
|
|
|
|
"op_compiler_respond found unexpected existing compiler output",
|
|
|
|
);
|
|
|
|
Ok(json!({}))
|
|
|
|
}),
|
|
|
|
);
|
2020-10-01 06:33:15 -04:00
|
|
|
js_runtime.register_op(
|
|
|
|
"op_create_hash",
|
|
|
|
json_op_sync(move |_s, args, _bufs| {
|
|
|
|
let v: CreateHashArgs = serde_json::from_value(args)?;
|
|
|
|
let hash = crate::checksum::gen(&[v.data.as_bytes()]);
|
|
|
|
Ok(json!({ "hash": hash }))
|
|
|
|
}),
|
|
|
|
);
|
2020-09-26 10:33:25 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
let bootstrap_script = format!(
|
2020-10-13 19:52:49 -04:00
|
|
|
"globalThis.startup({{ debugFlag: {}, legacy: true }})",
|
2020-09-26 10:33:25 -04:00
|
|
|
debug_flag
|
|
|
|
);
|
|
|
|
js_runtime.execute("<compiler>", &bootstrap_script)?;
|
|
|
|
|
2020-07-23 09:29:36 -04:00
|
|
|
let script = format!("globalThis.tsCompilerOnMessage({{ data: {} }});", req);
|
2020-09-26 10:33:25 -04:00
|
|
|
js_runtime.execute("<compiler>", &script)?;
|
|
|
|
|
|
|
|
let maybe_response = response.lock().unwrap().take();
|
|
|
|
assert!(
|
|
|
|
maybe_response.is_some(),
|
|
|
|
"Unexpected missing response from TS compiler"
|
|
|
|
);
|
|
|
|
|
|
|
|
Ok(maybe_response.unwrap())
|
2020-02-06 21:24:51 -05:00
|
|
|
}
|
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
async fn create_runtime_module_graph(
|
2020-10-13 07:35:35 -04:00
|
|
|
program_state: &Arc<ProgramState>,
|
2020-05-11 07:13:27 -04:00
|
|
|
permissions: Permissions,
|
2020-01-08 09:17:44 -05:00
|
|
|
root_name: &str,
|
2020-06-19 06:27:15 -04:00
|
|
|
sources: &Option<HashMap<String, String>>,
|
2020-08-31 14:12:24 -04:00
|
|
|
type_files: Vec<String>,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<(Vec<String>, ModuleGraph), AnyError> {
|
2020-05-18 06:59:29 -04:00
|
|
|
let mut root_names = vec![];
|
|
|
|
let mut module_graph_loader = ModuleGraphLoader::new(
|
2020-10-13 07:35:35 -04:00
|
|
|
program_state.file_fetcher.clone(),
|
2020-05-18 06:59:29 -04:00
|
|
|
None,
|
2020-06-19 06:27:15 -04:00
|
|
|
permissions,
|
2020-05-18 06:59:29 -04:00
|
|
|
false,
|
|
|
|
false,
|
|
|
|
);
|
|
|
|
|
|
|
|
if let Some(s_map) = sources {
|
|
|
|
root_names.push(root_name.to_string());
|
|
|
|
module_graph_loader.build_local_graph(root_name, s_map)?;
|
|
|
|
} else {
|
|
|
|
let module_specifier =
|
|
|
|
ModuleSpecifier::resolve_import(root_name, "<unknown>")?;
|
|
|
|
root_names.push(module_specifier.to_string());
|
2020-05-29 10:32:15 -04:00
|
|
|
module_graph_loader
|
|
|
|
.add_to_graph(&module_specifier, None)
|
|
|
|
.await?;
|
2020-05-18 06:59:29 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// download all additional files from TSconfig and add them to root_names
|
2020-08-31 14:12:24 -04:00
|
|
|
for type_file in type_files {
|
|
|
|
let type_specifier = ModuleSpecifier::resolve_url_or_path(&type_file)?;
|
|
|
|
module_graph_loader
|
|
|
|
.add_to_graph(&type_specifier, None)
|
|
|
|
.await?;
|
|
|
|
root_names.push(type_specifier.to_string())
|
2020-05-18 06:59:29 -04:00
|
|
|
}
|
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
Ok((root_names, module_graph_loader.get_graph()))
|
|
|
|
}
|
|
|
|
|
2020-09-26 10:33:25 -04:00
|
|
|
fn extract_js_error(error: AnyError) -> AnyError {
|
2020-09-06 15:44:29 -04:00
|
|
|
match error.downcast::<JsError>() {
|
2020-07-15 08:23:17 -04:00
|
|
|
Ok(js_error) => {
|
|
|
|
let msg = format!("Error in TS compiler:\n{}", js_error);
|
2020-09-14 12:48:57 -04:00
|
|
|
generic_error(msg)
|
2020-07-15 08:23:17 -04:00
|
|
|
}
|
2020-08-25 18:22:15 -04:00
|
|
|
Err(error) => error,
|
2020-07-15 08:23:17 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
/// This function is used by `Deno.compile()` API.
|
|
|
|
pub async fn runtime_compile(
|
2020-10-13 07:35:35 -04:00
|
|
|
program_state: &Arc<ProgramState>,
|
2020-06-19 06:27:15 -04:00
|
|
|
permissions: Permissions,
|
|
|
|
root_name: &str,
|
|
|
|
sources: &Option<HashMap<String, String>>,
|
|
|
|
maybe_options: &Option<String>,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2020-08-31 14:12:24 -04:00
|
|
|
let mut user_options = if let Some(options) = maybe_options {
|
|
|
|
tsc_config::parse_raw_config(options)?
|
|
|
|
} else {
|
|
|
|
json!({})
|
|
|
|
};
|
|
|
|
|
|
|
|
// Intentionally calling "take()" to replace value with `null` - otherwise TSC will try to load that file
|
|
|
|
// using `fileExists` API
|
|
|
|
let type_files = if let Some(types) = user_options["types"].take().as_array()
|
|
|
|
{
|
|
|
|
types
|
|
|
|
.iter()
|
|
|
|
.map(|type_value| type_value.as_str().unwrap_or("").to_string())
|
|
|
|
.filter(|type_str| !type_str.is_empty())
|
|
|
|
.collect()
|
|
|
|
} else {
|
|
|
|
vec![]
|
|
|
|
};
|
|
|
|
|
2020-10-13 07:35:35 -04:00
|
|
|
let unstable = program_state.flags.unstable;
|
2020-08-31 14:12:24 -04:00
|
|
|
|
|
|
|
let mut lib = vec![];
|
|
|
|
if let Some(user_libs) = user_options["lib"].take().as_array() {
|
|
|
|
let libs = user_libs
|
|
|
|
.iter()
|
|
|
|
.map(|type_value| type_value.as_str().unwrap_or("").to_string())
|
|
|
|
.filter(|type_str| !type_str.is_empty())
|
|
|
|
.collect::<Vec<String>>();
|
|
|
|
lib.extend(libs);
|
|
|
|
} else {
|
|
|
|
lib.push("deno.window".to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
if unstable {
|
|
|
|
lib.push("deno.unstable".to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut compiler_options = json!({
|
|
|
|
"allowJs": false,
|
|
|
|
"allowNonTsExtensions": true,
|
|
|
|
"checkJs": false,
|
|
|
|
"esModuleInterop": true,
|
2020-10-23 06:38:35 -04:00
|
|
|
"isolatedModules": true,
|
2020-08-31 14:12:24 -04:00
|
|
|
"jsx": "react",
|
|
|
|
"module": "esnext",
|
|
|
|
"sourceMap": true,
|
|
|
|
"strict": true,
|
|
|
|
"removeComments": true,
|
|
|
|
"target": "esnext",
|
|
|
|
});
|
|
|
|
|
|
|
|
tsc_config::json_merge(&mut compiler_options, &user_options);
|
|
|
|
tsc_config::json_merge(&mut compiler_options, &json!({ "lib": lib }));
|
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
let (root_names, module_graph) = create_runtime_module_graph(
|
2020-10-13 07:35:35 -04:00
|
|
|
&program_state,
|
2020-06-19 06:27:15 -04:00
|
|
|
permissions.clone(),
|
|
|
|
root_name,
|
|
|
|
sources,
|
2020-08-31 14:12:24 -04:00
|
|
|
type_files,
|
2020-06-19 06:27:15 -04:00
|
|
|
)
|
|
|
|
.await?;
|
2020-05-18 06:59:29 -04:00
|
|
|
let module_graph_json =
|
|
|
|
serde_json::to_value(module_graph).expect("Failed to serialize data");
|
|
|
|
|
2020-01-08 09:17:44 -05:00
|
|
|
let req_msg = json!({
|
2020-09-15 10:33:14 -04:00
|
|
|
"type": CompilerRequestType::RuntimeCompile,
|
2020-01-24 14:15:01 -05:00
|
|
|
"target": "runtime",
|
2020-05-18 06:59:29 -04:00
|
|
|
"rootNames": root_names,
|
|
|
|
"sourceFileMap": module_graph_json,
|
2020-08-31 14:12:24 -04:00
|
|
|
"compilerOptions": compiler_options,
|
2020-01-08 09:17:44 -05:00
|
|
|
})
|
2020-07-23 09:29:36 -04:00
|
|
|
.to_string();
|
2020-01-08 09:17:44 -05:00
|
|
|
|
2020-10-13 07:35:35 -04:00
|
|
|
let compiler = program_state.ts_compiler.clone();
|
2020-05-05 12:23:15 -04:00
|
|
|
|
2020-09-26 10:33:25 -04:00
|
|
|
let json_str =
|
2020-10-13 07:35:35 -04:00
|
|
|
execute_in_tsc(program_state.clone(), req_msg).map_err(extract_js_error)?;
|
2020-07-23 09:29:36 -04:00
|
|
|
let response: RuntimeCompileResponse = serde_json::from_str(&json_str)?;
|
2020-05-05 12:23:15 -04:00
|
|
|
|
2020-09-12 05:53:57 -04:00
|
|
|
if response.diagnostics.0.is_empty() && sources.is_none() {
|
2020-05-05 12:23:15 -04:00
|
|
|
compiler.cache_emitted_files(response.emit_map)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
// We're returning `Ok()` instead of `Err()` because it's not runtime
|
2020-06-19 06:27:15 -04:00
|
|
|
// error if there were diagnostics produced; we want to let user handle
|
|
|
|
// diagnostics in the runtime.
|
2020-07-23 09:29:36 -04:00
|
|
|
Ok(serde_json::from_str::<Value>(&json_str).unwrap())
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This function is used by `Deno.bundle()` API.
|
|
|
|
pub async fn runtime_bundle(
|
2020-10-13 07:35:35 -04:00
|
|
|
program_state: &Arc<ProgramState>,
|
2020-06-19 06:27:15 -04:00
|
|
|
permissions: Permissions,
|
|
|
|
root_name: &str,
|
|
|
|
sources: &Option<HashMap<String, String>>,
|
|
|
|
maybe_options: &Option<String>,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2020-08-31 14:12:24 -04:00
|
|
|
let mut user_options = if let Some(options) = maybe_options {
|
|
|
|
tsc_config::parse_raw_config(options)?
|
|
|
|
} else {
|
|
|
|
json!({})
|
|
|
|
};
|
|
|
|
|
|
|
|
// Intentionally calling "take()" to replace value with `null` - otherwise TSC will try to load that file
|
|
|
|
// using `fileExists` API
|
|
|
|
let type_files = if let Some(types) = user_options["types"].take().as_array()
|
|
|
|
{
|
|
|
|
types
|
|
|
|
.iter()
|
|
|
|
.map(|type_value| type_value.as_str().unwrap_or("").to_string())
|
|
|
|
.filter(|type_str| !type_str.is_empty())
|
|
|
|
.collect()
|
|
|
|
} else {
|
|
|
|
vec![]
|
|
|
|
};
|
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
let (root_names, module_graph) = create_runtime_module_graph(
|
2020-10-13 07:35:35 -04:00
|
|
|
&program_state,
|
2020-06-19 06:27:15 -04:00
|
|
|
permissions.clone(),
|
|
|
|
root_name,
|
|
|
|
sources,
|
2020-08-31 14:12:24 -04:00
|
|
|
type_files,
|
2020-06-19 06:27:15 -04:00
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
let module_graph_json =
|
|
|
|
serde_json::to_value(module_graph).expect("Failed to serialize data");
|
|
|
|
|
2020-10-13 07:35:35 -04:00
|
|
|
let unstable = program_state.flags.unstable;
|
2020-08-31 14:12:24 -04:00
|
|
|
|
|
|
|
let mut lib = vec![];
|
|
|
|
if let Some(user_libs) = user_options["lib"].take().as_array() {
|
|
|
|
let libs = user_libs
|
|
|
|
.iter()
|
|
|
|
.map(|type_value| type_value.as_str().unwrap_or("").to_string())
|
|
|
|
.filter(|type_str| !type_str.is_empty())
|
|
|
|
.collect::<Vec<String>>();
|
|
|
|
lib.extend(libs);
|
|
|
|
} else {
|
|
|
|
lib.push("deno.window".to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
if unstable {
|
|
|
|
lib.push("deno.unstable".to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut compiler_options = json!({
|
|
|
|
"allowJs": false,
|
|
|
|
"allowNonTsExtensions": true,
|
|
|
|
"checkJs": false,
|
|
|
|
"esModuleInterop": true,
|
|
|
|
"jsx": "react",
|
|
|
|
"module": "esnext",
|
|
|
|
"outDir": null,
|
|
|
|
"sourceMap": true,
|
|
|
|
"strict": true,
|
|
|
|
"removeComments": true,
|
|
|
|
"target": "esnext",
|
|
|
|
});
|
|
|
|
|
|
|
|
let bundler_options = json!({
|
|
|
|
"allowJs": true,
|
|
|
|
"inlineSourceMap": false,
|
|
|
|
"module": "system",
|
|
|
|
"outDir": null,
|
|
|
|
"outFile": "deno:///bundle.js",
|
|
|
|
// disabled until we have effective way to modify source maps
|
|
|
|
"sourceMap": false,
|
|
|
|
});
|
|
|
|
|
|
|
|
tsc_config::json_merge(&mut compiler_options, &user_options);
|
|
|
|
tsc_config::json_merge(&mut compiler_options, &json!({ "lib": lib }));
|
|
|
|
tsc_config::json_merge(&mut compiler_options, &bundler_options);
|
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
let req_msg = json!({
|
2020-09-15 10:33:14 -04:00
|
|
|
"type": CompilerRequestType::RuntimeBundle,
|
2020-06-19 06:27:15 -04:00
|
|
|
"target": "runtime",
|
|
|
|
"rootNames": root_names,
|
|
|
|
"sourceFileMap": module_graph_json,
|
2020-08-31 14:12:24 -04:00
|
|
|
"compilerOptions": compiler_options,
|
2020-06-19 06:27:15 -04:00
|
|
|
})
|
2020-07-23 09:29:36 -04:00
|
|
|
.to_string();
|
2020-06-19 06:27:15 -04:00
|
|
|
|
2020-09-26 10:33:25 -04:00
|
|
|
let json_str =
|
2020-10-13 07:35:35 -04:00
|
|
|
execute_in_tsc(program_state.clone(), req_msg).map_err(extract_js_error)?;
|
2020-07-23 09:29:36 -04:00
|
|
|
let _response: RuntimeBundleResponse = serde_json::from_str(&json_str)?;
|
2020-06-19 06:27:15 -04:00
|
|
|
// We're returning `Ok()` instead of `Err()` because it's not runtime
|
|
|
|
// error if there were diagnostics produced; we want to let user handle
|
2020-05-05 12:23:15 -04:00
|
|
|
// diagnostics in the runtime.
|
2020-07-23 09:29:36 -04:00
|
|
|
Ok(serde_json::from_str::<Value>(&json_str).unwrap())
|
2020-01-08 09:17:44 -05:00
|
|
|
}
|
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
|
|
pub struct ImportDesc {
|
|
|
|
pub specifier: String,
|
|
|
|
pub deno_types: Option<String>,
|
|
|
|
pub location: Location,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
|
|
pub enum TsReferenceKind {
|
|
|
|
Lib,
|
|
|
|
Types,
|
|
|
|
Path,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
|
|
pub struct TsReferenceDesc {
|
|
|
|
pub kind: TsReferenceKind,
|
|
|
|
pub specifier: String,
|
|
|
|
pub location: Location,
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bartlomieju): handle imports in ambient contexts/TS modules
|
|
|
|
/// This function is a port of `ts.preProcessFile()`
|
|
|
|
///
|
|
|
|
/// Additionally it captures `@deno-types` references directly
|
|
|
|
/// preceeding `import .. from` and `export .. from` statements.
|
|
|
|
pub fn pre_process_file(
|
|
|
|
file_name: &str,
|
|
|
|
media_type: MediaType,
|
|
|
|
source_code: &str,
|
|
|
|
analyze_dynamic_imports: bool,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<(Vec<ImportDesc>, Vec<TsReferenceDesc>), AnyError> {
|
2020-09-14 08:27:44 -04:00
|
|
|
let specifier = ModuleSpecifier::resolve_url_or_path(file_name)?;
|
2020-10-26 09:03:03 -04:00
|
|
|
let module = parse(specifier.as_str(), source_code, &media_type)?;
|
2020-09-14 08:27:44 -04:00
|
|
|
|
|
|
|
let dependency_descriptors = module.analyze_dependencies();
|
2020-07-31 10:59:22 -04:00
|
|
|
|
|
|
|
// for each import check if there's relevant @deno-types directive
|
|
|
|
let imports = dependency_descriptors
|
|
|
|
.iter()
|
2020-09-03 11:11:30 -04:00
|
|
|
.filter(|desc| desc.kind != dep_graph::DependencyKind::Require)
|
2020-07-31 10:59:22 -04:00
|
|
|
.filter(|desc| {
|
|
|
|
if analyze_dynamic_imports {
|
|
|
|
return true;
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
2020-09-03 11:11:30 -04:00
|
|
|
!desc.is_dynamic
|
2020-07-31 10:59:22 -04:00
|
|
|
})
|
|
|
|
.map(|desc| {
|
2020-09-03 11:11:30 -04:00
|
|
|
let deno_types = get_deno_types(&desc.leading_comments);
|
2020-07-31 10:59:22 -04:00
|
|
|
ImportDesc {
|
|
|
|
specifier: desc.specifier.to_string(),
|
|
|
|
deno_types,
|
2020-09-03 11:11:30 -04:00
|
|
|
location: Location {
|
|
|
|
filename: file_name.to_string(),
|
|
|
|
col: desc.col,
|
|
|
|
line: desc.line,
|
|
|
|
},
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
2020-07-31 10:59:22 -04:00
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
// analyze comment from beginning of the file and find TS directives
|
2020-09-14 08:27:44 -04:00
|
|
|
let comments = module.get_leading_comments();
|
2020-07-31 10:59:22 -04:00
|
|
|
|
|
|
|
let mut references = vec![];
|
|
|
|
for comment in comments {
|
|
|
|
if comment.kind != CommentKind::Line {
|
|
|
|
continue;
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
2020-07-31 10:59:22 -04:00
|
|
|
|
|
|
|
let text = comment.text.to_string();
|
|
|
|
if let Some((kind, specifier)) = parse_ts_reference(text.trim()) {
|
2020-09-14 08:27:44 -04:00
|
|
|
let location = module.get_location(&comment.span);
|
2020-07-31 10:59:22 -04:00
|
|
|
references.push(TsReferenceDesc {
|
|
|
|
kind,
|
|
|
|
specifier,
|
2020-09-14 08:27:44 -04:00
|
|
|
location,
|
2020-07-31 10:59:22 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok((imports, references))
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
|
|
|
|
2020-09-03 11:11:30 -04:00
|
|
|
fn get_deno_types(comments: &[Comment]) -> Option<String> {
|
2020-06-19 06:27:15 -04:00
|
|
|
if comments.is_empty() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
// @deno-types must directly prepend import statement - hence
|
|
|
|
// checking last comment for span
|
|
|
|
let last = comments.last().unwrap();
|
|
|
|
let comment = last.text.trim_start();
|
|
|
|
parse_deno_types(&comment)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn parse_ts_reference(comment: &str) -> Option<(TsReferenceKind, String)> {
|
2020-09-04 04:44:31 -04:00
|
|
|
if !TRIPLE_SLASH_REFERENCE_RE.is_match(comment) {
|
2020-06-19 06:27:15 -04:00
|
|
|
return None;
|
2020-07-11 12:30:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
let (kind, specifier) =
|
|
|
|
if let Some(capture_groups) = PATH_REFERENCE_RE.captures(comment) {
|
2020-09-04 04:44:31 -04:00
|
|
|
(TsReferenceKind::Path, capture_groups.get(1).unwrap())
|
2020-07-11 12:30:30 -04:00
|
|
|
} else if let Some(capture_groups) = TYPES_REFERENCE_RE.captures(comment) {
|
2020-09-04 04:44:31 -04:00
|
|
|
(TsReferenceKind::Types, capture_groups.get(1).unwrap())
|
2020-07-11 12:30:30 -04:00
|
|
|
} else if let Some(capture_groups) = LIB_REFERENCE_RE.captures(comment) {
|
2020-09-04 04:44:31 -04:00
|
|
|
(TsReferenceKind::Lib, capture_groups.get(1).unwrap())
|
2020-07-11 12:30:30 -04:00
|
|
|
} else {
|
|
|
|
return None;
|
|
|
|
};
|
|
|
|
|
|
|
|
Some((kind, specifier.as_str().to_string()))
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn parse_deno_types(comment: &str) -> Option<String> {
|
2020-07-11 12:30:30 -04:00
|
|
|
if let Some(capture_groups) = DENO_TYPES_RE.captures(comment) {
|
|
|
|
if let Some(specifier) = capture_groups.get(1) {
|
2020-09-04 04:44:31 -04:00
|
|
|
return Some(specifier.as_str().to_string());
|
|
|
|
}
|
|
|
|
if let Some(specifier) = capture_groups.get(2) {
|
|
|
|
return Some(specifier.as_str().to_string());
|
2020-07-11 12:30:30 -04:00
|
|
|
}
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
2020-09-15 10:33:14 -04:00
|
|
|
// Warning! The values in this enum are duplicated in js/compiler.ts
|
|
|
|
// Update carefully!
|
|
|
|
#[repr(i32)]
|
|
|
|
#[derive(Clone, Copy, PartialEq, Debug)]
|
|
|
|
pub enum CompilerRequestType {
|
|
|
|
RuntimeCompile = 2,
|
|
|
|
RuntimeBundle = 3,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Serialize for CompilerRequestType {
|
|
|
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
|
|
where
|
|
|
|
S: Serializer,
|
|
|
|
{
|
|
|
|
let value: i32 = match self {
|
|
|
|
CompilerRequestType::RuntimeCompile => 2 as i32,
|
|
|
|
CompilerRequestType::RuntimeBundle => 3 as i32,
|
|
|
|
};
|
|
|
|
Serialize::serialize(&value, serializer)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-09 12:59:46 -05:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2019-08-17 12:53:34 -04:00
|
|
|
use crate::fs as deno_fs;
|
|
|
|
use tempfile::TempDir;
|
2019-07-17 18:15:30 -04:00
|
|
|
|
2020-06-19 06:27:15 -04:00
|
|
|
#[test]
|
|
|
|
fn test_parse_deno_types() {
|
|
|
|
assert_eq!(
|
|
|
|
parse_deno_types("@deno-types=./a/b/c.d.ts"),
|
|
|
|
Some("./a/b/c.d.ts".to_string())
|
|
|
|
);
|
2020-07-11 12:30:30 -04:00
|
|
|
assert_eq!(
|
|
|
|
parse_deno_types("@deno-types=\"./a/b/c.d.ts\""),
|
|
|
|
Some("./a/b/c.d.ts".to_string())
|
|
|
|
);
|
2020-06-19 06:27:15 -04:00
|
|
|
assert_eq!(
|
|
|
|
parse_deno_types("@deno-types = https://dneo.land/x/some/package/a.d.ts"),
|
|
|
|
Some("https://dneo.land/x/some/package/a.d.ts".to_string())
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
parse_deno_types("@deno-types = ./a/b/c.d.ts"),
|
|
|
|
Some("./a/b/c.d.ts".to_string())
|
|
|
|
);
|
|
|
|
assert!(parse_deno_types("asdf").is_none());
|
|
|
|
assert!(parse_deno_types("// deno-types = fooo").is_none());
|
2020-07-11 12:30:30 -04:00
|
|
|
assert_eq!(
|
|
|
|
parse_deno_types("@deno-types=./a/b/c.d.ts some comment"),
|
|
|
|
Some("./a/b/c.d.ts".to_string())
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
parse_deno_types(
|
|
|
|
"@deno-types=./a/b/c.d.ts // some comment after slashes"
|
|
|
|
),
|
|
|
|
Some("./a/b/c.d.ts".to_string())
|
|
|
|
);
|
2020-09-04 04:44:31 -04:00
|
|
|
assert_eq!(
|
|
|
|
parse_deno_types(r#"@deno-types="https://deno.land/x/foo/index.d.ts";"#),
|
|
|
|
Some("https://deno.land/x/foo/index.d.ts".to_string())
|
|
|
|
);
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_parse_ts_reference() {
|
|
|
|
assert_eq!(
|
|
|
|
parse_ts_reference(r#"/ <reference lib="deno.shared_globals" />"#),
|
|
|
|
Some((TsReferenceKind::Lib, "deno.shared_globals".to_string()))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
parse_ts_reference(r#"/ <reference path="./type/reference/dep.ts" />"#),
|
|
|
|
Some((TsReferenceKind::Path, "./type/reference/dep.ts".to_string()))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
parse_ts_reference(r#"/ <reference types="./type/reference.d.ts" />"#),
|
|
|
|
Some((TsReferenceKind::Types, "./type/reference.d.ts".to_string()))
|
|
|
|
);
|
|
|
|
assert!(parse_ts_reference("asdf").is_none());
|
|
|
|
assert!(
|
|
|
|
parse_ts_reference(r#"/ <reference unknown="unknown" />"#).is_none()
|
|
|
|
);
|
2020-09-04 04:44:31 -04:00
|
|
|
assert!(parse_ts_reference(r#"/ <asset path="./styles.css" />"#).is_none());
|
2020-06-19 06:27:15 -04:00
|
|
|
}
|
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
#[test]
|
|
|
|
fn test_source_code_version_hash() {
|
|
|
|
assert_eq!(
|
2019-08-28 18:58:42 -04:00
|
|
|
"0185b42de0686b4c93c314daaa8dee159f768a9e9a336c2a5e3d5b8ca6c4208c",
|
2019-07-17 18:15:30 -04:00
|
|
|
source_code_version_hash(b"1+2", "0.4.0", b"{}")
|
|
|
|
);
|
|
|
|
// Different source_code should result in different hash.
|
|
|
|
assert_eq!(
|
2019-08-28 18:58:42 -04:00
|
|
|
"e58631f1b6b6ce2b300b133ec2ad16a8a5ba6b7ecf812a8c06e59056638571ac",
|
2019-07-17 18:15:30 -04:00
|
|
|
source_code_version_hash(b"1", "0.4.0", b"{}")
|
|
|
|
);
|
|
|
|
// Different version should result in different hash.
|
|
|
|
assert_eq!(
|
2019-08-28 18:58:42 -04:00
|
|
|
"307e6200347a88dbbada453102deb91c12939c65494e987d2d8978f6609b5633",
|
2019-07-17 18:15:30 -04:00
|
|
|
source_code_version_hash(b"1", "0.1.0", b"{}")
|
|
|
|
);
|
|
|
|
// Different config should result in different hash.
|
|
|
|
assert_eq!(
|
2019-08-28 18:58:42 -04:00
|
|
|
"195eaf104a591d1d7f69fc169c60a41959c2b7a21373cd23a8f675f877ec385f",
|
2019-07-17 18:15:30 -04:00
|
|
|
source_code_version_hash(b"1", "0.4.0", b"{\"compilerOptions\": {}}")
|
|
|
|
);
|
|
|
|
}
|
2019-08-17 12:53:34 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_compile_js() {
|
|
|
|
let temp_dir = TempDir::new().expect("tempdir fail");
|
|
|
|
let temp_dir_path = temp_dir.path();
|
|
|
|
|
|
|
|
let test_cases = vec![
|
|
|
|
// valid JSON
|
2019-12-23 09:59:44 -05:00
|
|
|
(r#"{ "compilerOptions": { "checkJs": true } } "#, true),
|
2019-08-17 12:53:34 -04:00
|
|
|
// JSON with comment
|
|
|
|
(
|
2020-09-09 08:23:57 -04:00
|
|
|
r#"{
|
|
|
|
"compilerOptions": {
|
|
|
|
// force .js file compilation by Deno
|
|
|
|
"checkJs": true
|
|
|
|
}
|
2020-08-31 14:12:24 -04:00
|
|
|
}"#,
|
2019-08-17 12:53:34 -04:00
|
|
|
true,
|
|
|
|
),
|
|
|
|
// without content
|
2019-12-23 09:59:44 -05:00
|
|
|
("", false),
|
2019-08-17 12:53:34 -04:00
|
|
|
];
|
|
|
|
|
|
|
|
let path = temp_dir_path.join("tsconfig.json");
|
|
|
|
let path_str = path.to_str().unwrap().to_string();
|
|
|
|
|
|
|
|
for (json_str, expected) in test_cases {
|
|
|
|
deno_fs::write_file(&path, json_str.as_bytes(), 0o666).unwrap();
|
|
|
|
let config = CompilerConfig::load(Some(path_str.clone())).unwrap();
|
|
|
|
assert_eq!(config.compile_js, expected);
|
|
|
|
}
|
|
|
|
}
|
2019-09-20 10:19:51 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_compiler_config_load() {
|
|
|
|
let temp_dir = TempDir::new().expect("tempdir fail");
|
|
|
|
let temp_dir_path = temp_dir.path();
|
|
|
|
let path = temp_dir_path.join("doesnotexist.json");
|
|
|
|
let path_str = path.to_str().unwrap().to_string();
|
2019-12-23 09:59:44 -05:00
|
|
|
let res = CompilerConfig::load(Some(path_str));
|
2019-09-20 10:19:51 -04:00
|
|
|
assert!(res.is_err());
|
|
|
|
}
|
2019-01-09 12:59:46 -05:00
|
|
|
}
|