From 1117d2db3965fc44f174be3fd029293b7e2b952e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 24 Nov 2021 16:55:10 +0100 Subject: compat: support compat mode in REPL (#12882) This commit introduces "ProcState::maybe_resolver" field, which stores a single instance of resolver for the whole lifetime of the process, instead of creating these resolvers for each creation of module graph. As a result, this resolver can be used in fallback case where graph is not constructed (REPL, loading modules using "require") unifying resolution logic. --- cli/compat/errors.rs | 2 +- cli/compat/esm_resolver.rs | 10 +++------- cli/compat/mod.rs | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 8 deletions(-) (limited to 'cli/compat') diff --git a/cli/compat/errors.rs b/cli/compat/errors.rs index 3a44b2c88..e9cc31a0d 100644 --- a/cli/compat/errors.rs +++ b/cli/compat/errors.rs @@ -49,7 +49,7 @@ pub(crate) fn err_module_not_found( typ: &str, ) -> AnyError { generic_error(format!( - "[ERR_MODULE_NOT_FOUND] Cannot find {} '{}' imported from {}", + "[ERR_MODULE_NOT_FOUND] Cannot find {} \"{}\" imported from \"{}\"", typ, path, base )) } diff --git a/cli/compat/esm_resolver.rs b/cli/compat/esm_resolver.rs index 980e44b32..5787c9e48 100644 --- a/cli/compat/esm_resolver.rs +++ b/cli/compat/esm_resolver.rs @@ -24,10 +24,6 @@ impl NodeEsmResolver { maybe_import_map_resolver, } } - - pub fn as_resolver(&self) -> &dyn Resolver { - self - } } impl Resolver for NodeEsmResolver { @@ -232,12 +228,12 @@ fn finalize_resolution( }; if is_dir { return Err(errors::err_unsupported_dir_import( - &path.display().to_string(), - &to_file_path_string(base), + resolved.as_str(), + base.as_str(), )); } else if !is_file { return Err(errors::err_module_not_found( - &path.display().to_string(), + resolved.as_str(), base.as_str(), "module", )); diff --git a/cli/compat/mod.rs b/cli/compat/mod.rs index 01d84d65a..41443968f 100644 --- a/cli/compat/mod.rs +++ b/cli/compat/mod.rs @@ -104,6 +104,24 @@ pub(crate) fn load_cjs_module( Ok(()) } +pub(crate) fn add_global_require( + js_runtime: &mut JsRuntime, + main_module: &str, +) -> Result<(), AnyError> { + let source_code = &format!( + r#"(async function setupGlobalRequire(main) {{ + const Module = await import("{}"); + const require = Module.createRequire(main); + globalThis.require = require; + }})('{}');"#, + MODULE_URL_STR.as_str(), + escape_for_single_quote_string(main_module), + ); + + js_runtime.execute_script(&located_script_name!(), source_code)?; + Ok(()) +} + fn escape_for_single_quote_string(text: &str) -> String { text.replace(r"\", r"\\").replace("'", r"\'") } -- cgit v1.2.3