2022-01-07 22:09:52 -05:00
|
|
|
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
|
2021-10-18 13:36:28 -04:00
|
|
|
|
|
|
|
mod errors;
|
|
|
|
mod esm_resolver;
|
|
|
|
|
2022-02-27 08:38:45 -05:00
|
|
|
use crate::file_fetcher::FileFetcher;
|
|
|
|
use deno_ast::MediaType;
|
2021-10-18 13:36:28 -04:00
|
|
|
use deno_core::error::AnyError;
|
|
|
|
use deno_core::located_script_name;
|
|
|
|
use deno_core::url::Url;
|
|
|
|
use deno_core::JsRuntime;
|
2022-02-27 08:38:45 -05:00
|
|
|
use deno_core::ModuleSpecifier;
|
2021-12-18 16:14:42 -05:00
|
|
|
use once_cell::sync::Lazy;
|
2021-10-18 13:36:28 -04:00
|
|
|
|
2021-11-01 14:46:07 -04:00
|
|
|
pub use esm_resolver::check_if_should_use_esm_loader;
|
2022-03-23 09:54:22 -04:00
|
|
|
pub use esm_resolver::NodeEsmResolver;
|
2021-10-18 13:36:28 -04:00
|
|
|
|
2022-04-14 15:50:48 -04:00
|
|
|
// WARNING: Ensure this is the only deno_std version reference as this
|
|
|
|
// is automatically updated by the version bump workflow.
|
2022-06-30 15:31:47 -04:00
|
|
|
pub(crate) static STD_URL_STR: &str = "https://deno.land/std@0.146.0/";
|
2021-10-18 13:36:28 -04:00
|
|
|
|
|
|
|
static SUPPORTED_MODULES: &[&str] = &[
|
|
|
|
"assert",
|
|
|
|
"assert/strict",
|
|
|
|
"async_hooks",
|
|
|
|
"buffer",
|
|
|
|
"child_process",
|
|
|
|
"cluster",
|
|
|
|
"console",
|
|
|
|
"constants",
|
|
|
|
"crypto",
|
|
|
|
"dgram",
|
|
|
|
"dns",
|
|
|
|
"domain",
|
|
|
|
"events",
|
|
|
|
"fs",
|
|
|
|
"fs/promises",
|
|
|
|
"http",
|
|
|
|
"https",
|
|
|
|
"module",
|
|
|
|
"net",
|
|
|
|
"os",
|
|
|
|
"path",
|
|
|
|
"path/posix",
|
|
|
|
"path/win32",
|
|
|
|
"perf_hooks",
|
|
|
|
"process",
|
|
|
|
"querystring",
|
|
|
|
"readline",
|
|
|
|
"stream",
|
|
|
|
"stream/promises",
|
|
|
|
"stream/web",
|
|
|
|
"string_decoder",
|
|
|
|
"sys",
|
|
|
|
"timers",
|
|
|
|
"timers/promises",
|
|
|
|
"tls",
|
|
|
|
"tty",
|
|
|
|
"url",
|
|
|
|
"util",
|
|
|
|
"util/types",
|
|
|
|
"v8",
|
|
|
|
"vm",
|
|
|
|
"zlib",
|
|
|
|
];
|
|
|
|
|
2021-12-18 16:14:42 -05:00
|
|
|
static NODE_COMPAT_URL: Lazy<String> = Lazy::new(|| {
|
|
|
|
std::env::var("DENO_NODE_COMPAT_URL")
|
|
|
|
.map(String::into)
|
|
|
|
.ok()
|
|
|
|
.unwrap_or_else(|| STD_URL_STR.to_string())
|
|
|
|
});
|
|
|
|
|
|
|
|
static GLOBAL_URL_STR: Lazy<String> =
|
|
|
|
Lazy::new(|| format!("{}node/global.ts", NODE_COMPAT_URL.as_str()));
|
|
|
|
|
2022-03-23 09:54:22 -04:00
|
|
|
pub static GLOBAL_URL: Lazy<Url> =
|
2021-12-18 16:14:42 -05:00
|
|
|
Lazy::new(|| Url::parse(&GLOBAL_URL_STR).unwrap());
|
|
|
|
|
|
|
|
static MODULE_URL_STR: Lazy<String> =
|
|
|
|
Lazy::new(|| format!("{}node/module.ts", NODE_COMPAT_URL.as_str()));
|
|
|
|
|
2022-03-23 09:54:22 -04:00
|
|
|
pub static MODULE_URL: Lazy<Url> =
|
2021-12-18 16:14:42 -05:00
|
|
|
Lazy::new(|| Url::parse(&MODULE_URL_STR).unwrap());
|
|
|
|
|
|
|
|
static COMPAT_IMPORT_URL: Lazy<Url> =
|
|
|
|
Lazy::new(|| Url::parse("flags:compat").unwrap());
|
2021-10-18 13:36:28 -04:00
|
|
|
|
|
|
|
/// Provide imports into a module graph when the compat flag is true.
|
2022-03-23 09:54:22 -04:00
|
|
|
pub fn get_node_imports() -> Vec<(Url, Vec<String>)> {
|
2021-10-18 13:36:28 -04:00
|
|
|
vec![(COMPAT_IMPORT_URL.clone(), vec![GLOBAL_URL_STR.clone()])]
|
|
|
|
}
|
|
|
|
|
|
|
|
fn try_resolve_builtin_module(specifier: &str) -> Option<Url> {
|
|
|
|
if SUPPORTED_MODULES.contains(&specifier) {
|
2021-10-20 18:23:57 -04:00
|
|
|
let module_url =
|
|
|
|
format!("{}node/{}.ts", NODE_COMPAT_URL.as_str(), specifier);
|
2021-10-18 13:36:28 -04:00
|
|
|
Some(Url::parse(&module_url).unwrap())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-23 09:54:22 -04:00
|
|
|
pub fn load_cjs_module(
|
2021-10-18 13:36:28 -04:00
|
|
|
js_runtime: &mut JsRuntime,
|
2021-12-30 11:18:30 -05:00
|
|
|
module: &str,
|
|
|
|
main: bool,
|
2021-10-18 13:36:28 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let source_code = &format!(
|
2021-12-30 11:18:30 -05:00
|
|
|
r#"(async function loadCjsModule(module) {{
|
|
|
|
const Module = await import("{module_loader}");
|
|
|
|
Module.default._load(module, null, {main});
|
|
|
|
}})('{module}');"#,
|
|
|
|
module_loader = MODULE_URL_STR.as_str(),
|
|
|
|
main = main,
|
|
|
|
module = escape_for_single_quote_string(module),
|
2021-10-18 13:36:28 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
js_runtime.execute_script(&located_script_name!(), source_code)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-03-23 09:54:22 -04:00
|
|
|
pub fn add_global_require(
|
2021-11-24 10:55:10 -05:00
|
|
|
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(())
|
|
|
|
}
|
|
|
|
|
2021-10-18 13:36:28 -04:00
|
|
|
fn escape_for_single_quote_string(text: &str) -> String {
|
2022-02-24 20:03:12 -05:00
|
|
|
text.replace('\\', r"\\").replace('\'', r"\'")
|
2021-10-18 13:36:28 -04:00
|
|
|
}
|
2022-01-03 14:10:17 -05:00
|
|
|
|
|
|
|
pub fn setup_builtin_modules(
|
|
|
|
js_runtime: &mut JsRuntime,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let mut script = String::new();
|
|
|
|
for module in SUPPORTED_MODULES {
|
|
|
|
// skipping the modules that contains '/' as they are not available in NodeJS repl as well
|
|
|
|
if !module.contains('/') {
|
|
|
|
script = format!("{}const {} = require('{}');\n", script, module, module);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
js_runtime.execute_script("setup_node_builtins.js", &script)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2022-02-27 08:38:45 -05:00
|
|
|
|
|
|
|
/// Translates given CJS module into ESM. This function will perform static
|
|
|
|
/// analysis on the file to find defined exports and reexports.
|
|
|
|
///
|
|
|
|
/// For all discovered reexports the analysis will be performed recursively.
|
|
|
|
///
|
|
|
|
/// If successful a source code for equivalent ES module is returned.
|
|
|
|
pub async fn translate_cjs_to_esm(
|
|
|
|
file_fetcher: &FileFetcher,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
code: String,
|
|
|
|
media_type: MediaType,
|
|
|
|
) -> Result<String, AnyError> {
|
|
|
|
let parsed_source = deno_ast::parse_script(deno_ast::ParseParams {
|
|
|
|
specifier: specifier.to_string(),
|
2022-05-20 16:40:55 -04:00
|
|
|
text_info: deno_ast::SourceTextInfo::new(code.into()),
|
2022-02-27 08:38:45 -05:00
|
|
|
media_type,
|
|
|
|
capture_tokens: true,
|
|
|
|
scope_analysis: false,
|
|
|
|
maybe_syntax: None,
|
|
|
|
})?;
|
|
|
|
let analysis = parsed_source.analyze_cjs();
|
|
|
|
|
|
|
|
let mut source = vec![
|
|
|
|
r#"import { createRequire } from "node:module";"#.to_string(),
|
|
|
|
r#"const require = createRequire(import.meta.url);"#.to_string(),
|
|
|
|
];
|
|
|
|
|
|
|
|
// if there are reexports, handle them first
|
|
|
|
for (idx, reexport) in analysis.reexports.iter().enumerate() {
|
|
|
|
// Firstly, resolve relate reexport specifier
|
2022-03-16 21:37:02 -04:00
|
|
|
let resolved_reexport = node_resolver::resolve(
|
2022-02-27 08:38:45 -05:00
|
|
|
reexport,
|
|
|
|
&specifier.to_file_path().unwrap(),
|
|
|
|
// FIXME(bartlomieju): check if these conditions are okay, probably
|
|
|
|
// should be `deno-require`, because `deno` is already used in `esm_resolver.rs`
|
|
|
|
&["deno", "require", "default"],
|
|
|
|
)?;
|
|
|
|
let reexport_specifier =
|
|
|
|
ModuleSpecifier::from_file_path(&resolved_reexport).unwrap();
|
|
|
|
// Secondly, read the source code from disk
|
|
|
|
let reexport_file = file_fetcher.get_source(&reexport_specifier).unwrap();
|
|
|
|
// Now perform analysis again
|
|
|
|
{
|
|
|
|
let parsed_source = deno_ast::parse_script(deno_ast::ParseParams {
|
|
|
|
specifier: reexport_specifier.to_string(),
|
2022-05-20 16:40:55 -04:00
|
|
|
text_info: deno_ast::SourceTextInfo::new(reexport_file.source),
|
2022-02-27 08:38:45 -05:00
|
|
|
media_type: reexport_file.media_type,
|
|
|
|
capture_tokens: true,
|
|
|
|
scope_analysis: false,
|
|
|
|
maybe_syntax: None,
|
|
|
|
})?;
|
|
|
|
let analysis = parsed_source.analyze_cjs();
|
|
|
|
|
|
|
|
source.push(format!(
|
|
|
|
"const reexport{} = require(\"{}\");",
|
|
|
|
idx, reexport
|
|
|
|
));
|
|
|
|
|
|
|
|
for export in analysis.exports.iter().filter(|e| e.as_str() != "default")
|
|
|
|
{
|
|
|
|
// TODO(bartlomieju): Node actually checks if a given export exists in `exports` object,
|
|
|
|
// but it might not be necessary here since our analysis is more detailed?
|
|
|
|
source.push(format!(
|
|
|
|
"export const {} = reexport{}.{};",
|
|
|
|
export, idx, export
|
|
|
|
));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
source.push(format!(
|
|
|
|
"const mod = require(\"{}\");",
|
|
|
|
specifier
|
|
|
|
.to_file_path()
|
|
|
|
.unwrap()
|
|
|
|
.to_str()
|
|
|
|
.unwrap()
|
|
|
|
.replace('\\', "\\\\")
|
|
|
|
.replace('\'', "\\\'")
|
|
|
|
.replace('\"', "\\\"")
|
|
|
|
));
|
2022-03-30 14:57:13 -04:00
|
|
|
source.push("export default mod;".to_string());
|
2022-02-27 08:38:45 -05:00
|
|
|
|
|
|
|
for export in analysis.exports.iter().filter(|e| e.as_str() != "default") {
|
|
|
|
// TODO(bartlomieju): Node actually checks if a given export exists in `exports` object,
|
|
|
|
// but it might not be necessary here since our analysis is more detailed?
|
|
|
|
source.push(format!("export const {} = mod.{};", export, export));
|
|
|
|
}
|
|
|
|
|
|
|
|
let translated_source = source.join("\n");
|
|
|
|
Ok(translated_source)
|
|
|
|
}
|