2021-01-10 21:59:07 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
use rusty_v8 as v8;
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
use crate::bindings;
|
2020-09-14 12:48:57 -04:00
|
|
|
use crate::error::generic_error;
|
|
|
|
use crate::error::AnyError;
|
2019-06-12 19:55:59 -04:00
|
|
|
use crate::module_specifier::ModuleSpecifier;
|
2021-05-19 14:53:43 -04:00
|
|
|
use crate::runtime::exception_to_err_result;
|
2020-09-19 19:17:35 -04:00
|
|
|
use crate::OpState;
|
2019-11-16 19:17:47 -05:00
|
|
|
use futures::future::FutureExt;
|
2019-08-07 12:55:39 -04:00
|
|
|
use futures::stream::FuturesUnordered;
|
|
|
|
use futures::stream::Stream;
|
2021-05-19 14:53:43 -04:00
|
|
|
use futures::stream::StreamFuture;
|
2019-11-16 19:17:47 -05:00
|
|
|
use futures::stream::TryStreamExt;
|
2021-05-19 14:53:43 -04:00
|
|
|
use log::debug;
|
2020-09-19 19:17:35 -04:00
|
|
|
use std::cell::RefCell;
|
2019-03-26 11:56:34 -04:00
|
|
|
use std::collections::HashMap;
|
2019-04-16 15:13:42 -04:00
|
|
|
use std::collections::HashSet;
|
2021-06-28 21:03:02 -04:00
|
|
|
use std::collections::VecDeque;
|
2021-05-19 14:53:43 -04:00
|
|
|
use std::convert::TryFrom;
|
2019-11-16 19:17:47 -05:00
|
|
|
use std::future::Future;
|
|
|
|
use std::pin::Pin;
|
2020-02-14 19:18:36 -05:00
|
|
|
use std::rc::Rc;
|
2020-04-26 13:00:10 -04:00
|
|
|
use std::sync::atomic::AtomicI32;
|
|
|
|
use std::sync::atomic::Ordering;
|
2019-11-16 19:17:47 -05:00
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2021-03-26 12:34:25 -04:00
|
|
|
lazy_static::lazy_static! {
|
2020-04-26 13:00:10 -04:00
|
|
|
pub static ref NEXT_LOAD_ID: AtomicI32 = AtomicI32::new(0);
|
|
|
|
}
|
|
|
|
|
2020-05-28 13:36:43 -04:00
|
|
|
pub type ModuleId = i32;
|
|
|
|
pub type ModuleLoadId = i32;
|
|
|
|
|
2020-03-02 13:12:49 -05:00
|
|
|
/// EsModule source code that will be loaded into V8.
|
|
|
|
///
|
|
|
|
/// Users can implement `Into<ModuleInfo>` for different file types that
|
|
|
|
/// can be transpiled to valid EsModule.
|
|
|
|
///
|
|
|
|
/// Found module URL might be different from specified URL
|
|
|
|
/// used for loading due to redirections (like HTTP 303).
|
2021-09-05 10:22:45 -04:00
|
|
|
/// Eg. Both "`https://example.com/a.ts`" and
|
|
|
|
/// "`https://example.com/b.ts`" may point to "`https://example.com/c.ts`"
|
2020-03-02 13:12:49 -05:00
|
|
|
/// By keeping track of specified and found URL we can alias modules and avoid
|
|
|
|
/// recompiling the same code 3 times.
|
|
|
|
// TODO(bartlomieju): I have a strong opinion we should store all redirects
|
|
|
|
// that happened; not only first and final target. It would simplify a lot
|
|
|
|
// of things throughout the codebase otherwise we may end up requesting
|
|
|
|
// intermediate redirects from file loader.
|
2020-12-15 00:52:55 -05:00
|
|
|
#[derive(Debug, Clone, Eq, PartialEq)]
|
2020-03-02 13:12:49 -05:00
|
|
|
pub struct ModuleSource {
|
|
|
|
pub code: String,
|
|
|
|
pub module_url_specified: String,
|
|
|
|
pub module_url_found: String,
|
|
|
|
}
|
|
|
|
|
2020-04-30 08:37:06 -04:00
|
|
|
pub type PrepareLoadFuture =
|
2020-09-14 12:48:57 -04:00
|
|
|
dyn Future<Output = (ModuleLoadId, Result<RecursiveModuleLoad, AnyError>)>;
|
|
|
|
pub type ModuleSourceFuture =
|
|
|
|
dyn Future<Output = Result<ModuleSource, AnyError>>;
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2020-03-02 13:12:49 -05:00
|
|
|
pub trait ModuleLoader {
|
2019-03-26 11:56:34 -04:00
|
|
|
/// Returns an absolute URL.
|
|
|
|
/// When implementing an spec-complaint VM, this should be exactly the
|
|
|
|
/// algorithm described here:
|
2021-09-05 10:22:45 -04:00
|
|
|
/// <https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier>
|
2020-01-25 12:53:16 -05:00
|
|
|
///
|
|
|
|
/// `is_main` can be used to resolve from current working directory or
|
|
|
|
/// apply import map for child imports.
|
2019-06-09 09:08:20 -04:00
|
|
|
fn resolve(
|
|
|
|
&self,
|
2020-10-02 07:13:23 -04:00
|
|
|
op_state: Rc<RefCell<OpState>>,
|
2019-06-09 09:08:20 -04:00
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
2020-09-06 10:50:49 -04:00
|
|
|
_is_main: bool,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<ModuleSpecifier, AnyError>;
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2019-06-12 19:55:59 -04:00
|
|
|
/// Given ModuleSpecifier, load its source code.
|
2020-01-25 12:53:16 -05:00
|
|
|
///
|
|
|
|
/// `is_dyn_import` can be used to check permissions or deny
|
|
|
|
/// dynamic imports altogether.
|
2019-06-12 19:55:59 -04:00
|
|
|
fn load(
|
|
|
|
&self,
|
2020-09-19 19:17:35 -04:00
|
|
|
op_state: Rc<RefCell<OpState>>,
|
2019-06-12 19:55:59 -04:00
|
|
|
module_specifier: &ModuleSpecifier,
|
2019-11-25 09:33:23 -05:00
|
|
|
maybe_referrer: Option<ModuleSpecifier>,
|
2020-01-25 12:53:16 -05:00
|
|
|
is_dyn_import: bool,
|
2020-03-02 13:12:49 -05:00
|
|
|
) -> Pin<Box<ModuleSourceFuture>>;
|
2020-04-30 08:37:06 -04:00
|
|
|
|
|
|
|
/// This hook can be used by implementors to do some preparation
|
|
|
|
/// work before starting loading of modules.
|
|
|
|
///
|
|
|
|
/// For example implementor might download multiple modules in
|
|
|
|
/// parallel and transpile them to final JS sources before
|
2020-09-06 15:44:29 -04:00
|
|
|
/// yielding control back to the runtime.
|
2020-04-30 08:37:06 -04:00
|
|
|
///
|
|
|
|
/// It's not required to implement this method.
|
|
|
|
fn prepare_load(
|
|
|
|
&self,
|
2020-09-19 19:17:35 -04:00
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
2020-04-30 08:37:06 -04:00
|
|
|
_load_id: ModuleLoadId,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<String>,
|
|
|
|
_is_dyn_import: bool,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Pin<Box<dyn Future<Output = Result<(), AnyError>>>> {
|
2020-04-30 08:37:06 -04:00
|
|
|
async { Ok(()) }.boxed_local()
|
|
|
|
}
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
2020-09-06 10:50:49 -04:00
|
|
|
/// Placeholder structure used when creating
|
2020-09-06 15:44:29 -04:00
|
|
|
/// a runtime that doesn't support module loading.
|
2020-12-11 12:49:26 -05:00
|
|
|
pub struct NoopModuleLoader;
|
2020-09-06 10:50:49 -04:00
|
|
|
|
|
|
|
impl ModuleLoader for NoopModuleLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
2020-10-02 07:13:23 -04:00
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
2020-09-06 10:50:49 -04:00
|
|
|
_specifier: &str,
|
|
|
|
_referrer: &str,
|
|
|
|
_is_main: bool,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
|
|
|
Err(generic_error("Module loading is not supported"))
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
2020-09-19 19:17:35 -04:00
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
2020-09-06 10:50:49 -04:00
|
|
|
_module_specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<ModuleSpecifier>,
|
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
2020-09-14 12:48:57 -04:00
|
|
|
async { Err(generic_error("Module loading is not supported")) }
|
2020-09-06 10:50:49 -04:00
|
|
|
.boxed_local()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-27 16:45:38 -05:00
|
|
|
/// Basic file system module loader.
|
|
|
|
///
|
|
|
|
/// Note that this loader will **block** event loop
|
|
|
|
/// when loading file as it uses synchronous FS API
|
|
|
|
/// from standard library.
|
|
|
|
pub struct FsModuleLoader;
|
|
|
|
|
|
|
|
impl ModuleLoader for FsModuleLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_is_main: bool,
|
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
2021-02-17 13:47:18 -05:00
|
|
|
Ok(crate::resolve_import(specifier, referrer)?)
|
2020-11-27 16:45:38 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<ModuleSpecifier>,
|
|
|
|
_is_dynamic: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
let module_specifier = module_specifier.clone();
|
|
|
|
async move {
|
2021-02-17 13:47:18 -05:00
|
|
|
let path = module_specifier.to_file_path().map_err(|_| {
|
2020-11-27 16:45:38 -05:00
|
|
|
generic_error(format!(
|
|
|
|
"Provided module specifier \"{}\" is not a file URL.",
|
|
|
|
module_specifier
|
|
|
|
))
|
|
|
|
})?;
|
|
|
|
let code = std::fs::read_to_string(path)?;
|
|
|
|
let module = ModuleSource {
|
|
|
|
code,
|
|
|
|
module_url_specified: module_specifier.to_string(),
|
|
|
|
module_url_found: module_specifier.to_string(),
|
|
|
|
};
|
|
|
|
Ok(module)
|
|
|
|
}
|
|
|
|
.boxed_local()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-19 10:14:43 -04:00
|
|
|
/// Describes the entrypoint of a recursive module load.
|
|
|
|
#[derive(Debug)]
|
|
|
|
enum LoadInit {
|
|
|
|
/// Main module specifier.
|
|
|
|
Main(String),
|
2021-09-17 21:44:53 -04:00
|
|
|
/// Module specifier for side module.
|
|
|
|
Side(String),
|
2021-06-19 10:14:43 -04:00
|
|
|
/// Dynamic import specifier with referrer.
|
|
|
|
DynamicImport(String, String),
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Eq, PartialEq)]
|
2020-01-08 09:06:04 -05:00
|
|
|
pub enum LoadState {
|
2021-06-19 10:14:43 -04:00
|
|
|
Init,
|
2019-08-07 12:55:39 -04:00
|
|
|
LoadingRoot,
|
2020-01-08 09:06:04 -05:00
|
|
|
LoadingImports,
|
|
|
|
Done,
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
2020-09-06 15:44:29 -04:00
|
|
|
/// This future is used to implement parallel async module loading.
|
2020-01-08 09:06:04 -05:00
|
|
|
pub struct RecursiveModuleLoad {
|
2021-06-19 10:14:43 -04:00
|
|
|
init: LoadInit,
|
2020-04-30 08:37:06 -04:00
|
|
|
// TODO(bartlomieju): in future this value should
|
|
|
|
// be randomized
|
2020-04-26 13:00:10 -04:00
|
|
|
pub id: ModuleLoadId,
|
2020-01-08 09:06:04 -05:00
|
|
|
pub root_module_id: Option<ModuleId>,
|
|
|
|
pub state: LoadState,
|
2021-06-28 21:03:02 -04:00
|
|
|
pub module_map_rc: Rc<RefCell<ModuleMap>>,
|
|
|
|
// These two fields are copied from `module_map_rc`, but they are cloned ahead
|
|
|
|
// of time to avoid already-borrowed errors.
|
|
|
|
pub op_state: Rc<RefCell<OpState>>,
|
2020-03-02 13:12:49 -05:00
|
|
|
pub loader: Rc<dyn ModuleLoader>,
|
|
|
|
pub pending: FuturesUnordered<Pin<Box<ModuleSourceFuture>>>,
|
2021-06-28 21:03:02 -04:00
|
|
|
pub visited: HashSet<ModuleSpecifier>,
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
impl RecursiveModuleLoad {
|
2019-08-07 12:55:39 -04:00
|
|
|
/// Starts a new parallel load of the given URL of the main module.
|
2021-06-28 21:03:02 -04:00
|
|
|
pub fn main(specifier: &str, module_map_rc: Rc<RefCell<ModuleMap>>) -> Self {
|
|
|
|
Self::new(LoadInit::Main(specifier.to_string()), module_map_rc)
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
|
|
|
|
2021-09-17 21:44:53 -04:00
|
|
|
pub fn side(specifier: &str, module_map_rc: Rc<RefCell<ModuleMap>>) -> Self {
|
|
|
|
Self::new(LoadInit::Side(specifier.to_string()), module_map_rc)
|
|
|
|
}
|
|
|
|
|
2019-08-07 12:55:39 -04:00
|
|
|
pub fn dynamic_import(
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
2021-06-28 21:03:02 -04:00
|
|
|
module_map_rc: Rc<RefCell<ModuleMap>>,
|
2019-08-07 12:55:39 -04:00
|
|
|
) -> Self {
|
2021-06-19 10:14:43 -04:00
|
|
|
let init =
|
|
|
|
LoadInit::DynamicImport(specifier.to_string(), referrer.to_string());
|
2021-06-28 21:03:02 -04:00
|
|
|
Self::new(init, module_map_rc)
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
pub fn is_dynamic_import(&self) -> bool {
|
2021-06-19 10:14:43 -04:00
|
|
|
matches!(self.init, LoadInit::DynamicImport(..))
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
|
|
|
|
2021-06-28 21:03:02 -04:00
|
|
|
fn new(init: LoadInit, module_map_rc: Rc<RefCell<ModuleMap>>) -> Self {
|
|
|
|
let op_state = module_map_rc.borrow().op_state.clone();
|
|
|
|
let loader = module_map_rc.borrow().loader.clone();
|
|
|
|
let mut load = Self {
|
2020-04-26 13:00:10 -04:00
|
|
|
id: NEXT_LOAD_ID.fetch_add(1, Ordering::SeqCst),
|
2020-01-08 09:06:04 -05:00
|
|
|
root_module_id: None,
|
2021-06-19 10:14:43 -04:00
|
|
|
init,
|
|
|
|
state: LoadState::Init,
|
2021-06-28 21:03:02 -04:00
|
|
|
module_map_rc: module_map_rc.clone(),
|
|
|
|
op_state,
|
2019-06-05 16:35:38 -04:00
|
|
|
loader,
|
2019-08-07 12:55:39 -04:00
|
|
|
pending: FuturesUnordered::new(),
|
2021-06-28 21:03:02 -04:00
|
|
|
visited: HashSet::new(),
|
|
|
|
};
|
|
|
|
// Ignore the error here, let it be hit in `Stream::poll_next()`.
|
|
|
|
if let Ok(root_specifier) = load.resolve_root() {
|
|
|
|
if let Some(module_id) =
|
|
|
|
module_map_rc.borrow().get_id(root_specifier.as_str())
|
|
|
|
{
|
|
|
|
load.root_module_id = Some(module_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
load
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn resolve_root(&self) -> Result<ModuleSpecifier, AnyError> {
|
|
|
|
match self.init {
|
|
|
|
LoadInit::Main(ref specifier) => {
|
|
|
|
self
|
|
|
|
.loader
|
|
|
|
.resolve(self.op_state.clone(), specifier, ".", true)
|
|
|
|
}
|
2021-09-17 21:44:53 -04:00
|
|
|
LoadInit::Side(ref specifier) => {
|
|
|
|
self
|
|
|
|
.loader
|
|
|
|
.resolve(self.op_state.clone(), specifier, ".", false)
|
|
|
|
}
|
2021-06-28 21:03:02 -04:00
|
|
|
LoadInit::DynamicImport(ref specifier, ref referrer) => self
|
|
|
|
.loader
|
|
|
|
.resolve(self.op_state.clone(), specifier, referrer, false),
|
2019-04-16 15:13:42 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-19 10:14:43 -04:00
|
|
|
pub async fn prepare(&self) -> Result<(), AnyError> {
|
2021-06-28 21:03:02 -04:00
|
|
|
let op_state = self.op_state.clone();
|
2021-06-19 10:14:43 -04:00
|
|
|
let (module_specifier, maybe_referrer) = match self.init {
|
2021-06-28 21:03:02 -04:00
|
|
|
LoadInit::Main(ref specifier) => {
|
2020-10-02 07:13:23 -04:00
|
|
|
let spec =
|
2021-06-19 10:14:43 -04:00
|
|
|
self
|
2020-10-02 07:13:23 -04:00
|
|
|
.loader
|
2021-06-28 21:03:02 -04:00
|
|
|
.resolve(op_state.clone(), specifier, ".", true)?;
|
2020-04-30 08:37:06 -04:00
|
|
|
(spec, None)
|
|
|
|
}
|
2021-09-17 21:44:53 -04:00
|
|
|
LoadInit::Side(ref specifier) => {
|
|
|
|
let spec =
|
|
|
|
self
|
|
|
|
.loader
|
|
|
|
.resolve(op_state.clone(), specifier, ".", false)?;
|
|
|
|
(spec, None)
|
|
|
|
}
|
2021-06-19 10:14:43 -04:00
|
|
|
LoadInit::DynamicImport(ref specifier, ref referrer) => {
|
2021-06-28 21:03:02 -04:00
|
|
|
let spec =
|
|
|
|
self
|
|
|
|
.loader
|
|
|
|
.resolve(op_state.clone(), specifier, referrer, false)?;
|
2020-04-30 08:37:06 -04:00
|
|
|
(spec, Some(referrer.to_string()))
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-06-19 10:14:43 -04:00
|
|
|
self
|
2020-04-30 08:37:06 -04:00
|
|
|
.loader
|
|
|
|
.prepare_load(
|
2021-06-28 21:03:02 -04:00
|
|
|
op_state,
|
2020-04-30 08:37:06 -04:00
|
|
|
self.id,
|
|
|
|
&module_specifier,
|
|
|
|
maybe_referrer,
|
|
|
|
self.is_dynamic_import(),
|
|
|
|
)
|
2021-06-19 10:14:43 -04:00
|
|
|
.await
|
2020-01-08 09:06:04 -05:00
|
|
|
}
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
pub fn is_currently_loading_main_module(&self) -> bool {
|
2021-09-17 21:44:53 -04:00
|
|
|
!self.is_dynamic_import()
|
|
|
|
&& matches!(self.init, LoadInit::Main(..))
|
|
|
|
&& self.state == LoadState::LoadingRoot
|
2021-05-19 14:53:43 -04:00
|
|
|
}
|
|
|
|
|
2021-06-28 21:03:02 -04:00
|
|
|
pub fn register_and_recurse(
|
|
|
|
&mut self,
|
|
|
|
scope: &mut v8::HandleScope,
|
|
|
|
module_source: &ModuleSource,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
// Register the module in the module map unless it's already there. If the
|
|
|
|
// specified URL and the "true" URL are different, register the alias.
|
|
|
|
if module_source.module_url_specified != module_source.module_url_found {
|
|
|
|
self.module_map_rc.borrow_mut().alias(
|
|
|
|
&module_source.module_url_specified,
|
|
|
|
&module_source.module_url_found,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
let maybe_module_id = self
|
|
|
|
.module_map_rc
|
|
|
|
.borrow()
|
|
|
|
.get_id(&module_source.module_url_found);
|
|
|
|
let module_id = match maybe_module_id {
|
|
|
|
Some(id) => {
|
|
|
|
debug!(
|
|
|
|
"Already-registered module fetched again: {}",
|
|
|
|
module_source.module_url_found
|
|
|
|
);
|
|
|
|
id
|
|
|
|
}
|
|
|
|
None => self.module_map_rc.borrow_mut().new_module(
|
|
|
|
scope,
|
|
|
|
self.is_currently_loading_main_module(),
|
|
|
|
&module_source.module_url_found,
|
|
|
|
&module_source.code,
|
|
|
|
)?,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Recurse the module's imports. There are two cases for each import:
|
|
|
|
// 1. If the module is not in the module map, start a new load for it in
|
|
|
|
// `self.pending`. The result of that load should eventually be passed to
|
|
|
|
// this function for recursion.
|
|
|
|
// 2. If the module is already in the module map, queue it up to be
|
|
|
|
// recursed synchronously here.
|
|
|
|
// This robustly ensures that the whole graph is in the module map before
|
|
|
|
// `LoadState::Done` is set.
|
|
|
|
let specifier =
|
|
|
|
crate::resolve_url(&module_source.module_url_found).unwrap();
|
|
|
|
let mut already_registered = VecDeque::new();
|
|
|
|
already_registered.push_back((module_id, specifier.clone()));
|
|
|
|
self.visited.insert(specifier);
|
|
|
|
while let Some((module_id, referrer)) = already_registered.pop_front() {
|
|
|
|
let imports = self
|
|
|
|
.module_map_rc
|
|
|
|
.borrow()
|
|
|
|
.get_children(module_id)
|
|
|
|
.unwrap()
|
|
|
|
.clone();
|
|
|
|
for specifier in imports {
|
|
|
|
if !self.visited.contains(&specifier) {
|
|
|
|
if let Some(module_id) =
|
|
|
|
self.module_map_rc.borrow().get_id(specifier.as_str())
|
|
|
|
{
|
|
|
|
already_registered.push_back((module_id, specifier.clone()));
|
|
|
|
} else {
|
|
|
|
let fut = self.loader.load(
|
|
|
|
self.op_state.clone(),
|
|
|
|
&specifier,
|
|
|
|
Some(referrer.clone()),
|
|
|
|
self.is_dynamic_import(),
|
|
|
|
);
|
|
|
|
self.pending.push(fut.boxed_local());
|
|
|
|
}
|
|
|
|
self.visited.insert(specifier);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update `self.state` however applicable.
|
2021-05-19 14:53:43 -04:00
|
|
|
if self.state == LoadState::LoadingRoot {
|
|
|
|
self.root_module_id = Some(module_id);
|
|
|
|
self.state = LoadState::LoadingImports;
|
|
|
|
}
|
|
|
|
if self.pending.is_empty() {
|
|
|
|
self.state = LoadState::Done;
|
|
|
|
}
|
|
|
|
|
2021-06-28 21:03:02 -04:00
|
|
|
Ok(())
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
|
|
|
}
|
2019-04-16 15:13:42 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
impl Stream for RecursiveModuleLoad {
|
2020-09-14 12:48:57 -04:00
|
|
|
type Item = Result<ModuleSource, AnyError>;
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
fn poll_next(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context,
|
|
|
|
) -> Poll<Option<Self::Item>> {
|
|
|
|
let inner = self.get_mut();
|
2021-06-28 21:03:02 -04:00
|
|
|
// IMPORTANT: Do not borrow `inner.module_map_rc` here. It may not be
|
|
|
|
// available.
|
2019-11-16 19:17:47 -05:00
|
|
|
match inner.state {
|
2021-06-19 10:14:43 -04:00
|
|
|
LoadState::Init => {
|
2021-06-28 21:03:02 -04:00
|
|
|
let module_specifier = match inner.resolve_root() {
|
2021-06-19 10:14:43 -04:00
|
|
|
Ok(url) => url,
|
|
|
|
Err(error) => return Poll::Ready(Some(Err(error))),
|
|
|
|
};
|
2021-06-28 21:03:02 -04:00
|
|
|
let load_fut = if let Some(_module_id) = inner.root_module_id {
|
|
|
|
// The root module is already in the module map.
|
|
|
|
// TODO(nayeemrmn): In this case we would ideally skip to
|
|
|
|
// `LoadState::LoadingImports` and synchronously recurse the imports
|
|
|
|
// like the bottom of `RecursiveModuleLoad::register_and_recurse()`.
|
|
|
|
// But the module map cannot be borrowed here. Instead fake a load
|
|
|
|
// event so it gets passed to that function and recursed eventually.
|
|
|
|
futures::future::ok(ModuleSource {
|
|
|
|
module_url_specified: module_specifier.to_string(),
|
|
|
|
module_url_found: module_specifier.to_string(),
|
|
|
|
// The code will be discarded, since this module is already in the
|
|
|
|
// module map.
|
|
|
|
code: Default::default(),
|
|
|
|
})
|
|
|
|
.boxed()
|
|
|
|
} else {
|
|
|
|
let maybe_referrer = match inner.init {
|
|
|
|
LoadInit::DynamicImport(_, ref referrer) => {
|
|
|
|
crate::resolve_url(referrer).ok()
|
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
};
|
|
|
|
inner
|
2021-06-19 10:14:43 -04:00
|
|
|
.loader
|
2021-06-28 21:03:02 -04:00
|
|
|
.load(
|
|
|
|
inner.op_state.clone(),
|
|
|
|
&module_specifier,
|
|
|
|
maybe_referrer,
|
|
|
|
inner.is_dynamic_import(),
|
|
|
|
)
|
|
|
|
.boxed_local()
|
2021-06-19 10:14:43 -04:00
|
|
|
};
|
|
|
|
inner.pending.push(load_fut);
|
|
|
|
inner.state = LoadState::LoadingRoot;
|
2019-11-16 19:17:47 -05:00
|
|
|
inner.try_poll_next_unpin(cx)
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
2020-01-08 09:06:04 -05:00
|
|
|
LoadState::LoadingRoot | LoadState::LoadingImports => {
|
2019-11-16 19:17:47 -05:00
|
|
|
match inner.pending.try_poll_next_unpin(cx)? {
|
|
|
|
Poll::Ready(None) => unreachable!(),
|
2020-01-08 09:06:04 -05:00
|
|
|
Poll::Ready(Some(info)) => Poll::Ready(Some(Ok(info))),
|
2019-11-16 19:17:47 -05:00
|
|
|
Poll::Pending => Poll::Pending,
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
|
|
|
}
|
2020-01-08 09:06:04 -05:00
|
|
|
LoadState::Done => Poll::Ready(None),
|
2019-11-16 19:17:47 -05:00
|
|
|
}
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
pub struct ModuleInfo {
|
2020-11-21 10:23:35 -05:00
|
|
|
pub id: ModuleId,
|
2021-05-19 14:53:43 -04:00
|
|
|
// Used in "bindings.rs" for "import.meta.main" property value.
|
2020-01-08 09:06:04 -05:00
|
|
|
pub main: bool,
|
|
|
|
pub name: String,
|
2020-01-25 12:53:16 -05:00
|
|
|
pub import_specifiers: Vec<ModuleSpecifier>,
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
2019-04-18 21:33:50 -04:00
|
|
|
/// A symbolic module entity.
|
2019-05-09 16:44:30 -04:00
|
|
|
enum SymbolicModule {
|
2019-04-18 21:33:50 -04:00
|
|
|
/// This module is an alias to another module.
|
|
|
|
/// This is useful such that multiple names could point to
|
|
|
|
/// the same underlying module (particularly due to redirects).
|
|
|
|
Alias(String),
|
|
|
|
/// This module associates with a V8 module by id.
|
2020-01-06 14:07:35 -05:00
|
|
|
Mod(ModuleId),
|
2019-04-18 21:33:50 -04:00
|
|
|
}
|
|
|
|
|
2019-03-26 11:56:34 -04:00
|
|
|
/// A collection of JS modules.
|
2021-02-23 09:22:55 -05:00
|
|
|
pub struct ModuleMap {
|
2021-05-19 14:53:43 -04:00
|
|
|
// Handling of specifiers and v8 objects
|
2020-11-21 10:23:35 -05:00
|
|
|
ids_by_handle: HashMap<v8::Global<v8::Module>, ModuleId>,
|
|
|
|
handles_by_id: HashMap<ModuleId, v8::Global<v8::Module>>,
|
|
|
|
info: HashMap<ModuleId, ModuleInfo>,
|
2021-02-23 09:22:55 -05:00
|
|
|
by_name: HashMap<String, SymbolicModule>,
|
2020-11-21 10:23:35 -05:00
|
|
|
next_module_id: ModuleId,
|
2021-05-19 14:53:43 -04:00
|
|
|
|
|
|
|
// Handling of futures for loading module sources
|
|
|
|
pub loader: Rc<dyn ModuleLoader>,
|
|
|
|
op_state: Rc<RefCell<OpState>>,
|
|
|
|
pub(crate) dynamic_import_map:
|
|
|
|
HashMap<ModuleLoadId, v8::Global<v8::PromiseResolver>>,
|
|
|
|
pub(crate) preparing_dynamic_imports:
|
|
|
|
FuturesUnordered<Pin<Box<PrepareLoadFuture>>>,
|
|
|
|
pub(crate) pending_dynamic_imports:
|
|
|
|
FuturesUnordered<StreamFuture<RecursiveModuleLoad>>,
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
2021-02-23 09:22:55 -05:00
|
|
|
impl ModuleMap {
|
2021-05-19 14:53:43 -04:00
|
|
|
pub fn new(
|
|
|
|
loader: Rc<dyn ModuleLoader>,
|
|
|
|
op_state: Rc<RefCell<OpState>>,
|
|
|
|
) -> ModuleMap {
|
2019-03-26 11:56:34 -04:00
|
|
|
Self {
|
2020-11-21 10:23:35 -05:00
|
|
|
ids_by_handle: HashMap::new(),
|
2021-05-19 14:53:43 -04:00
|
|
|
handles_by_id: HashMap::new(),
|
2019-03-26 11:56:34 -04:00
|
|
|
info: HashMap::new(),
|
2021-02-23 09:22:55 -05:00
|
|
|
by_name: HashMap::new(),
|
2020-11-21 10:23:35 -05:00
|
|
|
next_module_id: 1,
|
2021-05-19 14:53:43 -04:00
|
|
|
loader,
|
|
|
|
op_state,
|
|
|
|
dynamic_import_map: HashMap::new(),
|
|
|
|
preparing_dynamic_imports: FuturesUnordered::new(),
|
|
|
|
pending_dynamic_imports: FuturesUnordered::new(),
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-23 09:22:55 -05:00
|
|
|
/// Get module id, following all aliases in case of module specifier
|
|
|
|
/// that had been redirected.
|
2020-01-06 14:07:35 -05:00
|
|
|
pub fn get_id(&self, name: &str) -> Option<ModuleId> {
|
2021-02-23 09:22:55 -05:00
|
|
|
let mut mod_name = name;
|
|
|
|
loop {
|
|
|
|
let symbolic_module = self.by_name.get(mod_name)?;
|
|
|
|
match symbolic_module {
|
|
|
|
SymbolicModule::Alias(target) => {
|
|
|
|
mod_name = target;
|
|
|
|
}
|
|
|
|
SymbolicModule::Mod(mod_id) => return Some(*mod_id),
|
|
|
|
}
|
|
|
|
}
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
// Create and compile an ES module.
|
|
|
|
pub(crate) fn new_module(
|
2020-01-08 09:06:04 -05:00
|
|
|
&mut self,
|
2021-05-19 14:53:43 -04:00
|
|
|
scope: &mut v8::HandleScope,
|
2020-01-08 09:06:04 -05:00
|
|
|
main: bool,
|
2021-05-19 14:53:43 -04:00
|
|
|
name: &str,
|
|
|
|
source: &str,
|
|
|
|
) -> Result<ModuleId, AnyError> {
|
|
|
|
let name_str = v8::String::new(scope, name).unwrap();
|
|
|
|
let source_str = v8::String::new(scope, source).unwrap();
|
|
|
|
|
|
|
|
let origin = bindings::module_origin(scope, name_str);
|
|
|
|
let source = v8::script_compiler::Source::new(source_str, Some(&origin));
|
|
|
|
|
|
|
|
let tc_scope = &mut v8::TryCatch::new(scope);
|
|
|
|
|
|
|
|
let maybe_module = v8::script_compiler::compile_module(tc_scope, source);
|
|
|
|
|
|
|
|
if tc_scope.has_caught() {
|
|
|
|
assert!(maybe_module.is_none());
|
|
|
|
let e = tc_scope.exception().unwrap();
|
|
|
|
return exception_to_err_result(tc_scope, e, false);
|
|
|
|
}
|
|
|
|
|
|
|
|
let module = maybe_module.unwrap();
|
|
|
|
|
|
|
|
let mut import_specifiers: Vec<ModuleSpecifier> = vec![];
|
|
|
|
let module_requests = module.get_module_requests();
|
|
|
|
for i in 0..module_requests.length() {
|
|
|
|
let module_request = v8::Local::<v8::ModuleRequest>::try_from(
|
|
|
|
module_requests.get(tc_scope, i).unwrap(),
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let import_specifier = module_request
|
|
|
|
.get_specifier()
|
|
|
|
.to_rust_string_lossy(tc_scope);
|
|
|
|
let module_specifier = self.loader.resolve(
|
|
|
|
self.op_state.clone(),
|
|
|
|
&import_specifier,
|
|
|
|
name,
|
|
|
|
false,
|
|
|
|
)?;
|
|
|
|
import_specifiers.push(module_specifier);
|
|
|
|
}
|
|
|
|
|
2021-09-17 21:44:53 -04:00
|
|
|
if main {
|
|
|
|
let maybe_main_module = self.info.values().find(|module| module.main);
|
|
|
|
if let Some(main_module) = maybe_main_module {
|
|
|
|
return Err(generic_error(
|
|
|
|
format!("Trying to create \"main\" module ({:?}), when one already exists ({:?})",
|
|
|
|
name,
|
|
|
|
main_module.name,
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let handle = v8::Global::<v8::Module>::new(tc_scope, module);
|
2020-11-21 10:23:35 -05:00
|
|
|
let id = self.next_module_id;
|
|
|
|
self.next_module_id += 1;
|
2021-02-23 09:22:55 -05:00
|
|
|
self
|
|
|
|
.by_name
|
|
|
|
.insert(name.to_string(), SymbolicModule::Mod(id));
|
2020-11-21 10:23:35 -05:00
|
|
|
self.handles_by_id.insert(id, handle.clone());
|
|
|
|
self.ids_by_handle.insert(handle, id);
|
2019-03-26 11:56:34 -04:00
|
|
|
self.info.insert(
|
|
|
|
id,
|
|
|
|
ModuleInfo {
|
2020-11-21 10:23:35 -05:00
|
|
|
id,
|
2020-01-08 09:06:04 -05:00
|
|
|
main,
|
2021-05-19 14:53:43 -04:00
|
|
|
name: name.to_string(),
|
2020-01-08 09:06:04 -05:00
|
|
|
import_specifiers,
|
2019-03-26 11:56:34 -04:00
|
|
|
},
|
|
|
|
);
|
2021-05-19 14:53:43 -04:00
|
|
|
|
|
|
|
Ok(id)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_children(&self, id: ModuleId) -> Option<&Vec<ModuleSpecifier>> {
|
|
|
|
self.info.get(&id).map(|i| &i.import_specifiers)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn is_registered(&self, specifier: &ModuleSpecifier) -> bool {
|
|
|
|
self.get_id(specifier.as_str()).is_some()
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
2019-04-16 15:13:42 -04:00
|
|
|
|
2019-04-18 21:33:50 -04:00
|
|
|
pub fn alias(&mut self, name: &str, target: &str) {
|
2021-02-23 09:22:55 -05:00
|
|
|
self
|
|
|
|
.by_name
|
|
|
|
.insert(name.to_string(), SymbolicModule::Alias(target.to_string()));
|
2019-04-18 21:33:50 -04:00
|
|
|
}
|
|
|
|
|
2020-09-14 23:49:12 -04:00
|
|
|
#[cfg(test)]
|
2019-04-18 21:33:50 -04:00
|
|
|
pub fn is_alias(&self, name: &str) -> bool {
|
2021-02-23 09:22:55 -05:00
|
|
|
let cond = self.by_name.get(name);
|
|
|
|
matches!(cond, Some(SymbolicModule::Alias(_)))
|
2019-04-18 21:33:50 -04:00
|
|
|
}
|
|
|
|
|
2020-11-21 10:23:35 -05:00
|
|
|
pub fn get_handle(&self, id: ModuleId) -> Option<v8::Global<v8::Module>> {
|
|
|
|
self.handles_by_id.get(&id).cloned()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_info(
|
|
|
|
&self,
|
|
|
|
global: &v8::Global<v8::Module>,
|
|
|
|
) -> Option<&ModuleInfo> {
|
|
|
|
if let Some(id) = self.ids_by_handle.get(global) {
|
|
|
|
return self.info.get(id);
|
2020-01-08 09:06:04 -05:00
|
|
|
}
|
2020-11-21 10:23:35 -05:00
|
|
|
|
|
|
|
None
|
2020-01-08 09:06:04 -05:00
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
|
|
|
|
pub fn get_info_by_id(&self, id: &ModuleId) -> Option<&ModuleInfo> {
|
|
|
|
self.info.get(id)
|
|
|
|
}
|
2021-05-19 14:53:43 -04:00
|
|
|
|
2021-06-19 10:14:43 -04:00
|
|
|
pub async fn load_main(
|
2021-06-28 21:03:02 -04:00
|
|
|
module_map_rc: Rc<RefCell<ModuleMap>>,
|
2021-05-19 14:53:43 -04:00
|
|
|
specifier: &str,
|
2021-06-19 10:14:43 -04:00
|
|
|
) -> Result<RecursiveModuleLoad, AnyError> {
|
2021-06-28 21:03:02 -04:00
|
|
|
let load = RecursiveModuleLoad::main(specifier, module_map_rc.clone());
|
2021-06-19 10:14:43 -04:00
|
|
|
load.prepare().await?;
|
|
|
|
Ok(load)
|
2021-05-19 14:53:43 -04:00
|
|
|
}
|
|
|
|
|
2021-09-17 21:44:53 -04:00
|
|
|
pub async fn load_side(
|
|
|
|
module_map_rc: Rc<RefCell<ModuleMap>>,
|
|
|
|
specifier: &str,
|
|
|
|
) -> Result<RecursiveModuleLoad, AnyError> {
|
|
|
|
let load = RecursiveModuleLoad::side(specifier, module_map_rc.clone());
|
|
|
|
load.prepare().await?;
|
|
|
|
Ok(load)
|
|
|
|
}
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
// Initiate loading of a module graph imported using `import()`.
|
|
|
|
pub fn load_dynamic_import(
|
2021-06-28 21:03:02 -04:00
|
|
|
module_map_rc: Rc<RefCell<ModuleMap>>,
|
2021-05-19 14:53:43 -04:00
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
resolver_handle: v8::Global<v8::PromiseResolver>,
|
|
|
|
) {
|
|
|
|
let load = RecursiveModuleLoad::dynamic_import(
|
|
|
|
specifier,
|
|
|
|
referrer,
|
2021-06-28 21:03:02 -04:00
|
|
|
module_map_rc.clone(),
|
|
|
|
);
|
|
|
|
module_map_rc
|
|
|
|
.borrow_mut()
|
|
|
|
.dynamic_import_map
|
|
|
|
.insert(load.id, resolver_handle);
|
|
|
|
let resolve_result = module_map_rc.borrow().loader.resolve(
|
|
|
|
module_map_rc.borrow().op_state.clone(),
|
|
|
|
specifier,
|
|
|
|
referrer,
|
|
|
|
false,
|
2021-05-19 14:53:43 -04:00
|
|
|
);
|
2021-06-19 10:14:43 -04:00
|
|
|
let fut = match resolve_result {
|
|
|
|
Ok(module_specifier) => {
|
2021-06-28 21:03:02 -04:00
|
|
|
if module_map_rc.borrow().is_registered(&module_specifier) {
|
2021-06-19 10:14:43 -04:00
|
|
|
async move { (load.id, Ok(load)) }.boxed_local()
|
|
|
|
} else {
|
|
|
|
async move { (load.id, load.prepare().await.map(|()| load)) }
|
|
|
|
.boxed_local()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(error) => async move { (load.id, Err(error)) }.boxed_local(),
|
|
|
|
};
|
2021-06-28 21:03:02 -04:00
|
|
|
module_map_rc
|
|
|
|
.borrow_mut()
|
|
|
|
.preparing_dynamic_imports
|
|
|
|
.push(fut);
|
2021-05-19 14:53:43 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_pending_dynamic_imports(&self) -> bool {
|
|
|
|
!(self.preparing_dynamic_imports.is_empty()
|
|
|
|
&& self.pending_dynamic_imports.is_empty())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Called by `module_resolve_callback` during module instantiation.
|
|
|
|
pub fn resolve_callback<'s>(
|
|
|
|
&self,
|
|
|
|
scope: &mut v8::HandleScope<'s>,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
) -> Option<v8::Local<'s, v8::Module>> {
|
|
|
|
let resolved_specifier = self
|
|
|
|
.loader
|
|
|
|
.resolve(self.op_state.clone(), specifier, referrer, false)
|
|
|
|
.expect("Module should have been already resolved");
|
|
|
|
|
|
|
|
if let Some(id) = self.get_id(resolved_specifier.as_str()) {
|
|
|
|
if let Some(handle) = self.get_handle(id) {
|
|
|
|
return Some(v8::Local::new(scope, handle));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2021-05-19 14:53:43 -04:00
|
|
|
use crate::serialize_op_result;
|
2020-09-06 15:44:29 -04:00
|
|
|
use crate::JsRuntime;
|
2021-05-19 14:53:43 -04:00
|
|
|
use crate::Op;
|
|
|
|
use crate::OpPayload;
|
2020-09-11 09:18:49 -04:00
|
|
|
use crate::RuntimeOptions;
|
2019-11-16 19:17:47 -05:00
|
|
|
use futures::future::FutureExt;
|
2021-07-06 23:48:01 -04:00
|
|
|
use parking_lot::Mutex;
|
2019-07-10 18:53:48 -04:00
|
|
|
use std::error::Error;
|
2019-04-16 15:13:42 -04:00
|
|
|
use std::fmt;
|
2019-11-16 19:17:47 -05:00
|
|
|
use std::future::Future;
|
2021-05-19 14:53:43 -04:00
|
|
|
use std::io;
|
2021-06-28 21:03:02 -04:00
|
|
|
use std::path::PathBuf;
|
2021-05-19 14:53:43 -04:00
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
2020-02-14 19:18:36 -05:00
|
|
|
use std::sync::Arc;
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2020-05-28 13:36:43 -04:00
|
|
|
// TODO(ry) Sadly FuturesUnordered requires the current task to be set. So
|
|
|
|
// even though we are only using poll() in these tests and not Tokio, we must
|
|
|
|
// nevertheless run it in the tokio executor. Ideally run_in_task can be
|
|
|
|
// removed in the future.
|
2020-09-06 15:44:29 -04:00
|
|
|
use crate::runtime::tests::run_in_task;
|
2020-05-28 13:36:43 -04:00
|
|
|
|
2020-09-05 20:34:02 -04:00
|
|
|
#[derive(Default)]
|
2019-03-26 11:56:34 -04:00
|
|
|
struct MockLoader {
|
2019-06-05 16:35:38 -04:00
|
|
|
pub loads: Arc<Mutex<Vec<String>>>,
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl MockLoader {
|
2020-09-05 20:34:02 -04:00
|
|
|
fn new() -> Rc<Self> {
|
|
|
|
Default::default()
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-18 21:33:50 -04:00
|
|
|
fn mock_source_code(url: &str) -> Option<(&'static str, &'static str)> {
|
|
|
|
// (code, real_module_name)
|
2019-06-12 19:55:59 -04:00
|
|
|
let spec: Vec<&str> = url.split("file://").collect();
|
|
|
|
match spec[1] {
|
|
|
|
"/a.js" => Some((A_SRC, "file:///a.js")),
|
|
|
|
"/b.js" => Some((B_SRC, "file:///b.js")),
|
|
|
|
"/c.js" => Some((C_SRC, "file:///c.js")),
|
|
|
|
"/d.js" => Some((D_SRC, "file:///d.js")),
|
|
|
|
"/circular1.js" => Some((CIRCULAR1_SRC, "file:///circular1.js")),
|
|
|
|
"/circular2.js" => Some((CIRCULAR2_SRC, "file:///circular2.js")),
|
|
|
|
"/circular3.js" => Some((CIRCULAR3_SRC, "file:///circular3.js")),
|
|
|
|
"/redirect1.js" => Some((REDIRECT1_SRC, "file:///redirect1.js")),
|
|
|
|
// pretend redirect - real module name is different than one requested
|
|
|
|
"/redirect2.js" => Some((REDIRECT2_SRC, "file:///dir/redirect2.js")),
|
|
|
|
"/dir/redirect3.js" => Some((REDIRECT3_SRC, "file:///redirect3.js")),
|
|
|
|
"/slow.js" => Some((SLOW_SRC, "file:///slow.js")),
|
|
|
|
"/never_ready.js" => {
|
2019-08-07 12:55:39 -04:00
|
|
|
Some(("should never be Ready", "file:///never_ready.js"))
|
2019-06-12 19:55:59 -04:00
|
|
|
}
|
|
|
|
"/main.js" => Some((MAIN_SRC, "file:///main.js")),
|
|
|
|
"/bad_import.js" => Some((BAD_IMPORT_SRC, "file:///bad_import.js")),
|
2019-10-19 17:19:19 -04:00
|
|
|
// deliberately empty code.
|
|
|
|
"/main_with_code.js" => Some(("", "file:///main_with_code.js")),
|
2019-04-16 15:13:42 -04:00
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, PartialEq)]
|
|
|
|
enum MockError {
|
|
|
|
ResolveErr,
|
|
|
|
LoadErr,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for MockError {
|
|
|
|
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
unimplemented!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Error for MockError {
|
2019-06-18 09:28:56 -04:00
|
|
|
fn cause(&self) -> Option<&dyn Error> {
|
2019-04-16 15:13:42 -04:00
|
|
|
unimplemented!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct DelayedSourceCodeFuture {
|
|
|
|
url: String,
|
|
|
|
counter: u32,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Future for DelayedSourceCodeFuture {
|
2020-09-14 12:48:57 -04:00
|
|
|
type Output = Result<ModuleSource, AnyError>;
|
2019-04-16 15:13:42 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
|
|
|
let inner = self.get_mut();
|
|
|
|
inner.counter += 1;
|
|
|
|
if inner.url == "file:///never_ready.js" {
|
|
|
|
return Poll::Pending;
|
2019-08-07 12:55:39 -04:00
|
|
|
}
|
2019-11-16 19:17:47 -05:00
|
|
|
if inner.url == "file:///slow.js" && inner.counter < 2 {
|
2019-08-07 12:55:39 -04:00
|
|
|
// TODO(ry) Hopefully in the future we can remove current task
|
|
|
|
// notification. See comment above run_in_task.
|
2019-11-16 19:17:47 -05:00
|
|
|
cx.waker().wake_by_ref();
|
|
|
|
return Poll::Pending;
|
2019-04-16 15:13:42 -04:00
|
|
|
}
|
2019-11-16 19:17:47 -05:00
|
|
|
match mock_source_code(&inner.url) {
|
2020-03-02 13:12:49 -05:00
|
|
|
Some(src) => Poll::Ready(Ok(ModuleSource {
|
2019-04-18 21:33:50 -04:00
|
|
|
code: src.0.to_owned(),
|
2019-11-16 19:17:47 -05:00
|
|
|
module_url_specified: inner.url.clone(),
|
2019-08-07 12:55:39 -04:00
|
|
|
module_url_found: src.1.to_owned(),
|
2019-04-18 21:33:50 -04:00
|
|
|
})),
|
2019-11-16 19:17:47 -05:00
|
|
|
None => Poll::Ready(Err(MockError::LoadErr.into())),
|
2019-04-16 15:13:42 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-02 13:12:49 -05:00
|
|
|
impl ModuleLoader for MockLoader {
|
2019-06-09 09:08:20 -04:00
|
|
|
fn resolve(
|
|
|
|
&self,
|
2020-10-02 07:13:23 -04:00
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
2019-06-09 09:08:20 -04:00
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_is_root: bool,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
2019-06-12 19:55:59 -04:00
|
|
|
let referrer = if referrer == "." {
|
|
|
|
"file:///"
|
|
|
|
} else {
|
|
|
|
referrer
|
|
|
|
};
|
|
|
|
|
2019-04-18 21:33:50 -04:00
|
|
|
eprintln!(">> RESOLVING, S: {}, R: {}", specifier, referrer);
|
|
|
|
|
2021-02-17 13:47:18 -05:00
|
|
|
let output_specifier = match crate::resolve_import(specifier, referrer) {
|
|
|
|
Ok(specifier) => specifier,
|
|
|
|
Err(..) => return Err(MockError::ResolveErr.into()),
|
|
|
|
};
|
2019-06-12 19:55:59 -04:00
|
|
|
|
|
|
|
if mock_source_code(&output_specifier.to_string()).is_some() {
|
2019-04-18 21:33:50 -04:00
|
|
|
Ok(output_specifier)
|
2019-04-16 15:13:42 -04:00
|
|
|
} else {
|
2019-07-10 18:53:48 -04:00
|
|
|
Err(MockError::ResolveErr.into())
|
2019-04-16 15:13:42 -04:00
|
|
|
}
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
2019-06-12 19:55:59 -04:00
|
|
|
fn load(
|
|
|
|
&self,
|
2020-09-19 19:17:35 -04:00
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
2019-06-12 19:55:59 -04:00
|
|
|
module_specifier: &ModuleSpecifier,
|
2019-11-25 09:33:23 -05:00
|
|
|
_maybe_referrer: Option<ModuleSpecifier>,
|
2020-01-25 12:53:16 -05:00
|
|
|
_is_dyn_import: bool,
|
2020-03-02 13:12:49 -05:00
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
2021-07-06 23:48:01 -04:00
|
|
|
let mut loads = self.loads.lock();
|
2019-06-12 19:55:59 -04:00
|
|
|
loads.push(module_specifier.to_string());
|
|
|
|
let url = module_specifier.to_string();
|
2019-11-16 19:17:47 -05:00
|
|
|
DelayedSourceCodeFuture { url, counter: 0 }.boxed()
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const A_SRC: &str = r#"
|
2019-06-12 19:55:59 -04:00
|
|
|
import { b } from "/b.js";
|
|
|
|
import { c } from "/c.js";
|
2019-03-26 11:56:34 -04:00
|
|
|
if (b() != 'b') throw Error();
|
|
|
|
if (c() != 'c') throw Error();
|
|
|
|
if (!import.meta.main) throw Error();
|
2019-06-12 19:55:59 -04:00
|
|
|
if (import.meta.url != 'file:///a.js') throw Error();
|
2019-03-26 11:56:34 -04:00
|
|
|
"#;
|
|
|
|
|
|
|
|
const B_SRC: &str = r#"
|
2019-06-12 19:55:59 -04:00
|
|
|
import { c } from "/c.js";
|
2019-03-26 11:56:34 -04:00
|
|
|
if (c() != 'c') throw Error();
|
|
|
|
export function b() { return 'b'; }
|
|
|
|
if (import.meta.main) throw Error();
|
2019-06-12 19:55:59 -04:00
|
|
|
if (import.meta.url != 'file:///b.js') throw Error();
|
2019-03-26 11:56:34 -04:00
|
|
|
"#;
|
|
|
|
|
|
|
|
const C_SRC: &str = r#"
|
2019-06-12 19:55:59 -04:00
|
|
|
import { d } from "/d.js";
|
2019-03-26 11:56:34 -04:00
|
|
|
export function c() { return 'c'; }
|
|
|
|
if (d() != 'd') throw Error();
|
|
|
|
if (import.meta.main) throw Error();
|
2019-06-12 19:55:59 -04:00
|
|
|
if (import.meta.url != 'file:///c.js') throw Error();
|
2019-03-26 11:56:34 -04:00
|
|
|
"#;
|
|
|
|
|
|
|
|
const D_SRC: &str = r#"
|
|
|
|
export function d() { return 'd'; }
|
|
|
|
if (import.meta.main) throw Error();
|
2019-06-12 19:55:59 -04:00
|
|
|
if (import.meta.url != 'file:///d.js') throw Error();
|
2019-03-26 11:56:34 -04:00
|
|
|
"#;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_recursive_load() {
|
2020-01-08 09:06:04 -05:00
|
|
|
let loader = MockLoader::new();
|
|
|
|
let loads = loader.loads.clone();
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2021-02-17 13:47:18 -05:00
|
|
|
let spec = crate::resolve_url("file:///a.js").unwrap();
|
2021-09-17 21:44:53 -04:00
|
|
|
let a_id_fut = runtime.load_main_module(&spec, None);
|
2020-01-08 09:06:04 -05:00
|
|
|
let a_id = futures::executor::block_on(a_id_fut).expect("Failed to load");
|
2020-12-20 09:14:19 -05:00
|
|
|
|
2021-07-30 07:36:43 -04:00
|
|
|
let _ = runtime.mod_evaluate(a_id);
|
2021-05-26 15:07:12 -04:00
|
|
|
futures::executor::block_on(runtime.run_event_loop(false)).unwrap();
|
2021-07-06 23:48:01 -04:00
|
|
|
let l = loads.lock();
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(
|
|
|
|
l.to_vec(),
|
|
|
|
vec![
|
|
|
|
"file:///a.js",
|
|
|
|
"file:///b.js",
|
|
|
|
"file:///c.js",
|
|
|
|
"file:///d.js"
|
|
|
|
]
|
|
|
|
);
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = JsRuntime::module_map(runtime.v8_isolate());
|
|
|
|
let modules = module_map_rc.borrow();
|
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(modules.get_id("file:///a.js"), Some(a_id));
|
|
|
|
let b_id = modules.get_id("file:///b.js").unwrap();
|
|
|
|
let c_id = modules.get_id("file:///c.js").unwrap();
|
|
|
|
let d_id = modules.get_id("file:///d.js").unwrap();
|
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(a_id),
|
2020-01-25 12:53:16 -05:00
|
|
|
Some(&vec![
|
2021-02-17 13:47:18 -05:00
|
|
|
crate::resolve_url("file:///b.js").unwrap(),
|
|
|
|
crate::resolve_url("file:///c.js").unwrap()
|
2020-01-25 12:53:16 -05:00
|
|
|
])
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(b_id),
|
2021-02-17 13:47:18 -05:00
|
|
|
Some(&vec![crate::resolve_url("file:///c.js").unwrap()])
|
2020-01-25 12:53:16 -05:00
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(c_id),
|
2021-02-17 13:47:18 -05:00
|
|
|
Some(&vec![crate::resolve_url("file:///d.js").unwrap()])
|
2020-01-08 09:06:04 -05:00
|
|
|
);
|
|
|
|
assert_eq!(modules.get_children(d_id), Some(&vec![]));
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const CIRCULAR1_SRC: &str = r#"
|
2019-06-12 19:55:59 -04:00
|
|
|
import "/circular2.js";
|
2019-03-26 11:56:34 -04:00
|
|
|
Deno.core.print("circular1");
|
|
|
|
"#;
|
|
|
|
|
|
|
|
const CIRCULAR2_SRC: &str = r#"
|
2019-06-12 19:55:59 -04:00
|
|
|
import "/circular3.js";
|
2019-03-26 11:56:34 -04:00
|
|
|
Deno.core.print("circular2");
|
|
|
|
"#;
|
|
|
|
|
2019-04-16 15:13:42 -04:00
|
|
|
const CIRCULAR3_SRC: &str = r#"
|
2019-06-12 19:55:59 -04:00
|
|
|
import "/circular1.js";
|
|
|
|
import "/circular2.js";
|
2019-04-16 15:13:42 -04:00
|
|
|
Deno.core.print("circular3");
|
|
|
|
"#;
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
#[test]
|
|
|
|
fn test_mods() {
|
|
|
|
#[derive(Default)]
|
|
|
|
struct ModsLoader {
|
|
|
|
pub count: Arc<AtomicUsize>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ModuleLoader for ModsLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_is_main: bool,
|
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
|
|
|
self.count.fetch_add(1, Ordering::Relaxed);
|
|
|
|
assert_eq!(specifier, "./b.js");
|
|
|
|
assert_eq!(referrer, "file:///a.js");
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<ModuleSpecifier>,
|
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let loader = Rc::new(ModsLoader::default());
|
|
|
|
|
|
|
|
let resolve_count = loader.count.clone();
|
|
|
|
let dispatch_count = Arc::new(AtomicUsize::new(0));
|
|
|
|
let dispatch_count_ = dispatch_count.clone();
|
|
|
|
|
|
|
|
let dispatcher = move |state, payload: OpPayload| -> Op {
|
|
|
|
dispatch_count_.fetch_add(1, Ordering::Relaxed);
|
|
|
|
let (control, _): (u8, ()) = payload.deserialize().unwrap();
|
|
|
|
assert_eq!(control, 42);
|
|
|
|
let resp = (0, serialize_op_result(Ok(43), state));
|
|
|
|
Op::Async(Box::pin(futures::future::ready(resp)))
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
runtime.register_op("op_test", dispatcher);
|
|
|
|
runtime.sync_ops_cache();
|
|
|
|
|
|
|
|
runtime
|
2021-06-21 19:45:41 -04:00
|
|
|
.execute_script(
|
2021-05-19 14:53:43 -04:00
|
|
|
"setup.js",
|
|
|
|
r#"
|
|
|
|
function assert(cond) {
|
|
|
|
if (!cond) {
|
|
|
|
throw Error("assert");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 0);
|
|
|
|
|
|
|
|
let module_map_rc = JsRuntime::module_map(runtime.v8_isolate());
|
|
|
|
|
|
|
|
let (mod_a, mod_b) = {
|
|
|
|
let scope = &mut runtime.handle_scope();
|
|
|
|
let mut module_map = module_map_rc.borrow_mut();
|
|
|
|
let specifier_a = "file:///a.js".to_string();
|
|
|
|
let mod_a = module_map
|
|
|
|
.new_module(
|
|
|
|
scope,
|
|
|
|
true,
|
|
|
|
&specifier_a,
|
|
|
|
r#"
|
|
|
|
import { b } from './b.js'
|
|
|
|
if (b() != 'b') throw Error();
|
|
|
|
let control = 42;
|
|
|
|
Deno.core.opAsync("op_test", control);
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 0);
|
|
|
|
let imports = module_map.get_children(mod_a);
|
|
|
|
assert_eq!(
|
|
|
|
imports,
|
|
|
|
Some(&vec![crate::resolve_url("file:///b.js").unwrap()])
|
|
|
|
);
|
|
|
|
|
|
|
|
let mod_b = module_map
|
|
|
|
.new_module(
|
|
|
|
scope,
|
|
|
|
false,
|
|
|
|
"file:///b.js",
|
|
|
|
"export function b() { return 'b' }",
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let imports = module_map.get_children(mod_b).unwrap();
|
|
|
|
assert_eq!(imports.len(), 0);
|
|
|
|
(mod_a, mod_b)
|
|
|
|
};
|
|
|
|
|
|
|
|
runtime.instantiate_module(mod_b).unwrap();
|
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 0);
|
|
|
|
assert_eq!(resolve_count.load(Ordering::SeqCst), 1);
|
|
|
|
|
|
|
|
runtime.instantiate_module(mod_a).unwrap();
|
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 0);
|
|
|
|
|
2021-07-30 07:36:43 -04:00
|
|
|
let _ = runtime.mod_evaluate(mod_a);
|
2021-05-19 14:53:43 -04:00
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn dyn_import_err() {
|
|
|
|
#[derive(Clone, Default)]
|
|
|
|
struct DynImportErrLoader {
|
|
|
|
pub count: Arc<AtomicUsize>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ModuleLoader for DynImportErrLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_is_main: bool,
|
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
|
|
|
self.count.fetch_add(1, Ordering::Relaxed);
|
|
|
|
assert_eq!(specifier, "/foo.js");
|
|
|
|
assert_eq!(referrer, "file:///dyn_import2.js");
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<ModuleSpecifier>,
|
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
async { Err(io::Error::from(io::ErrorKind::NotFound).into()) }.boxed()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Test an erroneous dynamic import where the specified module isn't found.
|
|
|
|
run_in_task(|cx| {
|
|
|
|
let loader = Rc::new(DynImportErrLoader::default());
|
|
|
|
let count = loader.count.clone();
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2021-06-21 19:45:41 -04:00
|
|
|
.execute_script(
|
2021-05-19 14:53:43 -04:00
|
|
|
"file:///dyn_import2.js",
|
|
|
|
r#"
|
|
|
|
(async () => {
|
|
|
|
await import("/foo.js");
|
|
|
|
})();
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
// We should get an error here.
|
2021-05-26 15:07:12 -04:00
|
|
|
let result = runtime.poll_event_loop(cx, false);
|
2021-05-19 14:53:43 -04:00
|
|
|
if let Poll::Ready(Ok(_)) = result {
|
|
|
|
unreachable!();
|
|
|
|
}
|
2021-06-28 21:03:02 -04:00
|
|
|
assert_eq!(count.load(Ordering::Relaxed), 4);
|
2021-05-19 14:53:43 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Default)]
|
|
|
|
struct DynImportOkLoader {
|
|
|
|
pub prepare_load_count: Arc<AtomicUsize>,
|
|
|
|
pub resolve_count: Arc<AtomicUsize>,
|
|
|
|
pub load_count: Arc<AtomicUsize>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ModuleLoader for DynImportOkLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_is_main: bool,
|
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
|
|
|
let c = self.resolve_count.fetch_add(1, Ordering::Relaxed);
|
2021-06-28 21:03:02 -04:00
|
|
|
assert!(c < 7);
|
2021-05-19 14:53:43 -04:00
|
|
|
assert_eq!(specifier, "./b.js");
|
|
|
|
assert_eq!(referrer, "file:///dyn_import3.js");
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<ModuleSpecifier>,
|
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
self.load_count.fetch_add(1, Ordering::Relaxed);
|
|
|
|
let info = ModuleSource {
|
|
|
|
module_url_specified: specifier.to_string(),
|
|
|
|
module_url_found: specifier.to_string(),
|
|
|
|
code: "export function b() { return 'b' }".to_owned(),
|
|
|
|
};
|
|
|
|
async move { Ok(info) }.boxed()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn prepare_load(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
_load_id: ModuleLoadId,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<String>,
|
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<dyn Future<Output = Result<(), AnyError>>>> {
|
|
|
|
self.prepare_load_count.fetch_add(1, Ordering::Relaxed);
|
|
|
|
async { Ok(()) }.boxed_local()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn dyn_import_ok() {
|
|
|
|
run_in_task(|cx| {
|
|
|
|
let loader = Rc::new(DynImportOkLoader::default());
|
|
|
|
let prepare_load_count = loader.prepare_load_count.clone();
|
|
|
|
let resolve_count = loader.resolve_count.clone();
|
|
|
|
let load_count = loader.load_count.clone();
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
// Dynamically import mod_b
|
|
|
|
runtime
|
2021-06-21 19:45:41 -04:00
|
|
|
.execute_script(
|
2021-05-19 14:53:43 -04:00
|
|
|
"file:///dyn_import3.js",
|
|
|
|
r#"
|
|
|
|
(async () => {
|
|
|
|
let mod = await import("./b.js");
|
|
|
|
if (mod.b() !== 'b') {
|
|
|
|
throw Error("bad1");
|
|
|
|
}
|
|
|
|
// And again!
|
|
|
|
mod = await import("./b.js");
|
|
|
|
if (mod.b() !== 'b') {
|
|
|
|
throw Error("bad2");
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
// First poll runs `prepare_load` hook.
|
2021-05-26 15:07:12 -04:00
|
|
|
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
|
2021-05-19 14:53:43 -04:00
|
|
|
assert_eq!(prepare_load_count.load(Ordering::Relaxed), 1);
|
|
|
|
|
|
|
|
// Second poll actually loads modules into the isolate.
|
2021-05-26 15:07:12 -04:00
|
|
|
assert!(matches!(
|
|
|
|
runtime.poll_event_loop(cx, false),
|
|
|
|
Poll::Ready(Ok(_))
|
|
|
|
));
|
2021-06-28 21:03:02 -04:00
|
|
|
assert_eq!(resolve_count.load(Ordering::Relaxed), 7);
|
|
|
|
assert_eq!(load_count.load(Ordering::Relaxed), 1);
|
2021-05-26 15:07:12 -04:00
|
|
|
assert!(matches!(
|
|
|
|
runtime.poll_event_loop(cx, false),
|
|
|
|
Poll::Ready(Ok(_))
|
|
|
|
));
|
2021-06-28 21:03:02 -04:00
|
|
|
assert_eq!(resolve_count.load(Ordering::Relaxed), 7);
|
|
|
|
assert_eq!(load_count.load(Ordering::Relaxed), 1);
|
2021-05-19 14:53:43 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn dyn_import_borrow_mut_error() {
|
|
|
|
// https://github.com/denoland/deno/issues/6054
|
|
|
|
run_in_task(|cx| {
|
|
|
|
let loader = Rc::new(DynImportOkLoader::default());
|
|
|
|
let prepare_load_count = loader.prepare_load_count.clone();
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
runtime.sync_ops_cache();
|
|
|
|
runtime
|
2021-06-21 19:45:41 -04:00
|
|
|
.execute_script(
|
2021-05-19 14:53:43 -04:00
|
|
|
"file:///dyn_import3.js",
|
|
|
|
r#"
|
|
|
|
(async () => {
|
|
|
|
let mod = await import("./b.js");
|
|
|
|
if (mod.b() !== 'b') {
|
|
|
|
throw Error("bad");
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
// First poll runs `prepare_load` hook.
|
2021-05-26 15:07:12 -04:00
|
|
|
let _ = runtime.poll_event_loop(cx, false);
|
2021-05-19 14:53:43 -04:00
|
|
|
assert_eq!(prepare_load_count.load(Ordering::Relaxed), 1);
|
|
|
|
// Second poll triggers error
|
2021-05-26 15:07:12 -04:00
|
|
|
let _ = runtime.poll_event_loop(cx, false);
|
2021-05-19 14:53:43 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-06-28 21:03:02 -04:00
|
|
|
// Regression test for https://github.com/denoland/deno/issues/3736.
|
|
|
|
#[test]
|
|
|
|
fn dyn_concurrent_circular_import() {
|
|
|
|
#[derive(Clone, Default)]
|
|
|
|
struct DynImportCircularLoader {
|
|
|
|
pub resolve_count: Arc<AtomicUsize>,
|
|
|
|
pub load_count: Arc<AtomicUsize>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ModuleLoader for DynImportCircularLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_is_main: bool,
|
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
|
|
|
self.resolve_count.fetch_add(1, Ordering::Relaxed);
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
maybe_referrer: Option<ModuleSpecifier>,
|
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
self.load_count.fetch_add(1, Ordering::Relaxed);
|
|
|
|
let filename = PathBuf::from(specifier.to_string())
|
|
|
|
.file_name()
|
|
|
|
.unwrap()
|
|
|
|
.to_string_lossy()
|
|
|
|
.to_string();
|
|
|
|
eprintln!("{} from {:?}", filename.as_str(), maybe_referrer);
|
|
|
|
let code = match filename.as_str() {
|
|
|
|
"a.js" => "import './b.js';",
|
|
|
|
"b.js" => "import './c.js';\nimport './a.js';",
|
|
|
|
"c.js" => "import './d.js';",
|
|
|
|
"d.js" => "// pass",
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
let info = ModuleSource {
|
|
|
|
module_url_specified: specifier.to_string(),
|
|
|
|
module_url_found: specifier.to_string(),
|
|
|
|
code: code.to_owned(),
|
|
|
|
};
|
|
|
|
async move { Ok(info) }.boxed()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let loader = Rc::new(DynImportCircularLoader::default());
|
|
|
|
let resolve_count = loader.resolve_count.clone();
|
|
|
|
let load_count = loader.load_count.clone();
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
|
|
|
.execute_script(
|
|
|
|
"file:///entry.js",
|
|
|
|
"import('./b.js');\nimport('./a.js');",
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let result = futures::executor::block_on(runtime.run_event_loop(false));
|
|
|
|
eprintln!("result {:?}", result);
|
|
|
|
assert!(result.is_ok());
|
|
|
|
eprintln!("{}", resolve_count.load(Ordering::Relaxed));
|
|
|
|
eprintln!("{}", load_count.load(Ordering::Relaxed));
|
|
|
|
}
|
|
|
|
|
2019-03-26 11:56:34 -04:00
|
|
|
#[test]
|
|
|
|
fn test_circular_load() {
|
2020-01-08 09:06:04 -05:00
|
|
|
let loader = MockLoader::new();
|
|
|
|
let loads = loader.loads.clone();
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
let fut = async move {
|
2021-02-17 13:47:18 -05:00
|
|
|
let spec = crate::resolve_url("file:///circular1.js").unwrap();
|
2021-09-17 21:44:53 -04:00
|
|
|
let result = runtime.load_main_module(&spec, None).await;
|
2020-01-08 09:06:04 -05:00
|
|
|
assert!(result.is_ok());
|
|
|
|
let circular1_id = result.unwrap();
|
2021-07-30 07:36:43 -04:00
|
|
|
let _ = runtime.mod_evaluate(circular1_id);
|
2021-05-26 15:07:12 -04:00
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2021-07-06 23:48:01 -04:00
|
|
|
let l = loads.lock();
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(
|
|
|
|
l.to_vec(),
|
|
|
|
vec![
|
|
|
|
"file:///circular1.js",
|
|
|
|
"file:///circular2.js",
|
|
|
|
"file:///circular3.js"
|
|
|
|
]
|
|
|
|
);
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = JsRuntime::module_map(runtime.v8_isolate());
|
|
|
|
let modules = module_map_rc.borrow();
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(modules.get_id("file:///circular1.js"), Some(circular1_id));
|
|
|
|
let circular2_id = modules.get_id("file:///circular2.js").unwrap();
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(circular1_id),
|
2021-02-17 13:47:18 -05:00
|
|
|
Some(&vec![crate::resolve_url("file:///circular2.js").unwrap()])
|
2020-01-08 09:06:04 -05:00
|
|
|
);
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(circular2_id),
|
2021-02-17 13:47:18 -05:00
|
|
|
Some(&vec![crate::resolve_url("file:///circular3.js").unwrap()])
|
2020-01-08 09:06:04 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
assert!(modules.get_id("file:///circular3.js").is_some());
|
|
|
|
let circular3_id = modules.get_id("file:///circular3.js").unwrap();
|
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(circular3_id),
|
|
|
|
Some(&vec![
|
2021-02-17 13:47:18 -05:00
|
|
|
crate::resolve_url("file:///circular1.js").unwrap(),
|
|
|
|
crate::resolve_url("file:///circular2.js").unwrap()
|
2020-01-08 09:06:04 -05:00
|
|
|
])
|
|
|
|
);
|
|
|
|
}
|
2020-02-03 18:08:44 -05:00
|
|
|
.boxed_local();
|
2020-01-08 09:06:04 -05:00
|
|
|
|
|
|
|
futures::executor::block_on(fut);
|
2019-04-18 21:33:50 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const REDIRECT1_SRC: &str = r#"
|
|
|
|
import "./redirect2.js";
|
|
|
|
Deno.core.print("redirect1");
|
|
|
|
"#;
|
|
|
|
|
|
|
|
const REDIRECT2_SRC: &str = r#"
|
|
|
|
import "./redirect3.js";
|
|
|
|
Deno.core.print("redirect2");
|
|
|
|
"#;
|
|
|
|
|
|
|
|
const REDIRECT3_SRC: &str = r#"
|
|
|
|
Deno.core.print("redirect3");
|
|
|
|
"#;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_redirect_load() {
|
2020-01-08 09:06:04 -05:00
|
|
|
let loader = MockLoader::new();
|
|
|
|
let loads = loader.loads.clone();
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2020-01-08 09:06:04 -05:00
|
|
|
|
|
|
|
let fut = async move {
|
2021-02-17 13:47:18 -05:00
|
|
|
let spec = crate::resolve_url("file:///redirect1.js").unwrap();
|
2021-09-17 21:44:53 -04:00
|
|
|
let result = runtime.load_main_module(&spec, None).await;
|
2019-08-07 12:55:39 -04:00
|
|
|
println!(">> result {:?}", result);
|
2020-01-08 09:06:04 -05:00
|
|
|
assert!(result.is_ok());
|
|
|
|
let redirect1_id = result.unwrap();
|
2021-07-30 07:36:43 -04:00
|
|
|
let _ = runtime.mod_evaluate(redirect1_id);
|
2021-05-26 15:07:12 -04:00
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
2021-07-06 23:48:01 -04:00
|
|
|
let l = loads.lock();
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(
|
|
|
|
l.to_vec(),
|
|
|
|
vec![
|
|
|
|
"file:///redirect1.js",
|
|
|
|
"file:///redirect2.js",
|
|
|
|
"file:///dir/redirect3.js"
|
|
|
|
]
|
|
|
|
);
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = JsRuntime::module_map(runtime.v8_isolate());
|
|
|
|
let modules = module_map_rc.borrow();
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(modules.get_id("file:///redirect1.js"), Some(redirect1_id));
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
let redirect2_id = modules.get_id("file:///dir/redirect2.js").unwrap();
|
|
|
|
assert!(modules.is_alias("file:///redirect2.js"));
|
|
|
|
assert!(!modules.is_alias("file:///dir/redirect2.js"));
|
|
|
|
assert_eq!(modules.get_id("file:///redirect2.js"), Some(redirect2_id));
|
2019-08-07 12:55:39 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
let redirect3_id = modules.get_id("file:///redirect3.js").unwrap();
|
|
|
|
assert!(modules.is_alias("file:///dir/redirect3.js"));
|
|
|
|
assert!(!modules.is_alias("file:///redirect3.js"));
|
|
|
|
assert_eq!(
|
|
|
|
modules.get_id("file:///dir/redirect3.js"),
|
|
|
|
Some(redirect3_id)
|
|
|
|
);
|
|
|
|
}
|
2020-02-03 18:08:44 -05:00
|
|
|
.boxed_local();
|
2020-01-08 09:06:04 -05:00
|
|
|
|
|
|
|
futures::executor::block_on(fut);
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|
2019-04-16 15:13:42 -04:00
|
|
|
|
|
|
|
// main.js
|
|
|
|
const MAIN_SRC: &str = r#"
|
|
|
|
// never_ready.js never loads.
|
2019-06-12 19:55:59 -04:00
|
|
|
import "/never_ready.js";
|
2019-04-16 15:13:42 -04:00
|
|
|
// slow.js resolves after one tick.
|
2019-06-12 19:55:59 -04:00
|
|
|
import "/slow.js";
|
2019-04-16 15:13:42 -04:00
|
|
|
"#;
|
|
|
|
|
|
|
|
// slow.js
|
|
|
|
const SLOW_SRC: &str = r#"
|
|
|
|
// Circular import of never_ready.js
|
2020-03-02 13:12:49 -05:00
|
|
|
// Does this trigger two ModuleLoader calls? It shouldn't.
|
2019-06-12 19:55:59 -04:00
|
|
|
import "/never_ready.js";
|
|
|
|
import "/a.js";
|
2019-04-16 15:13:42 -04:00
|
|
|
"#;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn slow_never_ready_modules() {
|
2019-11-16 19:17:47 -05:00
|
|
|
run_in_task(|mut cx| {
|
2019-08-07 12:55:39 -04:00
|
|
|
let loader = MockLoader::new();
|
|
|
|
let loads = loader.loads.clone();
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2021-02-17 13:47:18 -05:00
|
|
|
let spec = crate::resolve_url("file:///main.js").unwrap();
|
2021-09-17 21:44:53 -04:00
|
|
|
let mut recursive_load =
|
|
|
|
runtime.load_main_module(&spec, None).boxed_local();
|
2019-04-16 15:13:42 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
let result = recursive_load.poll_unpin(&mut cx);
|
|
|
|
assert!(result.is_pending());
|
2019-08-07 12:55:39 -04:00
|
|
|
|
|
|
|
// TODO(ry) Arguably the first time we poll only the following modules
|
|
|
|
// should be loaded:
|
|
|
|
// "file:///main.js",
|
|
|
|
// "file:///never_ready.js",
|
|
|
|
// "file:///slow.js"
|
|
|
|
// But due to current task notification in DelayedSourceCodeFuture they
|
|
|
|
// all get loaded in a single poll. Also see the comment above
|
|
|
|
// run_in_task.
|
|
|
|
|
|
|
|
for _ in 0..10 {
|
2019-11-16 19:17:47 -05:00
|
|
|
let result = recursive_load.poll_unpin(&mut cx);
|
|
|
|
assert!(result.is_pending());
|
2021-07-06 23:48:01 -04:00
|
|
|
let l = loads.lock();
|
2019-08-07 12:55:39 -04:00
|
|
|
assert_eq!(
|
|
|
|
l.to_vec(),
|
|
|
|
vec![
|
|
|
|
"file:///main.js",
|
|
|
|
"file:///never_ready.js",
|
|
|
|
"file:///slow.js",
|
|
|
|
"file:///a.js",
|
|
|
|
"file:///b.js",
|
|
|
|
"file:///c.js",
|
|
|
|
"file:///d.js"
|
|
|
|
]
|
|
|
|
);
|
|
|
|
}
|
|
|
|
})
|
2019-04-16 15:13:42 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// bad_import.js
|
|
|
|
const BAD_IMPORT_SRC: &str = r#"
|
|
|
|
import "foo";
|
|
|
|
"#;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn loader_disappears_after_error() {
|
2019-11-16 19:17:47 -05:00
|
|
|
run_in_task(|mut cx| {
|
2019-08-07 12:55:39 -04:00
|
|
|
let loader = MockLoader::new();
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2021-02-17 13:47:18 -05:00
|
|
|
let spec = crate::resolve_url("file:///bad_import.js").unwrap();
|
2021-09-17 21:44:53 -04:00
|
|
|
let mut load_fut = runtime.load_main_module(&spec, None).boxed_local();
|
2019-11-16 19:17:47 -05:00
|
|
|
let result = load_fut.poll_unpin(&mut cx);
|
|
|
|
if let Poll::Ready(Err(err)) = result {
|
|
|
|
assert_eq!(
|
|
|
|
err.downcast_ref::<MockError>().unwrap(),
|
|
|
|
&MockError::ResolveErr
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
unreachable!();
|
|
|
|
}
|
2019-08-07 12:55:39 -04:00
|
|
|
})
|
2019-04-16 15:13:42 -04:00
|
|
|
}
|
2019-04-19 11:18:46 -04:00
|
|
|
|
2019-10-19 17:19:19 -04:00
|
|
|
const MAIN_WITH_CODE_SRC: &str = r#"
|
|
|
|
import { b } from "/b.js";
|
|
|
|
import { c } from "/c.js";
|
|
|
|
if (b() != 'b') throw Error();
|
|
|
|
if (c() != 'c') throw Error();
|
|
|
|
if (!import.meta.main) throw Error();
|
|
|
|
if (import.meta.url != 'file:///main_with_code.js') throw Error();
|
|
|
|
"#;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn recursive_load_main_with_code() {
|
2020-01-08 09:06:04 -05:00
|
|
|
let loader = MockLoader::new();
|
|
|
|
let loads = loader.loads.clone();
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2020-01-08 09:06:04 -05:00
|
|
|
// In default resolution code should be empty.
|
|
|
|
// Instead we explicitly pass in our own code.
|
|
|
|
// The behavior should be very similar to /a.js.
|
2021-02-17 13:47:18 -05:00
|
|
|
let spec = crate::resolve_url("file:///main_with_code.js").unwrap();
|
2020-09-06 15:44:29 -04:00
|
|
|
let main_id_fut = runtime
|
2021-09-17 21:44:53 -04:00
|
|
|
.load_main_module(&spec, Some(MAIN_WITH_CODE_SRC.to_owned()))
|
2020-02-03 18:08:44 -05:00
|
|
|
.boxed_local();
|
2020-01-08 09:06:04 -05:00
|
|
|
let main_id =
|
|
|
|
futures::executor::block_on(main_id_fut).expect("Failed to load");
|
2020-12-20 09:14:19 -05:00
|
|
|
|
2021-07-30 07:36:43 -04:00
|
|
|
let _ = runtime.mod_evaluate(main_id);
|
2021-05-26 15:07:12 -04:00
|
|
|
futures::executor::block_on(runtime.run_event_loop(false)).unwrap();
|
2020-01-08 09:06:04 -05:00
|
|
|
|
2021-07-06 23:48:01 -04:00
|
|
|
let l = loads.lock();
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(
|
|
|
|
l.to_vec(),
|
|
|
|
vec!["file:///b.js", "file:///c.js", "file:///d.js"]
|
|
|
|
);
|
2019-10-19 17:19:19 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = JsRuntime::module_map(runtime.v8_isolate());
|
|
|
|
let modules = module_map_rc.borrow();
|
2019-10-19 17:19:19 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(modules.get_id("file:///main_with_code.js"), Some(main_id));
|
|
|
|
let b_id = modules.get_id("file:///b.js").unwrap();
|
|
|
|
let c_id = modules.get_id("file:///c.js").unwrap();
|
|
|
|
let d_id = modules.get_id("file:///d.js").unwrap();
|
2019-10-19 17:19:19 -04:00
|
|
|
|
2020-01-08 09:06:04 -05:00
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(main_id),
|
2020-01-25 12:53:16 -05:00
|
|
|
Some(&vec![
|
2021-02-17 13:47:18 -05:00
|
|
|
crate::resolve_url("file:///b.js").unwrap(),
|
|
|
|
crate::resolve_url("file:///c.js").unwrap()
|
2020-01-25 12:53:16 -05:00
|
|
|
])
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(b_id),
|
2021-02-17 13:47:18 -05:00
|
|
|
Some(&vec![crate::resolve_url("file:///c.js").unwrap()])
|
2020-01-25 12:53:16 -05:00
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
modules.get_children(c_id),
|
2021-02-17 13:47:18 -05:00
|
|
|
Some(&vec![crate::resolve_url("file:///d.js").unwrap()])
|
2020-01-08 09:06:04 -05:00
|
|
|
);
|
|
|
|
assert_eq!(modules.get_children(d_id), Some(&vec![]));
|
2019-10-19 17:19:19 -04:00
|
|
|
}
|
2021-09-17 21:44:53 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn main_and_side_module() {
|
|
|
|
struct ModsLoader {}
|
|
|
|
|
|
|
|
let main_specifier = crate::resolve_url("file:///main_module.js").unwrap();
|
|
|
|
let side_specifier = crate::resolve_url("file:///side_module.js").unwrap();
|
|
|
|
|
|
|
|
impl ModuleLoader for ModsLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_is_main: bool,
|
|
|
|
) -> Result<ModuleSpecifier, AnyError> {
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_op_state: Rc<RefCell<OpState>>,
|
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
_maybe_referrer: Option<ModuleSpecifier>,
|
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
let module_source = match module_specifier.as_str() {
|
|
|
|
"file:///main_module.js" => Ok(ModuleSource {
|
|
|
|
module_url_specified: "file:///main_module.js".to_string(),
|
|
|
|
module_url_found: "file:///main_module.js".to_string(),
|
|
|
|
code: "if (!import.meta.main) throw Error();".to_owned(),
|
|
|
|
}),
|
|
|
|
"file:///side_module.js" => Ok(ModuleSource {
|
|
|
|
module_url_specified: "file:///side_module.js".to_string(),
|
|
|
|
module_url_found: "file:///side_module.js".to_string(),
|
|
|
|
code: "if (import.meta.main) throw Error();".to_owned(),
|
|
|
|
}),
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
async move { module_source }.boxed()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let loader = Rc::new(ModsLoader {});
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
let main_id_fut = runtime
|
|
|
|
.load_main_module(&main_specifier, None)
|
|
|
|
.boxed_local();
|
|
|
|
let main_id =
|
|
|
|
futures::executor::block_on(main_id_fut).expect("Failed to load");
|
|
|
|
|
|
|
|
let _ = runtime.mod_evaluate(main_id);
|
|
|
|
futures::executor::block_on(runtime.run_event_loop(false)).unwrap();
|
|
|
|
|
|
|
|
// Try to add another main module - it should error.
|
|
|
|
let side_id_fut = runtime
|
|
|
|
.load_main_module(&side_specifier, None)
|
|
|
|
.boxed_local();
|
|
|
|
futures::executor::block_on(side_id_fut)
|
|
|
|
.expect_err("Should have failed to load second main module");
|
|
|
|
|
|
|
|
// And now try to load it as a side module
|
|
|
|
let side_id_fut = runtime
|
|
|
|
.load_side_module(&side_specifier, None)
|
|
|
|
.boxed_local();
|
|
|
|
let side_id =
|
|
|
|
futures::executor::block_on(side_id_fut).expect("Failed to load");
|
|
|
|
|
|
|
|
let _ = runtime.mod_evaluate(side_id);
|
|
|
|
futures::executor::block_on(runtime.run_event_loop(false)).unwrap();
|
|
|
|
}
|
2019-03-26 11:56:34 -04:00
|
|
|
}
|