Skip to content

Commit

Permalink
more simple relative path creation for CJS wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
mash-graz committed Mar 19, 2024
1 parent 5fab2ce commit b870900
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 23 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion ext/node/Cargo.toml
Expand Up @@ -54,7 +54,6 @@ p224.workspace = true
p256.workspace = true
p384.workspace = true
path-clean = "=0.1.0"
pathdiff = "0.2.1"
pbkdf2 = "0.12.1"
pin-project-lite = "0.2.13"
rand.workspace = true
Expand Down
29 changes: 8 additions & 21 deletions ext/node/ops/worker_threads.rs
Expand Up @@ -6,7 +6,6 @@ use deno_core::op2;
use deno_core::url::Url;
use deno_core::OpState;
use deno_fs::FileSystemRc;
use pathdiff::diff_paths;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
Expand Down Expand Up @@ -67,34 +66,22 @@ where
let node_resolver = state.borrow::<Rc<NodeResolver>>();
match node_resolver.url_to_node_resolution(url)? {
resolution::NodeResolution::Esm(u) => Ok(u.to_string()),
resolution::NodeResolution::CommonJs(u) => wrap_cjs(state, u),
resolution::NodeResolution::CommonJs(u) => wrap_cjs(u),
_ => Err(generic_error("Neither ESM nor CJS")),
}
}

///
/// Wrap a CJS file-URL and the required setup in a stringified `data:`-URL
///
fn wrap_cjs(state: &mut OpState, url: Url) -> Result<String, AnyError> {
let fs = state.borrow::<FileSystemRc>();
let cwd = fs.cwd()?;
let cwd_url = Url::from_directory_path(&cwd)
.map_err(|e| generic_error(format!("Create CWD Url: {:#?}", e)))?;
let rel_path = match diff_paths(
url
.to_file_path()
.map_err(|e| generic_error(format!("URL to Path-String: {:#?}", e)))?,
&cwd,
) {
Some(p) => Path::new(".").join(p),
None => url.path().into(),
};
fn wrap_cjs(url: Url) -> Result<String, AnyError> {
let path = url
.to_file_path()
.map_err(|e| generic_error(format!("URL to Path: {:#?}", e)))?;
let filename = path.file_name().unwrap().to_string_lossy();
Ok(format!(
"data:text/javascript,import {{ createRequire }} from \"node:module\";\
const require = createRequire(\"{}\"); require(\"{}\");",
cwd_url,
rel_path
.to_string_lossy()
.replace(std::path::MAIN_SEPARATOR, "/")
const require = createRequire(\"{}\"); require(\"./{}\");",
url, filename,
))
}

0 comments on commit b870900

Please sign in to comment.