2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-01-08 09:17:44 -05:00
|
|
|
use crate::compilers::CompilationResultFuture;
|
2019-07-31 13:16:03 -04:00
|
|
|
use crate::compilers::CompiledModule;
|
|
|
|
use crate::compilers::CompiledModuleFuture;
|
2019-06-04 09:03:56 -04:00
|
|
|
use crate::diagnostics::Diagnostic;
|
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;
|
2019-11-04 10:38:52 -05:00
|
|
|
use crate::global_state::ThreadSafeGlobalState;
|
2019-01-14 01:30:38 -05:00
|
|
|
use crate::msg;
|
2020-01-08 09:17:44 -05:00
|
|
|
use crate::serde_json::json;
|
2019-07-17 18:15:30 -04:00
|
|
|
use crate::source_maps::SourceMapGetter;
|
2019-03-18 20:03:37 -04:00
|
|
|
use crate::startup_data;
|
2019-04-09 13:11:25 -04:00
|
|
|
use crate::state::*;
|
2019-07-17 18:15:30 -04:00
|
|
|
use crate::version;
|
2019-04-08 17:10:00 -04:00
|
|
|
use crate::worker::Worker;
|
2020-01-05 11:56:18 -05:00
|
|
|
use deno_core::Buf;
|
|
|
|
use deno_core::ErrBox;
|
|
|
|
use deno_core::ModuleSpecifier;
|
2019-11-16 19:17:47 -05:00
|
|
|
use futures::future::FutureExt;
|
2019-01-09 12:59:46 -05:00
|
|
|
use futures::Future;
|
2019-08-17 12:53:34 -04:00
|
|
|
use regex::Regex;
|
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;
|
2020-01-08 09:17:44 -05:00
|
|
|
use std::hash::BuildHasher;
|
2019-09-20 10:19:51 -04:00
|
|
|
use std::io;
|
2019-06-24 13:10:21 -04:00
|
|
|
use std::path::PathBuf;
|
2019-11-16 19:17:47 -05:00
|
|
|
use std::pin::Pin;
|
2019-02-18 10:42:15 -05:00
|
|
|
use std::str;
|
2019-04-04 05:33:32 -04:00
|
|
|
use std::sync::atomic::Ordering;
|
2019-07-17 18:15:30 -04:00
|
|
|
use std::sync::Mutex;
|
|
|
|
use url::Url;
|
2019-01-09 12:59:46 -05:00
|
|
|
|
2019-08-17 12:53:34 -04:00
|
|
|
lazy_static! {
|
|
|
|
static ref CHECK_JS_RE: Regex =
|
|
|
|
Regex::new(r#""checkJs"\s*?:\s*?true"#).unwrap();
|
|
|
|
}
|
|
|
|
|
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>,
|
|
|
|
pub content: Option<Vec<u8>>,
|
|
|
|
pub hash: Vec<u8>,
|
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.
|
|
|
|
pub fn load(config_path: Option<String>) -> Result<Self, ErrBox> {
|
|
|
|
let config_file = match &config_path {
|
|
|
|
Some(config_file_name) => {
|
|
|
|
debug!("Compiler config file: {}", config_file_name);
|
|
|
|
let cwd = std::env::current_dir().unwrap();
|
|
|
|
Some(cwd.join(config_file_name))
|
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Convert the PathBuf to a canonicalized string. This is needed by the
|
|
|
|
// compiler to properly deal with the configuration.
|
|
|
|
let config_path = match &config_file {
|
2019-12-23 09:59:44 -05:00
|
|
|
Some(config_file) => Some(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
|
|
|
_ => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Load the contents of the configuration file
|
|
|
|
let config = match &config_file {
|
|
|
|
Some(config_file) => {
|
|
|
|
debug!("Attempt to load config: {}", config_file.to_str().unwrap());
|
|
|
|
let config = fs::read(&config_file)?;
|
|
|
|
Some(config)
|
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
let config_hash = match &config {
|
|
|
|
Some(bytes) => bytes.clone(),
|
|
|
|
_ => b"".to_vec(),
|
|
|
|
};
|
|
|
|
|
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
|
|
|
|
let compile_js = if let Some(config_content) = config.clone() {
|
|
|
|
let config_str = std::str::from_utf8(&config_content)?;
|
|
|
|
CHECK_JS_RE.is_match(config_str)
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
|
2019-07-31 13:16:03 -04:00
|
|
|
let ts_config = Self {
|
2019-12-23 09:59:44 -05:00
|
|
|
path: config_path.unwrap_or_else(|| Ok(PathBuf::new())).ok(),
|
2019-07-31 13:16:03 -04:00
|
|
|
content: config,
|
|
|
|
hash: config_hash,
|
2019-08-17 12:53:34 -04:00
|
|
|
compile_js,
|
2019-07-31 13:16:03 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
Ok(ts_config)
|
|
|
|
}
|
|
|
|
}
|
2019-07-17 18:15:30 -04:00
|
|
|
|
|
|
|
/// Information associated with compiled file in cache.
|
|
|
|
/// Includes source code path and state hash.
|
|
|
|
/// version_hash is used to validate versions of the file
|
|
|
|
/// and could be used to remove stale file in cache.
|
|
|
|
pub struct CompiledFileMetadata {
|
|
|
|
pub source_path: PathBuf,
|
|
|
|
pub version_hash: String,
|
2019-01-09 12:59:46 -05:00
|
|
|
}
|
|
|
|
|
2019-08-16 20:49:00 -04:00
|
|
|
static SOURCE_PATH: &str = "source_path";
|
|
|
|
static VERSION_HASH: &str = "version_hash";
|
2019-03-28 16:05:41 -04:00
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
impl CompiledFileMetadata {
|
|
|
|
pub fn from_json_string(metadata_string: String) -> Option<Self> {
|
|
|
|
// TODO: use serde for deserialization
|
|
|
|
let maybe_metadata_json: serde_json::Result<serde_json::Value> =
|
|
|
|
serde_json::from_str(&metadata_string);
|
|
|
|
|
|
|
|
if let Ok(metadata_json) = maybe_metadata_json {
|
|
|
|
let source_path = metadata_json[SOURCE_PATH].as_str().map(PathBuf::from);
|
|
|
|
let version_hash = metadata_json[VERSION_HASH].as_str().map(String::from);
|
|
|
|
|
|
|
|
if source_path.is_none() || version_hash.is_none() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Some(CompiledFileMetadata {
|
|
|
|
source_path: source_path.unwrap(),
|
|
|
|
version_hash: version_hash.unwrap(),
|
|
|
|
});
|
2019-01-09 12:59:46 -05:00
|
|
|
}
|
2019-07-17 18:15:30 -04:00
|
|
|
|
|
|
|
None
|
2019-01-09 12:59:46 -05:00
|
|
|
}
|
|
|
|
|
2020-01-04 05:20:52 -05:00
|
|
|
pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
|
2019-07-17 18:15:30 -04:00
|
|
|
let mut value_map = serde_json::map::Map::new();
|
2019-04-08 17:10:00 -04:00
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
value_map.insert(SOURCE_PATH.to_owned(), json!(&self.source_path));
|
|
|
|
value_map.insert(VERSION_HASH.to_string(), json!(&self.version_hash));
|
|
|
|
serde_json::to_string(&value_map)
|
|
|
|
}
|
|
|
|
}
|
2019-05-20 12:06:57 -04:00
|
|
|
/// Creates the JSON message send to compiler.ts's onmessage.
|
2019-06-08 14:42:28 -04:00
|
|
|
fn req(
|
2019-11-13 10:35:56 -05:00
|
|
|
request_type: msg::CompilerRequestType,
|
2019-06-08 14:42:28 -04:00
|
|
|
root_names: Vec<String>,
|
|
|
|
compiler_config: CompilerConfig,
|
2019-11-13 10:35:56 -05:00
|
|
|
out_file: Option<String>,
|
2020-01-08 09:17:44 -05:00
|
|
|
bundle: bool,
|
2019-06-08 14:42:28 -04:00
|
|
|
) -> Buf {
|
2019-07-31 13:16:03 -04:00
|
|
|
let j = match (compiler_config.path, compiler_config.content) {
|
|
|
|
(Some(config_path), Some(config_data)) => json!({
|
2019-11-13 10:35:56 -05:00
|
|
|
"type": request_type as i32,
|
2019-07-31 17:11:37 -04:00
|
|
|
"rootNames": root_names,
|
2019-11-13 10:35:56 -05:00
|
|
|
"outFile": out_file,
|
2020-01-08 09:17:44 -05:00
|
|
|
"bundle": bundle,
|
2019-07-31 17:11:37 -04:00
|
|
|
"configPath": config_path,
|
|
|
|
"config": str::from_utf8(&config_data).unwrap(),
|
|
|
|
}),
|
2019-07-31 13:16:03 -04:00
|
|
|
_ => json!({
|
2019-11-13 10:35:56 -05:00
|
|
|
"type": request_type as i32,
|
2019-07-31 17:11:37 -04:00
|
|
|
"rootNames": root_names,
|
2019-11-13 10:35:56 -05:00
|
|
|
"outFile": out_file,
|
2020-01-08 09:17:44 -05:00
|
|
|
"bundle": bundle,
|
2019-07-31 17:11:37 -04:00
|
|
|
}),
|
2019-05-20 12:06:57 -04:00
|
|
|
};
|
2019-07-31 13:16:03 -04:00
|
|
|
|
2019-05-20 12:06:57 -04:00
|
|
|
j.to_string().into_boxed_str().into_boxed_bytes()
|
2019-01-09 12:59:46 -05: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.
|
|
|
|
pub fn source_code_version_hash(
|
|
|
|
source_code: &[u8],
|
|
|
|
version: &str,
|
|
|
|
config_hash: &[u8],
|
|
|
|
) -> String {
|
2019-11-03 10:39:27 -05:00
|
|
|
crate::checksum::gen(vec![source_code, version.as_bytes(), config_hash])
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct TsCompiler {
|
2019-07-31 07:58:41 -04:00
|
|
|
pub file_fetcher: SourceFileFetcher,
|
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
|
|
|
}
|
|
|
|
|
|
|
|
impl TsCompiler {
|
|
|
|
pub fn new(
|
2019-07-31 07:58:41 -04:00
|
|
|
file_fetcher: SourceFileFetcher,
|
|
|
|
disk_cache: DiskCache,
|
2019-07-17 18:15:30 -04:00
|
|
|
use_disk_cache: bool,
|
|
|
|
config_path: Option<String>,
|
2019-07-31 13:16:03 -04:00
|
|
|
) -> Result<Self, ErrBox> {
|
|
|
|
let config = CompilerConfig::load(config_path)?;
|
|
|
|
|
|
|
|
let compiler = Self {
|
2019-07-31 07:58:41 -04:00
|
|
|
file_fetcher,
|
|
|
|
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,
|
2019-07-31 13:16:03 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
Ok(compiler)
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a new V8 worker with snapshot of TS compiler and setup compiler's runtime.
|
2019-11-04 10:38:52 -05:00
|
|
|
fn setup_worker(global_state: ThreadSafeGlobalState) -> Worker {
|
2019-11-09 15:07:14 -05:00
|
|
|
let (int, ext) = ThreadSafeState::create_channels();
|
|
|
|
let worker_state =
|
2020-01-21 03:49:47 -05:00
|
|
|
ThreadSafeState::new(global_state.clone(), None, None, int)
|
2019-11-09 15:07:14 -05:00
|
|
|
.expect("Unable to create worker state");
|
2019-11-04 10:38:52 -05:00
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
// Count how many times we start the compiler worker.
|
2019-11-04 10:38:52 -05:00
|
|
|
global_state
|
|
|
|
.metrics
|
|
|
|
.compiler_starts
|
|
|
|
.fetch_add(1, Ordering::SeqCst);
|
2019-07-17 18:15:30 -04:00
|
|
|
|
|
|
|
let mut worker = Worker::new(
|
|
|
|
"TS".to_string(),
|
|
|
|
startup_data::compiler_isolate_init(),
|
2019-11-04 10:38:52 -05:00
|
|
|
worker_state,
|
2019-11-09 15:07:14 -05:00
|
|
|
ext,
|
2019-07-17 18:15:30 -04:00
|
|
|
);
|
|
|
|
worker.execute("denoMain()").unwrap();
|
|
|
|
worker.execute("workerMain()").unwrap();
|
|
|
|
worker.execute("compilerMain()").unwrap();
|
|
|
|
worker
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn bundle_async(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-11-04 10:38:52 -05:00
|
|
|
global_state: ThreadSafeGlobalState,
|
2019-07-17 18:15:30 -04:00
|
|
|
module_name: String,
|
2019-11-13 10:35:56 -05:00
|
|
|
out_file: Option<String>,
|
2019-11-16 19:17:47 -05:00
|
|
|
) -> impl Future<Output = Result<(), ErrBox>> {
|
2019-07-17 18:15:30 -04:00
|
|
|
debug!(
|
|
|
|
"Invoking the compiler to bundle. module_name: {}",
|
|
|
|
module_name
|
|
|
|
);
|
|
|
|
|
2019-12-23 09:59:44 -05:00
|
|
|
let root_names = vec![module_name];
|
2019-11-13 10:35:56 -05:00
|
|
|
let req_msg = req(
|
2020-01-08 09:17:44 -05:00
|
|
|
msg::CompilerRequestType::Compile,
|
2019-11-13 10:35:56 -05:00
|
|
|
root_names,
|
|
|
|
self.config.clone(),
|
|
|
|
out_file,
|
2020-01-08 09:17:44 -05:00
|
|
|
true,
|
2019-11-13 10:35:56 -05:00
|
|
|
);
|
2019-07-17 18:15:30 -04:00
|
|
|
|
2019-12-23 09:59:44 -05:00
|
|
|
let worker = TsCompiler::setup_worker(global_state);
|
2019-11-04 10:38:52 -05:00
|
|
|
let worker_ = worker.clone();
|
2019-07-17 18:15:30 -04:00
|
|
|
|
2019-11-22 12:14:34 -05:00
|
|
|
async move {
|
|
|
|
worker.post_message(req_msg).await?;
|
|
|
|
worker.await?;
|
|
|
|
debug!("Sent message to worker");
|
|
|
|
let maybe_msg = worker_.get_message().await?;
|
|
|
|
debug!("Received message from worker");
|
|
|
|
if let Some(msg) = maybe_msg {
|
|
|
|
let json_str = std::str::from_utf8(&msg).unwrap();
|
|
|
|
debug!("Message: {}", json_str);
|
|
|
|
if let Some(diagnostics) = Diagnostic::from_emit_result(json_str) {
|
|
|
|
return Err(ErrBox::from(diagnostics));
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
2019-11-22 12:14:34 -05:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Mark given module URL as compiled to avoid multiple compilations of same module
|
|
|
|
/// in single run.
|
|
|
|
fn mark_compiled(&self, url: &Url) {
|
|
|
|
let mut c = self.compiled.lock().unwrap();
|
|
|
|
c.insert(url.clone());
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if given module URL has already been compiled and can be fetched directly from disk.
|
|
|
|
fn has_compiled(&self, url: &Url) -> bool {
|
|
|
|
let c = self.compiled.lock().unwrap();
|
|
|
|
c.contains(url)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Asynchronously compile module and all it's dependencies.
|
|
|
|
///
|
|
|
|
/// This method compiled every module at most once.
|
|
|
|
///
|
|
|
|
/// If `--reload` flag was provided then compiler will not on-disk cache and force recompilation.
|
|
|
|
///
|
|
|
|
/// If compilation is required then new V8 worker is spawned with fresh TS compiler.
|
|
|
|
pub fn compile_async(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-11-04 10:38:52 -05:00
|
|
|
global_state: ThreadSafeGlobalState,
|
2019-07-17 18:15:30 -04:00
|
|
|
source_file: &SourceFile,
|
2019-11-16 19:17:47 -05:00
|
|
|
) -> Pin<Box<CompiledModuleFuture>> {
|
2019-07-17 18:15:30 -04:00
|
|
|
if self.has_compiled(&source_file.url) {
|
2019-07-31 13:16:03 -04:00
|
|
|
return match self.get_compiled_module(&source_file.url) {
|
2019-11-16 19:17:47 -05:00
|
|
|
Ok(compiled) => futures::future::ok(compiled).boxed(),
|
|
|
|
Err(err) => futures::future::err(err).boxed(),
|
2019-07-31 13:16:03 -04:00
|
|
|
};
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if self.use_disk_cache {
|
|
|
|
// Try to load cached version:
|
|
|
|
// 1. check if there's 'meta' file
|
|
|
|
if let Some(metadata) = self.get_metadata(&source_file.url) {
|
|
|
|
// 2. compare version hashes
|
|
|
|
// TODO: it would probably be good idea to make it method implemented on SourceFile
|
|
|
|
let version_hash_to_validate = source_code_version_hash(
|
|
|
|
&source_file.source_code,
|
|
|
|
version::DENO,
|
2019-07-31 13:16:03 -04:00
|
|
|
&self.config.hash,
|
2019-07-17 18:15:30 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
if metadata.version_hash == version_hash_to_validate {
|
|
|
|
debug!("load_cache metadata version hash match");
|
|
|
|
if let Ok(compiled_module) =
|
2019-07-31 13:16:03 -04:00
|
|
|
self.get_compiled_module(&source_file.url)
|
2019-07-17 18:15:30 -04:00
|
|
|
{
|
2019-07-31 13:16:03 -04:00
|
|
|
self.mark_compiled(&source_file.url);
|
2019-11-16 19:17:47 -05:00
|
|
|
return futures::future::ok(compiled_module).boxed();
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
2019-06-08 14:42:28 -04:00
|
|
|
}
|
|
|
|
}
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
2019-06-08 14:42:28 -04:00
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
let source_file_ = source_file.clone();
|
|
|
|
|
|
|
|
debug!(">>>>> compile_sync START");
|
|
|
|
let module_url = source_file.url.clone();
|
|
|
|
|
|
|
|
debug!(
|
|
|
|
"Running rust part of compile_sync, module specifier: {}",
|
|
|
|
&source_file.url
|
|
|
|
);
|
|
|
|
|
|
|
|
let root_names = vec![module_url.to_string()];
|
2019-11-13 10:35:56 -05:00
|
|
|
let req_msg = req(
|
|
|
|
msg::CompilerRequestType::Compile,
|
|
|
|
root_names,
|
|
|
|
self.config.clone(),
|
|
|
|
None,
|
2020-01-08 09:17:44 -05:00
|
|
|
false,
|
2019-11-13 10:35:56 -05:00
|
|
|
);
|
2019-07-17 18:15:30 -04:00
|
|
|
|
2019-11-04 10:38:52 -05:00
|
|
|
let worker = TsCompiler::setup_worker(global_state.clone());
|
|
|
|
let worker_ = worker.clone();
|
|
|
|
let compiling_job = global_state
|
|
|
|
.progress
|
|
|
|
.add("Compile", &module_url.to_string());
|
2019-12-23 09:59:44 -05:00
|
|
|
let global_state_ = global_state;
|
2019-11-04 10:38:52 -05:00
|
|
|
|
2019-11-22 12:14:34 -05:00
|
|
|
async move {
|
|
|
|
worker.post_message(req_msg).await?;
|
|
|
|
worker.await?;
|
2019-11-16 19:17:47 -05:00
|
|
|
debug!("Sent message to worker");
|
2019-11-22 12:14:34 -05:00
|
|
|
let maybe_msg = worker_.get_message().await?;
|
|
|
|
if let Some(msg) = maybe_msg {
|
|
|
|
let json_str = std::str::from_utf8(&msg).unwrap();
|
|
|
|
debug!("Message: {}", json_str);
|
|
|
|
if let Some(diagnostics) = Diagnostic::from_emit_result(json_str) {
|
|
|
|
return Err(ErrBox::from(diagnostics));
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
2019-11-22 12:14:34 -05:00
|
|
|
}
|
|
|
|
let compiled_module = global_state_
|
|
|
|
.ts_compiler
|
|
|
|
.get_compiled_module(&source_file_.url)
|
|
|
|
.expect("Expected to find compiled file");
|
|
|
|
drop(compiling_job);
|
|
|
|
debug!(">>>>> compile_sync END");
|
|
|
|
Ok(compiled_module)
|
|
|
|
}
|
2019-12-23 09:59:44 -05:00
|
|
|
.boxed()
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get associated `CompiledFileMetadata` for given module if it exists.
|
2020-01-04 05:20:52 -05:00
|
|
|
pub fn get_metadata(&self, url: &Url) -> Option<CompiledFileMetadata> {
|
2019-07-17 18:15:30 -04:00
|
|
|
// Try to load cached version:
|
|
|
|
// 1. check if there's 'meta' file
|
|
|
|
let cache_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(url, "meta");
|
|
|
|
if let Ok(metadata_bytes) = self.disk_cache.get(&cache_key) {
|
|
|
|
if let Ok(metadata) = std::str::from_utf8(&metadata_bytes) {
|
|
|
|
if let Some(read_metadata) =
|
|
|
|
CompiledFileMetadata::from_json_string(metadata.to_string())
|
|
|
|
{
|
|
|
|
return Some(read_metadata);
|
2019-06-04 09:03:56 -04:00
|
|
|
}
|
|
|
|
}
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
2019-05-20 12:06:57 -04:00
|
|
|
|
2019-07-31 13:16:03 -04:00
|
|
|
pub fn get_compiled_module(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-07-31 13:16:03 -04:00
|
|
|
module_url: &Url,
|
|
|
|
) -> Result<CompiledModule, ErrBox> {
|
|
|
|
let compiled_source_file = self.get_compiled_source_file(module_url)?;
|
|
|
|
|
|
|
|
let compiled_module = CompiledModule {
|
|
|
|
code: str::from_utf8(&compiled_source_file.source_code)
|
|
|
|
.unwrap()
|
|
|
|
.to_string(),
|
|
|
|
name: module_url.to_string(),
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(compiled_module)
|
|
|
|
}
|
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
/// Return compiled JS file for given TS module.
|
|
|
|
// TODO: ideally we shouldn't construct SourceFile by hand, but it should be delegated to
|
|
|
|
// SourceFileFetcher
|
|
|
|
pub fn get_compiled_source_file(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-07-31 13:16:03 -04:00
|
|
|
module_url: &Url,
|
2019-07-17 18:15:30 -04:00
|
|
|
) -> Result<SourceFile, ErrBox> {
|
|
|
|
let cache_key = self
|
|
|
|
.disk_cache
|
2019-07-31 13:16:03 -04:00
|
|
|
.get_cache_filename_with_extension(&module_url, "js");
|
2019-07-17 18:15:30 -04:00
|
|
|
let compiled_code = self.disk_cache.get(&cache_key)?;
|
|
|
|
let compiled_code_filename = self.disk_cache.location.join(cache_key);
|
|
|
|
debug!("compiled filename: {:?}", compiled_code_filename);
|
|
|
|
|
|
|
|
let compiled_module = SourceFile {
|
2019-07-31 13:16:03 -04:00
|
|
|
url: module_url.clone(),
|
2019-07-17 18:15:30 -04:00
|
|
|
filename: compiled_code_filename,
|
|
|
|
media_type: msg::MediaType::JavaScript,
|
|
|
|
source_code: compiled_code,
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(compiled_module)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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.
|
|
|
|
fn cache_compiled_file(
|
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<()> {
|
|
|
|
let js_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(module_specifier.as_url(), "js");
|
|
|
|
self
|
|
|
|
.disk_cache
|
|
|
|
.set(&js_key, contents.as_bytes())
|
|
|
|
.and_then(|_| {
|
|
|
|
self.mark_compiled(module_specifier.as_url());
|
|
|
|
|
|
|
|
let source_file = self
|
2019-07-31 07:58:41 -04:00
|
|
|
.file_fetcher
|
2019-11-22 12:46:57 -05:00
|
|
|
.fetch_cached_source_file(&module_specifier)
|
2019-07-17 18:15:30 -04:00
|
|
|
.expect("Source file not found");
|
|
|
|
|
|
|
|
let version_hash = source_code_version_hash(
|
|
|
|
&source_file.source_code,
|
|
|
|
version::DENO,
|
2019-07-31 13:16:03 -04:00
|
|
|
&self.config.hash,
|
2019-07-17 18:15:30 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
let compiled_file_metadata = CompiledFileMetadata {
|
2019-12-23 09:59:44 -05:00
|
|
|
source_path: source_file.filename,
|
2019-07-17 18:15:30 -04:00
|
|
|
version_hash,
|
|
|
|
};
|
|
|
|
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-06-08 07:10:12 -04:00
|
|
|
})
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return associated source map file for given TS module.
|
|
|
|
// TODO: ideally we shouldn't construct SourceFile by hand, but it should be delegated to
|
|
|
|
// SourceFileFetcher
|
|
|
|
pub fn get_source_map_file(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-07-17 18:15:30 -04:00
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
) -> Result<SourceFile, ErrBox> {
|
|
|
|
let cache_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(module_specifier.as_url(), "js.map");
|
|
|
|
let source_code = self.disk_cache.get(&cache_key)?;
|
|
|
|
let source_map_filename = self.disk_cache.location.join(cache_key);
|
|
|
|
debug!("source map filename: {:?}", source_map_filename);
|
|
|
|
|
|
|
|
let source_map_file = SourceFile {
|
|
|
|
url: module_specifier.as_url().to_owned(),
|
|
|
|
filename: source_map_filename,
|
|
|
|
media_type: msg::MediaType::JavaScript,
|
|
|
|
source_code,
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(source_map_file)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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<()> {
|
|
|
|
let source_map_key = self
|
|
|
|
.disk_cache
|
|
|
|
.get_cache_filename_with_extension(module_specifier.as_url(), "js.map");
|
|
|
|
self.disk_cache.set(&source_map_key, contents.as_bytes())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This method is called by TS compiler via an "op".
|
|
|
|
pub fn cache_compiler_output(
|
2020-01-04 05:20:52 -05:00
|
|
|
&self,
|
2019-07-17 18:15:30 -04:00
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
extension: &str,
|
|
|
|
contents: &str,
|
|
|
|
) -> std::io::Result<()> {
|
|
|
|
match extension {
|
|
|
|
".map" => self.cache_source_map(module_specifier, contents),
|
|
|
|
".js" => self.cache_compiled_file(module_specifier, contents),
|
|
|
|
_ => unreachable!(),
|
|
|
|
}
|
|
|
|
}
|
2019-04-05 00:04:06 -04:00
|
|
|
}
|
|
|
|
|
2019-07-17 18:15:30 -04:00
|
|
|
impl SourceMapGetter for TsCompiler {
|
|
|
|
fn get_source_map(&self, script_name: &str) -> Option<Vec<u8>> {
|
|
|
|
self
|
|
|
|
.try_to_resolve_and_get_source_map(script_name)
|
2019-11-07 14:21:45 -05:00
|
|
|
.map(|out| out.source_code)
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn get_source_line(&self, script_name: &str, line: usize) -> Option<String> {
|
|
|
|
self
|
|
|
|
.try_resolve_and_get_source_file(script_name)
|
|
|
|
.and_then(|out| {
|
|
|
|
str::from_utf8(&out.source_code).ok().and_then(|v| {
|
|
|
|
let lines: Vec<&str> = v.lines().collect();
|
|
|
|
assert!(lines.len() > line);
|
|
|
|
Some(lines[line].to_string())
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// `SourceMapGetter` related methods
|
|
|
|
impl TsCompiler {
|
2020-01-04 05:20:52 -05:00
|
|
|
fn try_to_resolve(&self, script_name: &str) -> Option<ModuleSpecifier> {
|
2019-07-17 18:15:30 -04:00
|
|
|
// if `script_name` can't be resolved to ModuleSpecifier it's probably internal
|
|
|
|
// script (like `gen/cli/bundle/compiler.js`) so we won't be
|
|
|
|
// able to get source for it anyway
|
|
|
|
ModuleSpecifier::resolve_url(script_name).ok()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn try_resolve_and_get_source_file(
|
|
|
|
&self,
|
|
|
|
script_name: &str,
|
|
|
|
) -> Option<SourceFile> {
|
|
|
|
if let Some(module_specifier) = self.try_to_resolve(script_name) {
|
2019-11-22 12:46:57 -05:00
|
|
|
return self
|
|
|
|
.file_fetcher
|
|
|
|
.fetch_cached_source_file(&module_specifier);
|
2019-07-17 18:15:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
fn try_to_resolve_and_get_source_map(
|
|
|
|
&self,
|
|
|
|
script_name: &str,
|
|
|
|
) -> Option<SourceFile> {
|
|
|
|
if let Some(module_specifier) = self.try_to_resolve(script_name) {
|
|
|
|
return match self.get_source_map_file(&module_specifier) {
|
|
|
|
Ok(out) => Some(out),
|
|
|
|
Err(_) => None,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
2019-01-09 12:59:46 -05:00
|
|
|
}
|
|
|
|
|
2020-01-08 09:17:44 -05:00
|
|
|
pub fn runtime_compile_async<S: BuildHasher>(
|
|
|
|
global_state: ThreadSafeGlobalState,
|
|
|
|
root_name: &str,
|
|
|
|
sources: &Option<HashMap<String, String, S>>,
|
|
|
|
bundle: bool,
|
|
|
|
options: &Option<String>,
|
|
|
|
) -> Pin<Box<CompilationResultFuture>> {
|
|
|
|
let req_msg = json!({
|
|
|
|
"type": msg::CompilerRequestType::RuntimeCompile as i32,
|
|
|
|
"rootName": root_name,
|
|
|
|
"sources": sources,
|
|
|
|
"options": options,
|
|
|
|
"bundle": bundle,
|
|
|
|
})
|
|
|
|
.to_string()
|
|
|
|
.into_boxed_str()
|
|
|
|
.into_boxed_bytes();
|
|
|
|
|
|
|
|
let worker = TsCompiler::setup_worker(global_state);
|
|
|
|
let worker_ = worker.clone();
|
|
|
|
|
|
|
|
async move {
|
|
|
|
worker.post_message(req_msg).await?;
|
|
|
|
worker.await?;
|
|
|
|
debug!("Sent message to worker");
|
|
|
|
let msg = (worker_.get_message().await?).unwrap();
|
|
|
|
let json_str = std::str::from_utf8(&msg).unwrap();
|
|
|
|
Ok(json!(json_str))
|
|
|
|
}
|
|
|
|
.boxed()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn runtime_transpile_async<S: BuildHasher>(
|
|
|
|
global_state: ThreadSafeGlobalState,
|
|
|
|
sources: &HashMap<String, String, S>,
|
|
|
|
options: &Option<String>,
|
|
|
|
) -> Pin<Box<CompilationResultFuture>> {
|
|
|
|
let req_msg = json!({
|
|
|
|
"type": msg::CompilerRequestType::RuntimeTranspile as i32,
|
|
|
|
"sources": sources,
|
|
|
|
"options": options,
|
|
|
|
})
|
|
|
|
.to_string()
|
|
|
|
.into_boxed_str()
|
|
|
|
.into_boxed_bytes();
|
|
|
|
|
|
|
|
let worker = TsCompiler::setup_worker(global_state);
|
|
|
|
let worker_ = worker.clone();
|
|
|
|
|
|
|
|
async move {
|
|
|
|
worker.post_message(req_msg).await?;
|
|
|
|
worker.await?;
|
|
|
|
debug!("Sent message to worker");
|
|
|
|
let msg = (worker_.get_message().await?).unwrap();
|
|
|
|
let json_str = std::str::from_utf8(&msg).unwrap();
|
|
|
|
Ok(json!(json_str))
|
|
|
|
}
|
|
|
|
.boxed()
|
|
|
|
}
|
|
|
|
|
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;
|
2019-07-17 18:15:30 -04:00
|
|
|
use crate::tokio_util;
|
2020-01-05 11:56:18 -05:00
|
|
|
use deno_core::ModuleSpecifier;
|
2019-07-17 18:15:30 -04:00
|
|
|
use std::path::PathBuf;
|
2019-08-17 12:53:34 -04:00
|
|
|
use tempfile::TempDir;
|
2019-07-17 18:15:30 -04:00
|
|
|
|
2019-01-09 12:59:46 -05:00
|
|
|
#[test]
|
2019-10-06 15:03:30 -04:00
|
|
|
fn test_compile_async() {
|
|
|
|
let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
|
|
|
.parent()
|
|
|
|
.unwrap()
|
2019-12-23 09:59:44 -05:00
|
|
|
.join("tests/002_hello.ts");
|
2019-10-06 15:03:30 -04:00
|
|
|
let specifier =
|
|
|
|
ModuleSpecifier::resolve_url_or_path(p.to_str().unwrap()).unwrap();
|
|
|
|
|
|
|
|
let out = SourceFile {
|
|
|
|
url: specifier.as_url().clone(),
|
|
|
|
filename: PathBuf::from(p.to_str().unwrap().to_string()),
|
|
|
|
media_type: msg::MediaType::TypeScript,
|
|
|
|
source_code: include_bytes!("../tests/002_hello.ts").to_vec(),
|
|
|
|
};
|
2019-04-05 00:04:06 -04:00
|
|
|
|
2019-11-04 10:38:52 -05:00
|
|
|
let mock_state = ThreadSafeGlobalState::mock(vec![
|
2019-10-06 15:03:30 -04:00
|
|
|
String::from("deno"),
|
|
|
|
String::from("hello.js"),
|
|
|
|
]);
|
|
|
|
|
2019-11-22 12:14:34 -05:00
|
|
|
let fut = async move {
|
|
|
|
let result = mock_state
|
2019-07-17 18:15:30 -04:00
|
|
|
.ts_compiler
|
2019-10-06 15:03:30 -04:00
|
|
|
.compile_async(mock_state.clone(), &out)
|
2019-11-22 12:14:34 -05:00
|
|
|
.await;
|
|
|
|
|
|
|
|
assert!(result.is_ok());
|
|
|
|
assert!(result
|
|
|
|
.unwrap()
|
|
|
|
.code
|
|
|
|
.as_bytes()
|
|
|
|
.starts_with("console.log(\"Hello World\");".as_bytes()));
|
|
|
|
};
|
|
|
|
|
|
|
|
tokio_util::run(fut.boxed())
|
2019-04-04 05:33:32 -04:00
|
|
|
}
|
|
|
|
|
2019-06-08 14:42:28 -04:00
|
|
|
#[test]
|
|
|
|
fn test_bundle_async() {
|
2019-09-04 17:16:46 -04:00
|
|
|
let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
|
|
|
.parent()
|
|
|
|
.unwrap()
|
2019-12-23 09:59:44 -05:00
|
|
|
.join("tests/002_hello.ts");
|
2020-01-05 11:56:18 -05:00
|
|
|
use deno_core::ModuleSpecifier;
|
2019-09-04 17:16:46 -04:00
|
|
|
let module_name = ModuleSpecifier::resolve_url_or_path(p.to_str().unwrap())
|
2019-06-08 14:42:28 -04:00
|
|
|
.unwrap()
|
|
|
|
.to_string();
|
|
|
|
|
2019-11-04 10:38:52 -05:00
|
|
|
let state = ThreadSafeGlobalState::mock(vec![
|
2019-09-04 17:16:46 -04:00
|
|
|
String::from("deno"),
|
|
|
|
p.to_string_lossy().into(),
|
2019-06-08 14:42:28 -04:00
|
|
|
String::from("$deno$/bundle.js"),
|
|
|
|
]);
|
2019-10-06 15:03:30 -04:00
|
|
|
|
2019-11-22 12:14:34 -05:00
|
|
|
let fut = async move {
|
|
|
|
let result = state
|
2019-10-06 15:03:30 -04:00
|
|
|
.ts_compiler
|
|
|
|
.bundle_async(
|
|
|
|
state.clone(),
|
|
|
|
module_name,
|
2019-11-13 10:35:56 -05:00
|
|
|
Some(String::from("$deno$/bundle.js")),
|
2019-10-06 15:03:30 -04:00
|
|
|
)
|
2019-11-22 12:14:34 -05:00
|
|
|
.await;
|
|
|
|
|
|
|
|
assert!(result.is_ok());
|
|
|
|
};
|
|
|
|
tokio_util::run(fut.boxed())
|
2019-06-08 14:42:28 -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
|
|
|
|
(
|
|
|
|
r#"{ "compilerOptions": { // force .js file compilation by Deno "checkJs": true } } "#,
|
|
|
|
true,
|
|
|
|
),
|
|
|
|
// invalid JSON
|
2019-12-23 09:59:44 -05:00
|
|
|
(r#"{ "compilerOptions": { "checkJs": true },{ } "#, true),
|
2019-08-17 12:53:34 -04:00
|
|
|
// 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
|
|
|
}
|