From 1f54d877895ea25258a941818f07c6e84d44a7a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Tue, 9 Aug 2022 21:06:01 +0200 Subject: feat: add ext/node for require support (#15362) This commit adds "ext/node" extension that implementes CommonJS module system. In the future this extension might be extended to actually contain implementation of Node compatibility layer in favor of "deno_std/node". Currently this functionality is not publicly exposed, it is available via "Deno[Deno.internal].require" namespace and is meant to be used by other functionality to be landed soon. This is a minimal first pass, things that still don't work: support for dynamic imports in CJS conditional exports --- cli/compat/mod.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'cli/compat/mod.rs') diff --git a/cli/compat/mod.rs b/cli/compat/mod.rs index 98af2ea61..df5174fd3 100644 --- a/cli/compat/mod.rs +++ b/cli/compat/mod.rs @@ -75,12 +75,18 @@ static NODE_COMPAT_URL: Lazy = Lazy::new(|| { static GLOBAL_URL_STR: Lazy = Lazy::new(|| format!("{}node/global.ts", NODE_COMPAT_URL.as_str())); +static PROCESS_URL_STR: Lazy = + Lazy::new(|| format!("{}node/process.ts", NODE_COMPAT_URL.as_str())); + pub static GLOBAL_URL: Lazy = Lazy::new(|| Url::parse(&GLOBAL_URL_STR).unwrap()); static MODULE_URL_STR: Lazy = Lazy::new(|| format!("{}node/module.ts", NODE_COMPAT_URL.as_str())); +static MODULE_ALL_URL_STR: Lazy = + Lazy::new(|| format!("{}node/module_all.ts", NODE_COMPAT_URL.as_str())); + pub static MODULE_URL: Lazy = Lazy::new(|| Url::parse(&MODULE_URL_STR).unwrap()); @@ -106,6 +112,46 @@ fn try_resolve_builtin_module(specifier: &str) -> Option { } } +#[allow(unused)] +pub async fn load_builtin_node_modules( + js_runtime: &mut JsRuntime, +) -> Result<(), AnyError> { + let source_code = &format!( + r#"(async function loadBuiltinNodeModules(moduleAllUrl, processUrl) {{ + const [moduleAll, processModule] = await Promise.all([ + import(moduleAllUrl), + import(processUrl) + ]); + Deno[Deno.internal].require.initializeCommonJs(moduleAll.default, processModule.default); + }})('{}', '{}');"#, + MODULE_ALL_URL_STR.as_str(), + PROCESS_URL_STR.as_str(), + ); + + let value = + js_runtime.execute_script(&located_script_name!(), source_code)?; + js_runtime.resolve_value(value).await?; + Ok(()) +} + +#[allow(unused)] +pub fn load_cjs_module_from_ext_node( + js_runtime: &mut JsRuntime, + module: &str, + main: bool, +) -> Result<(), AnyError> { + let source_code = &format!( + r#"(function loadCjsModule(module) {{ + Deno[Deno.internal].require.Module._load(module, null, {main}); + }})('{module}');"#, + main = main, + module = escape_for_single_quote_string(module), + ); + + js_runtime.execute_script(&located_script_name!(), source_code)?; + Ok(()) +} + pub fn load_cjs_module( js_runtime: &mut JsRuntime, module: &str, -- cgit v1.2.3