1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-21 15:04:11 -05:00

Move ModuleSpecifier to //core (#2509)

This commit is contained in:
Bartek Iwańczuk 2019-06-13 01:55:59 +02:00 committed by Ryan Dahl
parent b3c4307d02
commit bca5cc5041
13 changed files with 188 additions and 148 deletions

1
Cargo.lock generated
View file

@ -205,6 +205,7 @@ dependencies = [
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)",
"tokio 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)",
"url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]] [[package]]

View file

@ -247,7 +247,7 @@ mod tests {
fn test_compile_sync() { fn test_compile_sync() {
tokio_util::init(|| { tokio_util::init(|| {
let specifier = "./tests/002_hello.ts"; let specifier = "./tests/002_hello.ts";
use crate::module_specifier::ModuleSpecifier; use deno::ModuleSpecifier;
let module_name = ModuleSpecifier::resolve_root(specifier) let module_name = ModuleSpecifier::resolve_root(specifier)
.unwrap() .unwrap()
.to_string(); .to_string();
@ -294,7 +294,7 @@ mod tests {
#[test] #[test]
fn test_bundle_async() { fn test_bundle_async() {
let specifier = "./tests/002_hello.ts"; let specifier = "./tests/002_hello.ts";
use crate::module_specifier::ModuleSpecifier; use deno::ModuleSpecifier;
let module_name = ModuleSpecifier::resolve_root(specifier) let module_name = ModuleSpecifier::resolve_root(specifier)
.unwrap() .unwrap()
.to_string(); .to_string();

View file

@ -502,7 +502,7 @@ pub enum DenoSubcommand {
} }
fn get_default_bundle_filename(source_file: &str) -> String { fn get_default_bundle_filename(source_file: &str) -> String {
use crate::module_specifier::ModuleSpecifier; use deno::ModuleSpecifier;
let url = ModuleSpecifier::resolve_root(source_file).unwrap().to_url(); let url = ModuleSpecifier::resolve_root(source_file).unwrap().to_url();
let path_segments = url.path_segments().unwrap(); let path_segments = url.path_segments().unwrap();
let last = path_segments.last().unwrap(); let last = path_segments.last().unwrap();

View file

@ -1,4 +1,4 @@
use crate::module_specifier::ModuleSpecifier; use deno::ModuleSpecifier;
use indexmap::IndexMap; use indexmap::IndexMap;
use serde_json::Map; use serde_json::Map;
use serde_json::Value; use serde_json::Value;

View file

@ -27,7 +27,6 @@ mod http_body;
mod http_util; mod http_util;
mod import_map; mod import_map;
pub mod js_errors; pub mod js_errors;
mod module_specifier;
pub mod msg; pub mod msg;
pub mod msg_util; pub mod msg_util;
pub mod ops; pub mod ops;
@ -46,11 +45,11 @@ pub mod worker;
use crate::compiler::bundle_async; use crate::compiler::bundle_async;
use crate::errors::RustOrJsError; use crate::errors::RustOrJsError;
use crate::module_specifier::ModuleSpecifier;
use crate::progress::Progress; use crate::progress::Progress;
use crate::state::ThreadSafeState; use crate::state::ThreadSafeState;
use crate::worker::Worker; use crate::worker::Worker;
use deno::v8_set_flags; use deno::v8_set_flags;
use deno::ModuleSpecifier;
use flags::DenoFlags; use flags::DenoFlags;
use flags::DenoSubcommand; use flags::DenoSubcommand;
use futures::future; use futures::future;

View file

@ -10,7 +10,6 @@ use crate::fs as deno_fs;
use crate::http_util; use crate::http_util;
use crate::js_errors::apply_source_map; use crate::js_errors::apply_source_map;
use crate::js_errors::JSErrorColor; use crate::js_errors::JSErrorColor;
use crate::module_specifier::ModuleSpecifier;
use crate::msg; use crate::msg;
use crate::msg_util; use crate::msg_util;
use crate::rand; use crate::rand;
@ -29,6 +28,7 @@ use crate::worker::Worker;
use deno::js_check; use deno::js_check;
use deno::Buf; use deno::Buf;
use deno::JSError; use deno::JSError;
use deno::ModuleSpecifier;
use deno::Op; use deno::Op;
use deno::PinnedBuf; use deno::PinnedBuf;
use flatbuffers::FlatBufferBuilder; use flatbuffers::FlatBufferBuilder;
@ -505,15 +505,13 @@ fn op_fetch_module_meta_data(
// import map - why it is not always resolved? Eg. "bad-module.ts" will return NotFound // import map - why it is not always resolved? Eg. "bad-module.ts" will return NotFound
// error whilst it should return RelativeUrlWithCannotBeABaseBase error // error whilst it should return RelativeUrlWithCannotBeABaseBase error
let resolved_specifier = match &state.import_map { let resolved_specifier = match &state.import_map {
Some(import_map) => { Some(import_map) => match import_map.resolve(specifier, referrer) {
match import_map.resolve(specifier, referrer) { Ok(result) => match result {
Ok(result) => match result { Some(module_specifier) => module_specifier.to_string(),
Some(module_specifier) => module_specifier.to_string(), None => specifier.to_string(),
None => specifier.to_string(), },
}, Err(err) => return odd_future(DenoError::from(err)),
Err(err) => panic!("error resolving using import map: {:?}", err), // TODO: this should be coerced to DenoError },
}
}
None => specifier.to_string(), None => specifier.to_string(),
}; };

View file

@ -7,7 +7,6 @@ use crate::errors::DenoResult;
use crate::flags; use crate::flags;
use crate::global_timer::GlobalTimer; use crate::global_timer::GlobalTimer;
use crate::import_map::ImportMap; use crate::import_map::ImportMap;
use crate::module_specifier::ModuleSpecifier;
use crate::msg; use crate::msg;
use crate::ops; use crate::ops;
use crate::permissions::DenoPermissions; use crate::permissions::DenoPermissions;
@ -17,6 +16,7 @@ use crate::resources::ResourceId;
use crate::worker::Worker; use crate::worker::Worker;
use deno::Buf; use deno::Buf;
use deno::Loader; use deno::Loader;
use deno::ModuleSpecifier;
use deno::Op; use deno::Op;
use deno::PinnedBuf; use deno::PinnedBuf;
use futures::future::Either; use futures::future::Either;
@ -157,28 +157,27 @@ impl Loader for ThreadSafeState {
specifier: &str, specifier: &str,
referrer: &str, referrer: &str,
is_root: bool, is_root: bool,
) -> Result<String, Self::Error> { ) -> Result<ModuleSpecifier, Self::Error> {
if !is_root { if !is_root {
if let Some(import_map) = &self.import_map { if let Some(import_map) = &self.import_map {
let result = import_map.resolve(specifier, referrer)?; let result = import_map.resolve(specifier, referrer)?;
if result.is_some() { if result.is_some() {
return Ok(result.unwrap().to_string()); return Ok(result.unwrap());
} }
} }
} }
let module_specifier = ModuleSpecifier::resolve(specifier, referrer).map_err(DenoError::from)
ModuleSpecifier::resolve(specifier, referrer).map_err(DenoError::from)?;
Ok(module_specifier.to_string())
} }
/// Given an absolute url, load its source code. /// Given an absolute url, load its source code.
fn load(&self, url: &str) -> Box<deno::SourceCodeInfoFuture<Self::Error>> { fn load(
&self,
module_specifier: &ModuleSpecifier,
) -> Box<deno::SourceCodeInfoFuture<Self::Error>> {
self.metrics.resolve_count.fetch_add(1, Ordering::SeqCst); self.metrics.resolve_count.fetch_add(1, Ordering::SeqCst);
let module_specifier = ModuleSpecifier::resolve_root(url)
.expect("should already been properly resolved");
Box::new( Box::new(
fetch_module_meta_data_and_maybe_compile_async(self, &module_specifier) fetch_module_meta_data_and_maybe_compile_async(self, module_specifier)
.map_err(|err| { .map_err(|err| {
eprintln!("{}", err); eprintln!("{}", err);
err err

View file

@ -2,11 +2,11 @@
use crate::errors::DenoError; use crate::errors::DenoError;
use crate::errors::RustOrJsError; use crate::errors::RustOrJsError;
use crate::js_errors; use crate::js_errors;
use crate::module_specifier::ModuleSpecifier;
use crate::state::ThreadSafeState; use crate::state::ThreadSafeState;
use crate::tokio_util; use crate::tokio_util;
use deno; use deno;
use deno::JSError; use deno::JSError;
use deno::ModuleSpecifier;
use deno::StartupData; use deno::StartupData;
use futures::Async; use futures::Async;
use futures::Future; use futures::Future;

View file

@ -23,6 +23,7 @@ main_extern_rlib = [
"libc", "libc",
"serde_json", "serde_json",
"log", "log",
"url",
] ]
rust_rlib("deno") { rust_rlib("deno") {

View file

@ -19,6 +19,7 @@ lazy_static = "1.3.0"
libc = "0.2.55" libc = "0.2.55"
log = "0.4.6" log = "0.4.6"
serde_json = "1.0.39" serde_json = "1.0.39"
url = "1.7.2"
[[example]] [[example]]
name = "deno_core_http_bench" name = "deno_core_http_bench"

View file

@ -8,6 +8,7 @@ mod flags;
mod isolate; mod isolate;
mod js_errors; mod js_errors;
mod libdeno; mod libdeno;
mod module_specifier;
mod modules; mod modules;
mod shared_queue; mod shared_queue;
@ -16,6 +17,7 @@ pub use crate::isolate::*;
pub use crate::js_errors::*; pub use crate::js_errors::*;
pub use crate::libdeno::deno_mod; pub use crate::libdeno::deno_mod;
pub use crate::libdeno::PinnedBuf; pub use crate::libdeno::PinnedBuf;
pub use crate::module_specifier::ModuleSpecifier;
pub use crate::modules::*; pub use crate::modules::*;
pub fn v8_version() -> &'static str { pub fn v8_version() -> &'static str {

View file

@ -9,6 +9,7 @@ impl ModuleSpecifier {
pub fn to_url(&self) -> Url { pub fn to_url(&self) -> Url {
self.0.clone() self.0.clone()
} }
/// Resolves module using this algorithm: /// Resolves module using this algorithm:
/// https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier /// https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
pub fn resolve( pub fn resolve(
@ -62,18 +63,18 @@ impl ModuleSpecifier {
} }
} }
impl From<Url> for ModuleSpecifier {
fn from(url: Url) -> Self {
ModuleSpecifier(url)
}
}
impl fmt::Display for ModuleSpecifier { impl fmt::Display for ModuleSpecifier {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f) self.0.fmt(f)
} }
} }
impl From<Url> for ModuleSpecifier {
fn from(url: Url) -> Self {
ModuleSpecifier(url)
}
}
impl PartialEq<String> for ModuleSpecifier { impl PartialEq<String> for ModuleSpecifier {
fn eq(&self, other: &String) -> bool { fn eq(&self, other: &String) -> bool {
&self.to_string() == other &self.to_string() == other

View file

@ -9,6 +9,7 @@
use crate::isolate::Isolate; use crate::isolate::Isolate;
use crate::js_errors::JSError; use crate::js_errors::JSError;
use crate::libdeno::deno_mod; use crate::libdeno::deno_mod;
use crate::module_specifier::ModuleSpecifier;
use futures::Async; use futures::Async;
use futures::Future; use futures::Future;
use futures::Poll; use futures::Poll;
@ -48,10 +49,13 @@ pub trait Loader: Send + Sync {
specifier: &str, specifier: &str,
referrer: &str, referrer: &str,
is_root: bool, is_root: bool,
) -> Result<String, Self::Error>; ) -> Result<ModuleSpecifier, Self::Error>;
/// Given an absolute url, load its source code. /// Given ModuleSpecifier, load its source code.
fn load(&self, url: &str) -> Box<SourceCodeInfoFuture<Self::Error>>; fn load(
&self,
module_specifier: &ModuleSpecifier,
) -> Box<SourceCodeInfoFuture<Self::Error>>;
} }
struct PendingLoad<E: Error> { struct PendingLoad<E: Error> {
@ -104,12 +108,13 @@ impl<L: Loader> RecursiveLoad<L> {
parent_id: Option<deno_mod>, parent_id: Option<deno_mod>,
) -> Result<String, L::Error> { ) -> Result<String, L::Error> {
let is_root = parent_id.is_none(); let is_root = parent_id.is_none();
let url = self.loader.resolve(specifier, referrer, is_root)?; let module_specifier = self.loader.resolve(specifier, referrer, is_root)?;
let module_name = module_specifier.to_string();
if !is_root { if !is_root {
{ {
let mut m = self.modules.lock().unwrap(); let mut m = self.modules.lock().unwrap();
m.add_child(parent_id.unwrap(), &url); m.add_child(parent_id.unwrap(), &module_name);
} }
} }
@ -118,22 +123,22 @@ impl<L: Loader> RecursiveLoad<L> {
// Only short circuit after add_child(). // Only short circuit after add_child().
// This impacts possible conditions in #A. // This impacts possible conditions in #A.
let modules = self.modules.lock().unwrap(); let modules = self.modules.lock().unwrap();
if modules.is_registered(&url) { if modules.is_registered(&module_name) {
return Ok(url); return Ok(module_name);
} }
} }
if !self.is_pending.contains(&url) { if !self.is_pending.contains(&module_name) {
self.is_pending.insert(url.clone()); self.is_pending.insert(module_name.to_string());
let source_code_info_future = { self.loader.load(&url) }; let source_code_info_future = { self.loader.load(&module_specifier) };
self.pending.push(PendingLoad { self.pending.push(PendingLoad {
url: url.clone(), url: module_name.to_string(),
source_code_info_future, source_code_info_future,
is_root, is_root,
}); });
} }
Ok(url) Ok(module_name)
} }
} }
@ -254,10 +259,9 @@ impl<L: Loader> Future for RecursiveLoad<L> {
|specifier: &str, referrer_id: deno_mod| -> deno_mod { |specifier: &str, referrer_id: deno_mod| -> deno_mod {
let modules = self.modules.lock().unwrap(); let modules = self.modules.lock().unwrap();
let referrer = modules.get_name(referrer_id).unwrap(); let referrer = modules.get_name(referrer_id).unwrap();
// TODO(bartlomieju): there must be a better way // this callback is only called for non-root modules
let is_root = referrer == "."; match self.loader.resolve(specifier, &referrer, false) {
match self.loader.resolve(specifier, &referrer, is_root) { Ok(specifier) => match modules.get_id(&specifier.to_string()) {
Ok(url) => match modules.get_id(&url) {
Some(id) => id, Some(id) => id,
None => 0, None => 0,
}, },
@ -557,22 +561,25 @@ mod tests {
fn mock_source_code(url: &str) -> Option<(&'static str, &'static str)> { fn mock_source_code(url: &str) -> Option<(&'static str, &'static str)> {
// (code, real_module_name) // (code, real_module_name)
match url { let spec: Vec<&str> = url.split("file://").collect();
"a.js" => Some((A_SRC, "a.js")), match spec[1] {
"b.js" => Some((B_SRC, "b.js")), "/a.js" => Some((A_SRC, "file:///a.js")),
"c.js" => Some((C_SRC, "c.js")), "/b.js" => Some((B_SRC, "file:///b.js")),
"d.js" => Some((D_SRC, "d.js")), "/c.js" => Some((C_SRC, "file:///c.js")),
"circular1.js" => Some((CIRCULAR1_SRC, "circular1.js")), "/d.js" => Some((D_SRC, "file:///d.js")),
"circular2.js" => Some((CIRCULAR2_SRC, "circular2.js")), "/circular1.js" => Some((CIRCULAR1_SRC, "file:///circular1.js")),
"circular3.js" => Some((CIRCULAR3_SRC, "circular3.js")), "/circular2.js" => Some((CIRCULAR2_SRC, "file:///circular2.js")),
"redirect1.js" => Some((REDIRECT1_SRC, "redirect1.js")), "/circular3.js" => Some((CIRCULAR3_SRC, "file:///circular3.js")),
// pretend redirect "/redirect1.js" => Some((REDIRECT1_SRC, "file:///redirect1.js")),
"./redirect2.js" => Some((REDIRECT2_SRC, "./dir/redirect2.js")), // pretend redirect - real module name is different than one requested
"./dir/redirect3.js" => Some((REDIRECT3_SRC, "./redirect3.js")), "/redirect2.js" => Some((REDIRECT2_SRC, "file:///dir/redirect2.js")),
"slow.js" => Some((SLOW_SRC, "slow.js")), "/dir/redirect3.js" => Some((REDIRECT3_SRC, "file:///redirect3.js")),
"never_ready.js" => Some(("should never be loaded", "never_ready.js")), "/slow.js" => Some((SLOW_SRC, "file:///slow.js")),
"main.js" => Some((MAIN_SRC, "main.js")), "/never_ready.js" => {
"bad_import.js" => Some((BAD_IMPORT_SRC, "bad_import.js")), Some(("should never be loaded", "file:///never_ready.js"))
}
"/main.js" => Some((MAIN_SRC, "file:///main.js")),
"/bad_import.js" => Some((BAD_IMPORT_SRC, "file:///bad_import.js")),
_ => None, _ => None,
} }
} }
@ -606,8 +613,8 @@ mod tests {
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.counter += 1; self.counter += 1;
if self.url == "never_ready.js" if self.url == "file:///never_ready.js"
|| (self.url == "slow.js" && self.counter < 2) || (self.url == "file:///slow.js" && self.counter < 2)
{ {
return Ok(Async::NotReady); return Ok(Async::NotReady);
} }
@ -629,72 +636,68 @@ mod tests {
specifier: &str, specifier: &str,
referrer: &str, referrer: &str,
_is_root: bool, _is_root: bool,
) -> Result<String, Self::Error> { ) -> Result<ModuleSpecifier, Self::Error> {
eprintln!(">> RESOLVING, S: {}, R: {}", specifier, referrer); let referrer = if referrer == "." {
let output_specifier = "file:///"
if specifier.starts_with("./") && referrer.starts_with("./") { } else {
// Special fake path resolving logic (for redirect test) referrer
// if both started with "./" };
eprintln!(">> SPECIAL!");
let prefix = {
let mut iter = referrer.rsplitn(2, '/');
let _ = iter.next();
iter.next().unwrap()
};
let suffix = {
let mut iter = specifier.splitn(2, '/');
let _ = iter.next();
iter.next().unwrap()
};
format!("{}/{}", &prefix, &suffix)
} else {
specifier.to_owned()
};
if mock_source_code(&output_specifier).is_some() { eprintln!(">> RESOLVING, S: {}, R: {}", specifier, referrer);
let output_specifier = match ModuleSpecifier::resolve(specifier, referrer)
{
Ok(specifier) => specifier,
Err(_e) => return Err(MockError::ResolveErr),
};
if mock_source_code(&output_specifier.to_string()).is_some() {
Ok(output_specifier) Ok(output_specifier)
} else { } else {
Err(MockError::ResolveErr) Err(MockError::ResolveErr)
} }
} }
fn load(&self, url: &str) -> Box<SourceCodeInfoFuture<Self::Error>> { fn load(
&self,
module_specifier: &ModuleSpecifier,
) -> Box<SourceCodeInfoFuture<Self::Error>> {
let mut loads = self.loads.lock().unwrap(); let mut loads = self.loads.lock().unwrap();
loads.push(url.to_string()); loads.push(module_specifier.to_string());
let url = url.to_string(); let url = module_specifier.to_string();
Box::new(DelayedSourceCodeFuture { url, counter: 0 }) Box::new(DelayedSourceCodeFuture { url, counter: 0 })
} }
} }
const A_SRC: &str = r#" const A_SRC: &str = r#"
import { b } from "b.js"; import { b } from "/b.js";
import { c } from "c.js"; import { c } from "/c.js";
if (b() != 'b') throw Error(); if (b() != 'b') throw Error();
if (c() != 'c') throw Error(); if (c() != 'c') throw Error();
if (!import.meta.main) throw Error(); if (!import.meta.main) throw Error();
if (import.meta.url != 'a.js') throw Error(); if (import.meta.url != 'file:///a.js') throw Error();
"#; "#;
const B_SRC: &str = r#" const B_SRC: &str = r#"
import { c } from "c.js"; import { c } from "/c.js";
if (c() != 'c') throw Error(); if (c() != 'c') throw Error();
export function b() { return 'b'; } export function b() { return 'b'; }
if (import.meta.main) throw Error(); if (import.meta.main) throw Error();
if (import.meta.url != 'b.js') throw Error(); if (import.meta.url != 'file:///b.js') throw Error();
"#; "#;
const C_SRC: &str = r#" const C_SRC: &str = r#"
import { d } from "d.js"; import { d } from "/d.js";
export function c() { return 'c'; } export function c() { return 'c'; }
if (d() != 'd') throw Error(); if (d() != 'd') throw Error();
if (import.meta.main) throw Error(); if (import.meta.main) throw Error();
if (import.meta.url != 'c.js') throw Error(); if (import.meta.url != 'file:///c.js') throw Error();
"#; "#;
const D_SRC: &str = r#" const D_SRC: &str = r#"
export function d() { return 'd'; } export function d() { return 'd'; }
if (import.meta.main) throw Error(); if (import.meta.main) throw Error();
if (import.meta.url != 'd.js') throw Error(); if (import.meta.url != 'file:///d.js') throw Error();
"#; "#;
#[test] #[test]
@ -706,7 +709,7 @@ mod tests {
let isolate_ = isolate.clone(); let isolate_ = isolate.clone();
let loads = loader.loads.clone(); let loads = loader.loads.clone();
let mut recursive_load = let mut recursive_load =
RecursiveLoad::new("a.js", loader, isolate, modules); RecursiveLoad::new("/a.js", loader, isolate, modules);
let result = recursive_load.poll(); let result = recursive_load.poll();
assert!(result.is_ok()); assert!(result.is_ok());
@ -715,21 +718,38 @@ mod tests {
js_check(isolate.mod_evaluate(a_id)); js_check(isolate.mod_evaluate(a_id));
let l = loads.lock().unwrap(); let l = loads.lock().unwrap();
assert_eq!(l.to_vec(), vec!["a.js", "b.js", "c.js", "d.js"]); assert_eq!(
l.to_vec(),
vec![
"file:///a.js",
"file:///b.js",
"file:///c.js",
"file:///d.js"
]
);
let modules = modules_.lock().unwrap(); let modules = modules_.lock().unwrap();
assert_eq!(modules.get_id("a.js"), Some(a_id)); assert_eq!(modules.get_id("file:///a.js"), Some(a_id));
let b_id = modules.get_id("b.js").unwrap(); let b_id = modules.get_id("file:///b.js").unwrap();
let c_id = modules.get_id("c.js").unwrap(); let c_id = modules.get_id("file:///c.js").unwrap();
let d_id = modules.get_id("d.js").unwrap(); let d_id = modules.get_id("file:///d.js").unwrap();
assert_eq!( assert_eq!(
modules.get_children(a_id), modules.get_children(a_id),
Some(&vec!["b.js".to_string(), "c.js".to_string()]) Some(&vec![
"file:///b.js".to_string(),
"file:///c.js".to_string()
])
);
assert_eq!(
modules.get_children(b_id),
Some(&vec!["file:///c.js".to_string()])
);
assert_eq!(
modules.get_children(c_id),
Some(&vec!["file:///d.js".to_string()])
); );
assert_eq!(modules.get_children(b_id), Some(&vec!["c.js".to_string()]));
assert_eq!(modules.get_children(c_id), Some(&vec!["d.js".to_string()]));
assert_eq!(modules.get_children(d_id), Some(&vec![])); assert_eq!(modules.get_children(d_id), Some(&vec![]));
} else { } else {
unreachable!(); unreachable!();
@ -737,18 +757,18 @@ mod tests {
} }
const CIRCULAR1_SRC: &str = r#" const CIRCULAR1_SRC: &str = r#"
import "circular2.js"; import "/circular2.js";
Deno.core.print("circular1"); Deno.core.print("circular1");
"#; "#;
const CIRCULAR2_SRC: &str = r#" const CIRCULAR2_SRC: &str = r#"
import "circular3.js"; import "/circular3.js";
Deno.core.print("circular2"); Deno.core.print("circular2");
"#; "#;
const CIRCULAR3_SRC: &str = r#" const CIRCULAR3_SRC: &str = r#"
import "circular1.js"; import "/circular1.js";
import "circular2.js"; import "/circular2.js";
Deno.core.print("circular3"); Deno.core.print("circular3");
"#; "#;
@ -761,7 +781,7 @@ mod tests {
let modules_ = modules.clone(); let modules_ = modules.clone();
let loads = loader.loads.clone(); let loads = loader.loads.clone();
let mut recursive_load = let mut recursive_load =
RecursiveLoad::new("circular1.js", loader, isolate, modules); RecursiveLoad::new("/circular1.js", loader, isolate, modules);
let result = recursive_load.poll(); let result = recursive_load.poll();
assert!(result.is_ok()); assert!(result.is_ok());
@ -772,31 +792,35 @@ mod tests {
let l = loads.lock().unwrap(); let l = loads.lock().unwrap();
assert_eq!( assert_eq!(
l.to_vec(), l.to_vec(),
vec!["circular1.js", "circular2.js", "circular3.js"] vec![
"file:///circular1.js",
"file:///circular2.js",
"file:///circular3.js"
]
); );
let modules = modules_.lock().unwrap(); let modules = modules_.lock().unwrap();
assert_eq!(modules.get_id("circular1.js"), Some(circular1_id)); assert_eq!(modules.get_id("file:///circular1.js"), Some(circular1_id));
let circular2_id = modules.get_id("circular2.js").unwrap(); let circular2_id = modules.get_id("file:///circular2.js").unwrap();
assert_eq!( assert_eq!(
modules.get_children(circular1_id), modules.get_children(circular1_id),
Some(&vec!["circular2.js".to_string()]) Some(&vec!["file:///circular2.js".to_string()])
); );
assert_eq!( assert_eq!(
modules.get_children(circular2_id), modules.get_children(circular2_id),
Some(&vec!["circular3.js".to_string()]) Some(&vec!["file:///circular3.js".to_string()])
); );
assert!(modules.get_id("circular3.js").is_some()); assert!(modules.get_id("file:///circular3.js").is_some());
let circular3_id = modules.get_id("circular3.js").unwrap(); let circular3_id = modules.get_id("file:///circular3.js").unwrap();
assert_eq!( assert_eq!(
modules.get_children(circular3_id), modules.get_children(circular3_id),
Some(&vec![ Some(&vec![
"circular1.js".to_string(), "file:///circular1.js".to_string(),
"circular2.js".to_string() "file:///circular2.js".to_string()
]) ])
); );
} else { } else {
@ -827,7 +851,7 @@ mod tests {
let modules_ = modules.clone(); let modules_ = modules.clone();
let loads = loader.loads.clone(); let loads = loader.loads.clone();
let mut recursive_load = let mut recursive_load =
RecursiveLoad::new("redirect1.js", loader, isolate, modules); RecursiveLoad::new("/redirect1.js", loader, isolate, modules);
let result = recursive_load.poll(); let result = recursive_load.poll();
assert!(result.is_ok()); assert!(result.is_ok());
@ -837,22 +861,29 @@ mod tests {
let l = loads.lock().unwrap(); let l = loads.lock().unwrap();
assert_eq!( assert_eq!(
l.to_vec(), l.to_vec(),
vec!["redirect1.js", "./redirect2.js", "./dir/redirect3.js"] vec![
"file:///redirect1.js",
"file:///redirect2.js",
"file:///dir/redirect3.js"
]
); );
let modules = modules_.lock().unwrap(); let modules = modules_.lock().unwrap();
assert_eq!(modules.get_id("redirect1.js"), Some(redirect1_id)); assert_eq!(modules.get_id("file:///redirect1.js"), Some(redirect1_id));
let redirect2_id = modules.get_id("./dir/redirect2.js").unwrap(); let redirect2_id = modules.get_id("file:///dir/redirect2.js").unwrap();
assert!(modules.is_alias("./redirect2.js")); assert!(modules.is_alias("file:///redirect2.js"));
assert!(!modules.is_alias("./dir/redirect2.js")); assert!(!modules.is_alias("file:///dir/redirect2.js"));
assert_eq!(modules.get_id("./redirect2.js").unwrap(), redirect2_id); assert_eq!(modules.get_id("file:///redirect2.js"), Some(redirect2_id));
let redirect3_id = modules.get_id("./redirect3.js").unwrap(); let redirect3_id = modules.get_id("file:///redirect3.js").unwrap();
assert!(modules.is_alias("./dir/redirect3.js")); assert!(modules.is_alias("file:///dir/redirect3.js"));
assert!(!modules.is_alias("./redirect3.js")); assert!(!modules.is_alias("file:///redirect3.js"));
assert_eq!(modules.get_id("./dir/redirect3.js").unwrap(), redirect3_id); assert_eq!(
modules.get_id("file:///dir/redirect3.js"),
Some(redirect3_id)
);
} else { } else {
unreachable!(); unreachable!();
} }
@ -861,17 +892,17 @@ mod tests {
// main.js // main.js
const MAIN_SRC: &str = r#" const MAIN_SRC: &str = r#"
// never_ready.js never loads. // never_ready.js never loads.
import "never_ready.js"; import "/never_ready.js";
// slow.js resolves after one tick. // slow.js resolves after one tick.
import "slow.js"; import "/slow.js";
"#; "#;
// slow.js // slow.js
const SLOW_SRC: &str = r#" const SLOW_SRC: &str = r#"
// Circular import of never_ready.js // Circular import of never_ready.js
// Does this trigger two Loader calls? It shouldn't. // Does this trigger two Loader calls? It shouldn't.
import "never_ready.js"; import "/never_ready.js";
import "a.js"; import "/a.js";
"#; "#;
#[test] #[test]
@ -881,7 +912,7 @@ mod tests {
let modules = loader.modules.clone(); let modules = loader.modules.clone();
let loads = loader.loads.clone(); let loads = loader.loads.clone();
let mut recursive_load = let mut recursive_load =
RecursiveLoad::new("main.js", loader, isolate, modules); RecursiveLoad::new("/main.js", loader, isolate, modules);
let result = recursive_load.poll(); let result = recursive_load.poll();
assert!(result.is_ok()); assert!(result.is_ok());
@ -889,7 +920,14 @@ mod tests {
{ {
let l = loads.lock().unwrap(); let l = loads.lock().unwrap();
assert_eq!(l.to_vec(), vec!["main.js", "never_ready.js", "slow.js"]); assert_eq!(
l.to_vec(),
vec![
"file:///main.js",
"file:///never_ready.js",
"file:///slow.js"
]
);
} }
for _ in 0..10 { for _ in 0..10 {
@ -900,13 +938,13 @@ mod tests {
assert_eq!( assert_eq!(
l.to_vec(), l.to_vec(),
vec![ vec![
"main.js", "file:///main.js",
"never_ready.js", "file:///never_ready.js",
"slow.js", "file:///slow.js",
"a.js", "file:///a.js",
"b.js", "file:///b.js",
"c.js", "file:///c.js",
"d.js" "file:///d.js"
] ]
); );
} }
@ -923,7 +961,7 @@ mod tests {
let isolate = loader.isolate.clone(); let isolate = loader.isolate.clone();
let modules = loader.modules.clone(); let modules = loader.modules.clone();
let mut recursive_load = let mut recursive_load =
RecursiveLoad::new("bad_import.js", loader, isolate, modules); RecursiveLoad::new("/bad_import.js", loader, isolate, modules);
let result = recursive_load.poll(); let result = recursive_load.poll();
assert!(result.is_err()); assert!(result.is_err());
let either_err = result.err().unwrap(); let either_err = result.err().unwrap();