From 7eda0b9910831cc46e7999409e44f58b00a5063e Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 6 Sep 2026 06:10:52 +0000 Subject: [PATCH 01/15] resolver: anchor a relative require.resolve paths entry at the cwd Node resolves each options.paths entry with path.resolve() before it searches node_modules under it. Bun passed the raw entry to the resolver, which has no DirInfo for a non-absolute directory, so require.resolve("pkg", { paths: ["./lib"] }) threw MODULE_NOT_FOUND while Node found /lib/node_modules/pkg. --- src/resolver/resolver.rs | 23 +++++++++--- .../module-resolve-filename-paths.test.js | 37 +++++++++++++++++++ 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 31dd498e7972..69d96658dd0f 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -1971,12 +1971,23 @@ impl<'a> Resolver<'a> { bun_core::hint::cold(); for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8(); - match self.check_package_path( - custom_utf8.slice(), - import_path, - kind, - global_cache, - ) { + // Node anchors a relative `paths` entry at the cwd + // (`Module._nodeModulePaths` starts with `path.resolve(from)`). + let mut abs_buf = bun_paths::path_buffer_pool::get(); + let custom_dir: &[u8] = if bun_paths::is_absolute(custom_utf8.slice()) { + custom_utf8.slice() + } else { + use bun_paths::resolve_path::{join_abs_string_buf_checked, platform}; + match join_abs_string_buf_checked::( + self.fs_ref().top_level_dir, + &mut *abs_buf, + &[custom_utf8.slice()], + ) { + Some(dir) => dir, + None => continue, + } + }; + match self.check_package_path(custom_dir, import_path, kind, global_cache) { ResultUnion::Success(res) => return ResultUnion::Success(res), ResultUnion::Pending(p) => return ResultUnion::Pending(p), ResultUnion::Failure(p) => return ResultUnion::Failure(p), diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index 43740bee95ba..6be53d8ea843 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -199,3 +199,40 @@ test("Module._resolveFilename throws ERR_INVALID_ARG_TYPE if options.paths is no Module._resolveFilename("path", __filename, false, { paths: { 0: "/some/path" } }); }).toThrow(); }); + +test("require.resolve anchors a relative options.paths entry at the cwd", () => { + // Node resolves a relative entry with path.resolve(), so it is relative to process.cwd(). + const { path: dir, cleanup } = createTempDir("require-resolve-relative-paths", { + "lib/node_modules/relative-paths-pkg/package.json": JSON.stringify({ + name: "relative-paths-pkg", + main: "index.js", + }), + "lib/node_modules/relative-paths-pkg/index.js": "module.exports = 'relative-paths';", + }); + const previousCwd = process.cwd(); + + try { + process.chdir(dir); + const expected = resolve(dir, "lib/node_modules/relative-paths-pkg/index.js"); + + expect(require.resolve("relative-paths-pkg", { paths: ["./lib"] })).toBe(expected); + expect(require.resolve("relative-paths-pkg", { paths: ["lib"] })).toBe(expected); + + const fakeParent = new Module("/some/other/directory/file.js"); + fakeParent.filename = "/some/other/directory/file.js"; + fakeParent.paths = Module._nodeModulePaths("/some/other/directory"); + expect(Module._resolveFilename("relative-paths-pkg", fakeParent, false, { paths: ["lib"] })).toBe(expected); + + // An entry that does not exist under the cwd is not found. + let caught; + try { + require.resolve("relative-paths-pkg", { paths: ["./missing"] }); + } catch (err) { + caught = err.code; + } + expect(caught).toBe("MODULE_NOT_FOUND"); + } finally { + process.chdir(previousCwd); + cleanup(); + } +}); From 9c590719f37044724087e78232ae154d3ee288d8 Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 6 Sep 2026 06:24:07 +0000 Subject: [PATCH 02/15] resolver: join a relative paths entry with the shared abs_buf_checked helper --- src/resolver/resolver.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 69d96658dd0f..9af4de6c1132 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -1977,12 +1977,10 @@ impl<'a> Resolver<'a> { let custom_dir: &[u8] = if bun_paths::is_absolute(custom_utf8.slice()) { custom_utf8.slice() } else { - use bun_paths::resolve_path::{join_abs_string_buf_checked, platform}; - match join_abs_string_buf_checked::( - self.fs_ref().top_level_dir, - &mut *abs_buf, - &[custom_utf8.slice()], - ) { + match self + .fs_ref() + .abs_buf_checked(&[custom_utf8.slice()], &mut *abs_buf) + { Some(dir) => dir, None => continue, } From 8012e2f8e16f38603f3e703ebbb585d9c2844d5a Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 6 Sep 2026 06:25:23 +0000 Subject: [PATCH 03/15] resolver: shorten the relative paths comment --- src/resolver/resolver.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 9af4de6c1132..818972c3199b 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -1971,8 +1971,7 @@ impl<'a> Resolver<'a> { bun_core::hint::cold(); for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8(); - // Node anchors a relative `paths` entry at the cwd - // (`Module._nodeModulePaths` starts with `path.resolve(from)`). + // A relative entry is cwd-relative, like Node's `path.resolve(from)`. let mut abs_buf = bun_paths::path_buffer_pool::get(); let custom_dir: &[u8] = if bun_paths::is_absolute(custom_utf8.slice()) { custom_utf8.slice() From 403d5a964724af616bda59e800f69f38b90e2325 Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 6 Sep 2026 07:46:49 +0000 Subject: [PATCH 04/15] ci: retrigger From 849a01f8391cdf5fa4347f94ba36a50ed5214ad6 Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 26 Oct 2026 05:23:33 +0000 Subject: [PATCH 05/15] resolver: read a require.resolve paths entry with host path rules in both loops One helper resolves an entry the way Node's path.resolve() does. The bare-request loop and the relative-request loop both use it. On POSIX a component that holds a backslash or a NUL is not handed to the directory cache, which reads the first as a separator and the second as the end of the path. - Bare request: search from the deepest directory above such a component, with auto-install off for that entry. - Relative request: Node's Module._findPath gate (the entry is a directory unless the request leaves it). A ".." request is joined with host rules. - Module._resolveFilename: a builtin id is returned before paths is read. A non-string entry of a request that is not relative throws ERR_INVALID_ARG_TYPE. --- src/jsc/modules/NodeModuleModule.cpp | 28 ++ src/resolver/resolver.rs | 304 +++++++++++++++--- .../module-resolve-filename-paths.test.js | 179 +++++++++-- 3 files changed, 443 insertions(+), 68 deletions(-) diff --git a/src/jsc/modules/NodeModuleModule.cpp b/src/jsc/modules/NodeModuleModule.cpp index 7bffa59c6af3..3bf62455fa09 100644 --- a/src/jsc/modules/NodeModuleModule.cpp +++ b/src/jsc/modules/NodeModuleModule.cpp @@ -278,6 +278,16 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleCreateRequire, scope, JSValue::encode(Bun::JSCommonJSModule::createBoundRequireFunction(vm, globalObject, val, Bun::currentModuleGraph(defaultGlobalObject(globalObject))))); } +// The requests the resolver reads as relative to a directory instead of as a package name. +static bool isRelativeRequest(const WTF::String& request) +{ + return request == "."_s || request == ".."_s || request.startsWith("./"_s) || request.startsWith("../"_s) +#if OS(WINDOWS) + || request.startsWith(".\\"_s) || request.startsWith("..\\"_s) +#endif + ; +} + JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) @@ -343,6 +353,17 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, JSC::EncodedJSValue result; + // Like Node: a builtin id wins before `paths` is read; any other non-relative request needs string entries. + bool entriesMustBeStrings = false; + if (!pathsValue.isUndefinedOrNull() && moduleName.isString()) { + auto request = moduleName.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); + if (Bun::isBuiltinModule(request)) + pathsValue = JSC::jsUndefined(); + else + entriesMustBeStrings = !isRelativeRequest(request); + } + // If paths are provided, use Bun__resolveSyncWithPaths if (!pathsValue.isUndefinedOrNull()) { // Node.js requires options.paths to be an array @@ -356,12 +377,19 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, } WTF::Vector paths; + size_t index = 0; // Iterate through the array using forEachInIterable forEachInIterable(globalObject, pathsValue, [&](JSC::VM&, JSC::JSGlobalObject* lexicalGlobalObject, JSC::JSValue item) { if (scope.exception()) return; + if (entriesMustBeStrings && !item.isString()) { + Bun::ERR::INVALID_ARG_TYPE(scope, lexicalGlobalObject, makeString("paths["_s, index, "]"_s), "string"_s, item); + return; + } + index++; + WTF::String pathStr = item.toWTFString(lexicalGlobalObject); if (scope.exception()) return; diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 67e635fc39eb..45e1f83ea014 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -1890,22 +1890,14 @@ impl<'a> Resolver<'a> { if let Some(custom_paths) = self.custom_dir_paths { // @branchHint(.unlikely) bun_core::hint::cold(); - for custom_path in custom_paths { - let custom_utf8 = custom_path.to_utf8(); - match self.check_relative_path( - custom_utf8.slice(), - import_path, - kind, - global_cache, - ) { - ResultUnion::Success(res) => return ResultUnion::Success(res), - ResultUnion::Pending(p) => return ResultUnion::Pending(p), - ResultUnion::Failure(p) => return ResultUnion::Failure(p), - ResultUnion::NotFound => {} - } - } debug_assert!(!check_package); // always from JavaScript - return ResultUnion::NotFound; // bail out now since there isn't anywhere else to check + // bail out after this since there isn't anywhere else to check + return self.check_relative_path_in_custom_dirs( + custom_paths, + import_path, + kind, + global_cache, + ); } else { match self.check_relative_path(source_dir, import_path, kind, global_cache) { ResultUnion::Success(res) => return ResultUnion::Success(res), @@ -2031,28 +2023,12 @@ impl<'a> Resolver<'a> { if let Some(custom_paths) = self.custom_dir_paths { bun_core::hint::cold(); - for custom_path in custom_paths { - let custom_utf8 = custom_path.to_utf8(); - // A relative entry is cwd-relative, like Node's `path.resolve(from)`. - let mut abs_buf = bun_paths::path_buffer_pool::get(); - let custom_dir: &[u8] = if bun_paths::is_absolute(custom_utf8.slice()) { - custom_utf8.slice() - } else { - match self - .fs_ref() - .abs_buf_checked(&[custom_utf8.slice()], &mut *abs_buf) - { - Some(dir) => dir, - None => continue, - } - }; - match self.check_package_path(custom_dir, import_path, kind, global_cache) { - ResultUnion::Success(res) => return ResultUnion::Success(res), - ResultUnion::Pending(p) => return ResultUnion::Pending(p), - ResultUnion::Failure(p) => return ResultUnion::Failure(p), - ResultUnion::NotFound => {} - } - } + return self.check_package_path_in_custom_dirs( + custom_paths, + import_path, + kind, + global_cache, + ); } else { match self.check_package_path(source_dir, import_path, kind, global_cache) { ResultUnion::Success(res) => return ResultUnion::Success(res), @@ -2085,6 +2061,197 @@ impl<'a> Resolver<'a> { rest.is_empty() || ResolvePath::is_sep_any(rest[rest.len() - 1]) } + /// Node's `path.resolve(entry)` for a `paths` entry. `buf` is taken only when that changes it. + fn custom_dir<'b>( + &self, + entry: &'b [u8], + buf: &'b mut Option, + ) -> Option> { + #[cfg(windows)] + let path: &'b [u8] = if bun_paths::is_absolute(entry) { + entry + } else { + let buf = buf.get_or_insert_with(bun_paths::path_buffer_pool::get); + self.fs_ref().abs_buf_checked(&[entry], &mut buf[..])? + }; + #[cfg(not(windows))] + let path: &'b [u8] = if CustomDir::is_resolved(entry) { + entry + } else { + let cwd: &[u8] = if entry.first() == Some(&b'/') { + b"" + } else { + self.fs_ref().top_level_dir() + }; + let buf = buf.get_or_insert_with(bun_paths::path_buffer_pool::get); + if cwd.len() + entry.len() + 2 > buf.len() { + return None; + } + let joined = + bun_paths::join_string_buf(&mut buf[..], &[cwd, entry], bun_paths::Platform::Posix); + if joined.len() > 1 && joined.ends_with(b"/") { + &joined[..joined.len() - 1] + } else { + joined + } + }; + + let searchable_len = match strings::index_of_any(path, CustomDir::UNSEARCHABLE) { + None => path.len(), + Some(unsearchable) => { + #[cfg(windows)] + let root_len = bun_paths::windows_filesystem_root(path).len(); + #[cfg(not(windows))] + let root_len = 1; + if unsearchable < root_len { + return None; + } + strings::last_index_of_any(&path[..unsearchable], CustomDir::SEPARATORS) + .map_or(root_len, |separator| separator.max(root_len)) + } + }; + Some(CustomDir { + path, + searchable_len, + }) + } + + /// Node's `_stat(entry) === 1`. The OS walks each component, so `missing/..` is no directory. + fn custom_dir_entry_is_directory( + &self, + entry: &[u8], + buf: &mut Option, + ) -> bool { + // Node hands the entry to stat() as a C string. + let entry = match strings::index_of_char(entry, 0) { + Some(nul) => &entry[..nul as usize], + None => entry, + }; + if entry.is_empty() { + return false; + } + let cwd: &[u8] = if bun_paths::is_absolute(entry) { + b"" + } else { + self.fs_ref().top_level_dir() + }; + let buf = buf.get_or_insert_with(bun_paths::path_buffer_pool::get); + if cwd.len() + 1 + entry.len() >= buf.len() { + return false; + } + let mut len = 0; + if !cwd.is_empty() { + buf[..cwd.len()].copy_from_slice(cwd); + buf[cwd.len()] = SEP; + len = cwd.len() + 1; + } + buf[len..len + entry.len()].copy_from_slice(entry); + len += entry.len(); + buf[len] = 0; + bun_sys::directory_exists_at(FD::cwd(), bun_core::ZStr::from_buf(&buf[..], len)) + .unwrap_or(false) + } + + /// Node's `Module._findPath` over the `paths` entries, for a relative request. + #[cold] + #[inline(never)] + fn check_relative_path_in_custom_dirs( + &mut self, + custom_paths: &[bun_core::String], + import_path: &[u8], + kind: ast::ImportKind, + global_cache: GlobalCache, + ) -> ResultUnion { + let stays_inside = CustomDir::request_stays_inside(import_path); + let mut buf = None; + for custom_path in custom_paths { + let custom_utf8 = custom_path.to_utf8(); + let entry = custom_utf8.slice(); + // Node skips an entry that is not a directory when the request cannot leave it. + let must_be_directory = stays_inside && !entry.is_empty(); + let has_parent_segment = cfg!(not(windows)) + && must_be_directory + && strings::split_any(entry, CustomDir::SEPARATORS).any(|segment| segment == b".."); + if has_parent_segment && !self.custom_dir_entry_is_directory(entry, &mut buf) { + continue; + } + let Some(dir) = self.custom_dir(entry, &mut buf) else { + continue; + }; + let result = if !dir.is_cut() { + if must_be_directory + && !has_parent_segment + && !matches!(self.dir_info_cached(dir.path), Ok(Some(_))) + { + continue; + } + self.check_relative_path(dir.path, import_path, kind, global_cache) + } else if stays_inside { + continue; + } else { + // A ".." request can step out of the components that were cut off. + let mut joined = bun_paths::path_buffer_pool::get(); + if dir.path.len() + import_path.len() + 3 > joined.len() { + continue; + } + let mut len = bun_paths::join_string_buf( + &mut joined[..], + &[dir.path, import_path], + bun_paths::Platform::AUTO, + ) + .len(); + if strings::index_of_any(&joined[..len], CustomDir::UNSEARCHABLE).is_some() { + continue; + } + if Self::import_path_names_directory(import_path) && joined[len - 1] != SEP { + joined[len] = SEP; + len += 1; + } + self.check_relative_path(&joined[..len], b"", kind, global_cache) + }; + match result { + ResultUnion::NotFound => {} + found => return found, + } + } + ResultUnion::NotFound + } + + /// Node's search of `Module._nodeModulePaths(entry)` per `paths` entry, for a bare request. + #[cold] + #[inline(never)] + fn check_package_path_in_custom_dirs( + &mut self, + custom_paths: &[bun_core::String], + import_path: &'static [u8], + kind: ast::ImportKind, + global_cache: GlobalCache, + ) -> ResultUnion { + let mut buf = None; + for custom_path in custom_paths { + let custom_utf8 = custom_path.to_utf8(); + let Some(dir) = self.custom_dir(custom_utf8.slice(), &mut buf) else { + continue; + }; + // Nothing below the cut was searched, so a miss must not start an install. + let global_cache = if dir.is_cut() { + GlobalCache::disable + } else { + global_cache + }; + match self.check_package_path( + &dir.path[..dir.searchable_len], + import_path, + kind, + global_cache, + ) { + ResultUnion::NotFound => {} + found => return found, + } + } + ResultUnion::NotFound + } + pub(crate) fn check_relative_path( &mut self, source_dir: &[u8], @@ -6946,6 +7113,69 @@ fn rewritten_file_extensions( } } +/// A `paths` entry of `require.resolve()` as Node's `path.resolve(entry)` reads it. +struct CustomDir<'a> { + path: &'a [u8], + /// `path[..searchable_len]` ends before the first component that holds an `UNSEARCHABLE` byte. + searchable_len: usize, +} + +impl CustomDir<'_> { + /// The directory cache reads a NUL as the end of a path and a POSIX backslash as a separator. + const UNSEARCHABLE: &'static [u8] = if cfg!(windows) { b"\0" } else { b"\\\0" }; + const SEPARATORS: &'static [u8] = if cfg!(windows) { b"/\\" } else { b"/" }; + + fn is_cut(&self) -> bool { + self.searchable_len < self.path.len() + } + + /// Whether `path.resolve(entry)` returns `entry` unchanged and no byte of it is unsearchable. + #[cfg(not(windows))] + fn is_resolved(entry: &[u8]) -> bool { + if entry.first() != Some(&b'/') { + return false; + } + let mut segment_start = 1; + for (i, &byte) in entry.iter().enumerate().skip(1) { + match byte { + b'\\' | 0 => return false, + b'/' => { + if matches!(&entry[segment_start..i], b"" | b"." | b"..") { + return false; + } + segment_start = i + 1; + } + _ => {} + } + } + entry.len() == 1 || !matches!(&entry[segment_start..], b"" | b"." | b"..") + } + + /// Node's `insidePath`: false when `path.normalize(request)` starts with "..". + fn request_stays_inside(request: &[u8]) -> bool { + let mut depth: usize = 0; + let mut first_starts_with_dot_dot = false; + for segment in strings::split_any(request, Self::SEPARATORS) { + match segment { + b"" | b"." => {} + b".." => { + if depth == 0 { + return false; + } + depth -= 1; + } + _ => { + if depth == 0 { + first_starts_with_dot_dot = segment.starts_with(b".."); + } + depth += 1; + } + } + } + depth == 0 || !first_starts_with_dot_dot + } +} + pub struct Dirname; impl Dirname { diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index 6be53d8ea843..a96446f5efda 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -1,4 +1,5 @@ // Use bun:test in Bun, or node:test in Node.js +import { spawnSync } from "child_process"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "fs"; import Module from "module"; import { tmpdir } from "os"; @@ -7,9 +8,11 @@ import { dirname, join, resolve } from "path"; // Detect runtime and import appropriate test framework const isBun = typeof Bun !== "undefined"; let test, expect; +let childEnv = process.env; if (isBun) { ({ test, expect } = await import("bun:test")); + ({ bunEnv: childEnv } = await import("harness")); } else { // Node.js const { createRequire } = await import("module"); @@ -184,55 +187,169 @@ test("require.resolve with relative path and options.paths (Next.js use case)", }); test("Module._resolveFilename throws ERR_INVALID_ARG_TYPE if options.paths is not an array", () => { + // The request is not a builtin id: Node returns a builtin id before it reads `options.paths`. + const fakeParent = new Module("/some/other/directory/file.js"); + // Test with string (which is iterable but not an array) expect(() => { - Module._resolveFilename("path", __filename, false, { paths: "/some/path" }); + Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: "/some/path" }); }).toThrow(); // Test with Set (which is iterable but not an array) expect(() => { - Module._resolveFilename("path", __filename, false, { paths: new Set(["/some/path"]) }); + Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: new Set(["/some/path"]) }); }).toThrow(); // Test with object (not iterable) expect(() => { - Module._resolveFilename("path", __filename, false, { paths: { 0: "/some/path" } }); + Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: { 0: "/some/path" } }); }).toThrow(); + + expect(Module._resolveFilename("path", fakeParent, false, { paths: "/some/path" })).toBe("path"); }); -test("require.resolve anchors a relative options.paths entry at the cwd", () => { - // Node resolves a relative entry with path.resolve(), so it is relative to process.cwd(). - const { path: dir, cleanup } = createTempDir("require-resolve-relative-paths", { - "lib/node_modules/relative-paths-pkg/package.json": JSON.stringify({ - name: "relative-paths-pkg", - main: "index.js", - }), - "lib/node_modules/relative-paths-pkg/index.js": "module.exports = 'relative-paths';", - }); - const previousCwd = process.cwd(); +// Node turns each `options.paths` entry into a directory with path.resolve(): a relative entry is +// relative to process.cwd(), and only the host's separators separate. Each resolve runs in a child +// process so that the cwd is the fixture and the resolver starts with empty caches. +const probeSource = ` +const Module = require("node:module"); +const path = require("node:path"); +const root = process.cwd(); +const rows = JSON.parse(require("node:fs").readFileSync("rows.json", "utf8")); +const resolvers = { + "require.resolve": (request, paths) => require.resolve(request, { paths }), + "Module._resolveFilename": (request, paths) => Module._resolveFilename(request, module, false, { paths }), + "createRequire().resolve": (request, paths) => Module.createRequire(__filename).resolve(request, { paths }), +}; +const order = rows.map((row, i) => i); +if (process.argv[2] === "reverse") order.reverse(); +const results = []; +for (const i of order) { + const [request, paths, chdir] = rows[i]; + if (chdir) process.chdir(chdir); + results[i] = {}; + for (const name in resolvers) { + try { + results[i][name] = path.relative(root, resolvers[name](request, paths)).split(path.sep).join("/"); + } catch (error) { + results[i][name] = error.code; + } + } + process.chdir(root); +} +console.log(JSON.stringify(results)); +`; + +function resolveRowsInChild(order) { + const isWindows = process.platform === "win32"; + const files = { + "probe.cjs": probeSource, + // A node_modules directory at the root also keeps Bun's auto-install off. + "node_modules/plugroot/index.js": "", + "plugins/node_modules/plug/index.js": "", + "plugins/file.js": "", + }; + if (!isWindows) { + files["back/slash/node_modules/plugc/index.js"] = ""; + files["C:/plugins/node_modules/plugd/index.js"] = ""; + } + const { path: dir, cleanup } = createTempDir("resolve-paths-entries", files); + + const plug = "plugins/node_modules/plug/index.js"; + const plugroot = "node_modules/plugroot/index.js"; + const file = "plugins/file.js"; + const missing = "MODULE_NOT_FOUND"; + // [request, paths, expected, directory to chdir() into first] + const rows = [ + // A bare request searches node_modules from the entry upward. + ["plug", ["./plugins"], plug], + ["plug", ["plugins"], plug], + ["plug", ["plugins/"], plug], + ["plug", ["plugins/../plugins"], plug], + ["plug", ["nowhere", "plugins"], plug], + ["plug", ["./nowhere"], missing], + ["plug", ["."], missing], + ["plugroot", [""], plugroot], + ["plugroot", ["."], plugroot], + ["plugroot", ["./nowhere/deeper"], plugroot], + ["plug", ["."], plug, "plugins"], + ["plugroot", [".."], plugroot, "plugins"], + // A relative request is joined to the entry. The entry must be a directory unless the + // request leaves it. + ["./node_modules/plug/index.js", ["plugins"], plug], + ["./node_modules/plug/index.js", ["./plugins"], plug], + ["./node_modules/plug/index.js", [join(dir, "plugins")], plug], + ["./node_modules/plug/index.js", ["nowhere", "plugins"], plug], + ["./file.js", ["plugins"], file], + ["./file.js", ["nowhere"], missing], + [".", ["plugins/file.js"], missing], + ["../plugins/file.js", ["nowhere"], file], + // A builtin id is resolved before `paths` is read. Any other bare request needs strings. + ["node:fs", [0], "node:fs"], + ["plugroot", [0], "ERR_INVALID_ARG_TYPE"], + ["plugroot", [".", null], "ERR_INVALID_ARG_TYPE"], + ]; + if (isWindows) { + rows.push(["plug", ["plugins\\"], plug], ["plug", [".\\plugins"], plug]); + } else { + const tooLong = Buffer.alloc(5000, "a").toString(); + rows.push( + ["plug", [dir + "/nope/../plugins"], plug], + // A backslash and a drive letter are file name characters on POSIX. + ["plug", ["plugins\\"], missing], + ["plug", [".\\plugins"], missing], + ["plug", [dir + "/plugins\\"], missing], + ["plugroot", ["plugins\\"], plugroot], + ["plugc", ["back\\slash"], missing], + ["plugd", ["C:/plugins"], "C:/plugins/node_modules/plugd/index.js"], + ["plugd", ["C:\\plugins"], missing], + ["./node_modules/plug/index.js", ["plugins\\"], missing], + ["./node_modules/plug/index.js", [".\\plugins"], missing], + ["./node_modules/plugc/index.js", ["back\\slash"], missing], + ["./node_modules/plugd/index.js", ["C:/plugins"], "C:/plugins/node_modules/plugd/index.js"], + ["../plugins/file.js", ["plugins\\"], file], + // The OS does not collapse "nowhere/..": the directory does not exist. + ["./node_modules/plugroot/index.js", ["nowhere/.."], missing], + ["plug", ["plugins\0x"], missing], + ["./index.js", [dir + "/plugins/node_modules/plug\0"], missing], + ["plug", [tooLong], missing], + ["./file.js", [tooLong], missing], + ); + } try { - process.chdir(dir); - const expected = resolve(dir, "lib/node_modules/relative-paths-pkg/index.js"); - - expect(require.resolve("relative-paths-pkg", { paths: ["./lib"] })).toBe(expected); - expect(require.resolve("relative-paths-pkg", { paths: ["lib"] })).toBe(expected); - - const fakeParent = new Module("/some/other/directory/file.js"); - fakeParent.filename = "/some/other/directory/file.js"; - fakeParent.paths = Module._nodeModulePaths("/some/other/directory"); - expect(Module._resolveFilename("relative-paths-pkg", fakeParent, false, { paths: ["lib"] })).toBe(expected); - - // An entry that does not exist under the cwd is not found. - let caught; + writeFileSync( + join(dir, "rows.json"), + JSON.stringify(rows.map(([request, paths, , chdir]) => [request, paths, chdir])), + ); + const { stdout, stderr, status } = spawnSync( + process.execPath, + isBun ? ["--no-install", "probe.cjs", order] : ["probe.cjs", order], + { cwd: dir, env: childEnv, encoding: "utf8" }, + ); + let results; try { - require.resolve("relative-paths-pkg", { paths: ["./missing"] }); - } catch (err) { - caught = err.code; + results = JSON.parse(stdout); + } catch { + results = { stdout, stderr }; } - expect(caught).toBe("MODULE_NOT_FOUND"); + expect(results).toEqual( + rows.map(([, , expected]) => ({ + "require.resolve": expected, + "Module._resolveFilename": expected, + "createRequire().resolve": expected, + })), + ); + expect(status).toBe(0); } finally { - process.chdir(previousCwd); cleanup(); } +} + +test("options.paths entries are resolved like path.resolve() does", () => { + resolveRowsInChild("forward"); +}); + +test("options.paths entries resolve the same in the reverse call order", () => { + resolveRowsInChild("reverse"); }); From 6ca0688354f07f69c7e41e51dd2553ec8ff62043 Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 26 Oct 2026 06:39:38 +0000 Subject: [PATCH 06/15] resolver: check that a paths entry is a directory only after a hit A clean absolute entry now costs one scan. The directory test of Node's Module._findPath runs once, for the entry that produced a result, and the ".." segment scan runs only when the text holds "..". --- src/resolver/resolver.rs | 46 +++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 45e1f83ea014..a8c9b68f6504 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -2075,9 +2075,13 @@ impl<'a> Resolver<'a> { self.fs_ref().abs_buf_checked(&[entry], &mut buf[..])? }; #[cfg(not(windows))] - let path: &'b [u8] = if CustomDir::is_resolved(entry) { - entry - } else { + let path: &'b [u8] = { + if CustomDir::is_resolved(entry) { + return Some(CustomDir { + path: entry, + searchable_len: entry.len(), + }); + } let cwd: &[u8] = if entry.first() == Some(&b'/') { b"" } else { @@ -2167,25 +2171,25 @@ impl<'a> Resolver<'a> { for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8(); let entry = custom_utf8.slice(); - // Node skips an entry that is not a directory when the request cannot leave it. - let must_be_directory = stays_inside && !entry.is_empty(); - let has_parent_segment = cfg!(not(windows)) - && must_be_directory - && strings::split_any(entry, CustomDir::SEPARATORS).any(|segment| segment == b".."); - if has_parent_segment && !self.custom_dir_entry_is_directory(entry, &mut buf) { - continue; - } let Some(dir) = self.custom_dir(entry, &mut buf) else { continue; }; let result = if !dir.is_cut() { - if must_be_directory - && !has_parent_segment - && !matches!(self.dir_info_cached(dir.path), Ok(Some(_))) - { - continue; + let dir = dir.path; + let result = self.check_relative_path(dir, import_path, kind, global_cache); + // Node skips an entry that is not a directory when the request cannot leave it. + if stays_inside && !entry.is_empty() && !matches!(result, ResultUnion::NotFound) { + let is_directory = if cfg!(not(windows)) && CustomDir::has_parent_segment(entry) + { + self.custom_dir_entry_is_directory(entry, &mut buf) + } else { + matches!(self.dir_info_cached(dir), Ok(Some(_))) + }; + if !is_directory { + continue; + } } - self.check_relative_path(dir.path, import_path, kind, global_cache) + result } else if stays_inside { continue; } else { @@ -7129,6 +7133,11 @@ impl CustomDir<'_> { self.searchable_len < self.path.len() } + fn has_parent_segment(entry: &[u8]) -> bool { + strings::contains(entry, b"..") + && strings::split_any(entry, Self::SEPARATORS).any(|segment| segment == b"..") + } + /// Whether `path.resolve(entry)` returns `entry` unchanged and no byte of it is unsearchable. #[cfg(not(windows))] fn is_resolved(entry: &[u8]) -> bool { @@ -7153,6 +7162,9 @@ impl CustomDir<'_> { /// Node's `insidePath`: false when `path.normalize(request)` starts with "..". fn request_stays_inside(request: &[u8]) -> bool { + if !strings::contains(request, b"..") { + return true; + } let mut depth: usize = 0; let mut first_starts_with_dot_dot = false; for segment in strings::split_any(request, Self::SEPARATORS) { From 1443052f15cd5811339cd4f4ea0d3fc52a237d9c Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 26 Oct 2026 15:01:51 +0000 Subject: [PATCH 07/15] resolver: keep the paths change to relative entries of a bare request The relative-request loop goes back to main's text. Absolute entries are used as written. A relative entry is resolved against the cwd with host rules, and a component the directory cache misreads is cut off. No entry installs a package before every entry was searched for it. --- src/resolver/resolver.rs | 308 ++++-------------- .../module-resolve-filename-paths.test.js | 197 ++++++++--- 2 files changed, 204 insertions(+), 301 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index a8c9b68f6504..0ac31b9ed50c 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -1890,14 +1890,22 @@ impl<'a> Resolver<'a> { if let Some(custom_paths) = self.custom_dir_paths { // @branchHint(.unlikely) bun_core::hint::cold(); + for custom_path in custom_paths { + let custom_utf8 = custom_path.to_utf8(); + match self.check_relative_path( + custom_utf8.slice(), + import_path, + kind, + global_cache, + ) { + ResultUnion::Success(res) => return ResultUnion::Success(res), + ResultUnion::Pending(p) => return ResultUnion::Pending(p), + ResultUnion::Failure(p) => return ResultUnion::Failure(p), + ResultUnion::NotFound => {} + } + } debug_assert!(!check_package); // always from JavaScript - // bail out after this since there isn't anywhere else to check - return self.check_relative_path_in_custom_dirs( - custom_paths, - import_path, - kind, - global_cache, - ); + return ResultUnion::NotFound; // bail out now since there isn't anywhere else to check } else { match self.check_relative_path(source_dir, import_path, kind, global_cache) { ResultUnion::Success(res) => return ResultUnion::Success(res), @@ -2061,164 +2069,29 @@ impl<'a> Resolver<'a> { rest.is_empty() || ResolvePath::is_sep_any(rest[rest.len() - 1]) } - /// Node's `path.resolve(entry)` for a `paths` entry. `buf` is taken only when that changes it. - fn custom_dir<'b>( - &self, - entry: &'b [u8], - buf: &'b mut Option, - ) -> Option> { + /// Node's `path.resolve(entry)` for a relative `paths` entry, and whether it was cut short. + fn custom_dir<'b>(&self, entry: &[u8], buf: &'b mut PathBuffer) -> Option<(&'b [u8], bool)> { #[cfg(windows)] - let path: &'b [u8] = if bun_paths::is_absolute(entry) { - entry - } else { - let buf = buf.get_or_insert_with(bun_paths::path_buffer_pool::get); - self.fs_ref().abs_buf_checked(&[entry], &mut buf[..])? - }; + let path: &'b [u8] = self.fs_ref().abs_buf_checked(&[entry], &mut buf[..])?; #[cfg(not(windows))] let path: &'b [u8] = { - if CustomDir::is_resolved(entry) { - return Some(CustomDir { - path: entry, - searchable_len: entry.len(), - }); - } - let cwd: &[u8] = if entry.first() == Some(&b'/') { - b"" - } else { - self.fs_ref().top_level_dir() - }; - let buf = buf.get_or_insert_with(bun_paths::path_buffer_pool::get); - if cwd.len() + entry.len() + 2 > buf.len() { - return None; - } - let joined = - bun_paths::join_string_buf(&mut buf[..], &[cwd, entry], bun_paths::Platform::Posix); - if joined.len() > 1 && joined.ends_with(b"/") { - &joined[..joined.len() - 1] - } else { - joined - } - }; - - let searchable_len = match strings::index_of_any(path, CustomDir::UNSEARCHABLE) { - None => path.len(), - Some(unsearchable) => { - #[cfg(windows)] - let root_len = bun_paths::windows_filesystem_root(path).len(); - #[cfg(not(windows))] - let root_len = 1; - if unsearchable < root_len { - return None; - } - strings::last_index_of_any(&path[..unsearchable], CustomDir::SEPARATORS) - .map_or(root_len, |separator| separator.max(root_len)) - } - }; - Some(CustomDir { - path, - searchable_len, - }) - } - - /// Node's `_stat(entry) === 1`. The OS walks each component, so `missing/..` is no directory. - fn custom_dir_entry_is_directory( - &self, - entry: &[u8], - buf: &mut Option, - ) -> bool { - // Node hands the entry to stat() as a C string. - let entry = match strings::index_of_char(entry, 0) { - Some(nul) => &entry[..nul as usize], - None => entry, + use ::bun_paths::resolve_path::{join_z_buf_checked, platform}; + let cwd = self.fs_ref().top_level_dir(); + join_z_buf_checked::(&mut buf[..], &[cwd, entry])?.as_bytes() }; - if entry.is_empty() { - return false; - } - let cwd: &[u8] = if bun_paths::is_absolute(entry) { - b"" - } else { - self.fs_ref().top_level_dir() + // The cache reads a NUL as the end of a path and, on POSIX, a backslash as a separator. + let misread: &[u8] = if cfg!(windows) { b"\0" } else { b"\\\0" }; + let Some(first) = strings::index_of_any(path, misread) else { + return Some((path, false)); }; - let buf = buf.get_or_insert_with(bun_paths::path_buffer_pool::get); - if cwd.len() + 1 + entry.len() >= buf.len() { - return false; - } - let mut len = 0; - if !cwd.is_empty() { - buf[..cwd.len()].copy_from_slice(cwd); - buf[cwd.len()] = SEP; - len = cwd.len() + 1; - } - buf[len..len + entry.len()].copy_from_slice(entry); - len += entry.len(); - buf[len] = 0; - bun_sys::directory_exists_at(FD::cwd(), bun_core::ZStr::from_buf(&buf[..], len)) - .unwrap_or(false) - } - - /// Node's `Module._findPath` over the `paths` entries, for a relative request. - #[cold] - #[inline(never)] - fn check_relative_path_in_custom_dirs( - &mut self, - custom_paths: &[bun_core::String], - import_path: &[u8], - kind: ast::ImportKind, - global_cache: GlobalCache, - ) -> ResultUnion { - let stays_inside = CustomDir::request_stays_inside(import_path); - let mut buf = None; - for custom_path in custom_paths { - let custom_utf8 = custom_path.to_utf8(); - let entry = custom_utf8.slice(); - let Some(dir) = self.custom_dir(entry, &mut buf) else { - continue; - }; - let result = if !dir.is_cut() { - let dir = dir.path; - let result = self.check_relative_path(dir, import_path, kind, global_cache); - // Node skips an entry that is not a directory when the request cannot leave it. - if stays_inside && !entry.is_empty() && !matches!(result, ResultUnion::NotFound) { - let is_directory = if cfg!(not(windows)) && CustomDir::has_parent_segment(entry) - { - self.custom_dir_entry_is_directory(entry, &mut buf) - } else { - matches!(self.dir_info_cached(dir), Ok(Some(_))) - }; - if !is_directory { - continue; - } - } - result - } else if stays_inside { - continue; - } else { - // A ".." request can step out of the components that were cut off. - let mut joined = bun_paths::path_buffer_pool::get(); - if dir.path.len() + import_path.len() + 3 > joined.len() { - continue; - } - let mut len = bun_paths::join_string_buf( - &mut joined[..], - &[dir.path, import_path], - bun_paths::Platform::AUTO, - ) - .len(); - if strings::index_of_any(&joined[..len], CustomDir::UNSEARCHABLE).is_some() { - continue; - } - if Self::import_path_names_directory(import_path) && joined[len - 1] != SEP { - joined[len] = SEP; - len += 1; - } - self.check_relative_path(&joined[..len], b"", kind, global_cache) - }; - match result { - ResultUnion::NotFound => {} - found => return found, - } - } - ResultUnion::NotFound + #[cfg(windows)] + let root_len = bun_paths::windows_filesystem_root(path).len(); + #[cfg(not(windows))] + let root_len = 1; + let separators: &[u8] = if cfg!(windows) { b"/\\" } else { b"/" }; + let cut = strings::last_index_of_any(&path[..first], separators) + .map_or(root_len, |separator| separator.max(root_len)); + Some((&path[..cut], true)) } /// Node's search of `Module._nodeModulePaths(entry)` per `paths` entry, for a bare request. @@ -2231,26 +2104,30 @@ impl<'a> Resolver<'a> { kind: ast::ImportKind, global_cache: GlobalCache, ) -> ResultUnion { - let mut buf = None; - for custom_path in custom_paths { - let custom_utf8 = custom_path.to_utf8(); - let Some(dir) = self.custom_dir(custom_utf8.slice(), &mut buf) else { - continue; - }; - // Nothing below the cut was searched, so a miss must not start an install. - let global_cache = if dir.is_cut() { - GlobalCache::disable - } else { - global_cache - }; - match self.check_package_path( - &dir.path[..dir.searchable_len], - import_path, - kind, - global_cache, - ) { - ResultUnion::NotFound => {} - found => return found, + // No entry installs a package before every entry was searched for it. + for cache in [GlobalCache::disable, global_cache] { + for custom_path in custom_paths { + let custom_utf8 = custom_path.to_utf8(); + let entry = custom_utf8.slice(); + let mut buf; + let dir = if bun_paths::is_absolute(entry) { + entry + } else { + buf = bun_paths::path_buffer_pool::get(); + match self.custom_dir(entry, &mut buf) { + // Nothing below the cut was searched, so a miss there installs nothing. + Some((_, true)) if cache != GlobalCache::disable => continue, + Some((dir, _)) => dir, + None => continue, + } + }; + match self.check_package_path(dir, import_path, kind, cache) { + ResultUnion::NotFound => {} + found => return found, + } + } + if global_cache == GlobalCache::disable { + break; } } ResultUnion::NotFound @@ -7117,77 +6994,6 @@ fn rewritten_file_extensions( } } -/// A `paths` entry of `require.resolve()` as Node's `path.resolve(entry)` reads it. -struct CustomDir<'a> { - path: &'a [u8], - /// `path[..searchable_len]` ends before the first component that holds an `UNSEARCHABLE` byte. - searchable_len: usize, -} - -impl CustomDir<'_> { - /// The directory cache reads a NUL as the end of a path and a POSIX backslash as a separator. - const UNSEARCHABLE: &'static [u8] = if cfg!(windows) { b"\0" } else { b"\\\0" }; - const SEPARATORS: &'static [u8] = if cfg!(windows) { b"/\\" } else { b"/" }; - - fn is_cut(&self) -> bool { - self.searchable_len < self.path.len() - } - - fn has_parent_segment(entry: &[u8]) -> bool { - strings::contains(entry, b"..") - && strings::split_any(entry, Self::SEPARATORS).any(|segment| segment == b"..") - } - - /// Whether `path.resolve(entry)` returns `entry` unchanged and no byte of it is unsearchable. - #[cfg(not(windows))] - fn is_resolved(entry: &[u8]) -> bool { - if entry.first() != Some(&b'/') { - return false; - } - let mut segment_start = 1; - for (i, &byte) in entry.iter().enumerate().skip(1) { - match byte { - b'\\' | 0 => return false, - b'/' => { - if matches!(&entry[segment_start..i], b"" | b"." | b"..") { - return false; - } - segment_start = i + 1; - } - _ => {} - } - } - entry.len() == 1 || !matches!(&entry[segment_start..], b"" | b"." | b"..") - } - - /// Node's `insidePath`: false when `path.normalize(request)` starts with "..". - fn request_stays_inside(request: &[u8]) -> bool { - if !strings::contains(request, b"..") { - return true; - } - let mut depth: usize = 0; - let mut first_starts_with_dot_dot = false; - for segment in strings::split_any(request, Self::SEPARATORS) { - match segment { - b"" | b"." => {} - b".." => { - if depth == 0 { - return false; - } - depth -= 1; - } - _ => { - if depth == 0 { - first_starts_with_dot_dot = segment.starts_with(b".."); - } - depth += 1; - } - } - } - depth == 0 || !first_starts_with_dot_dot - } -} - pub struct Dirname; impl Dirname { diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index a96446f5efda..031bb9f79af1 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -187,30 +187,60 @@ test("require.resolve with relative path and options.paths (Next.js use case)", }); test("Module._resolveFilename throws ERR_INVALID_ARG_TYPE if options.paths is not an array", () => { - // The request is not a builtin id: Node returns a builtin id before it reads `options.paths`. - const fakeParent = new Module("/some/other/directory/file.js"); + const { path: dir, cleanup } = createTempDir("module-resolve-paths-not-array", { + "node_modules/resolve-test-pkg/index.js": "", + }); - // Test with string (which is iterable but not an array) - expect(() => { - Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: "/some/path" }); - }).toThrow(); + try { + // The parent can resolve the package, so only the check of `options.paths` can throw. + const fakeParent = new Module(join(dir, "file.js")); + fakeParent.filename = join(dir, "file.js"); + fakeParent.paths = Module._nodeModulePaths(dir); + expect(Module._resolveFilename("resolve-test-pkg", fakeParent)).toBe( + resolve(dir, "node_modules/resolve-test-pkg/index.js"), + ); + + // Test with string (which is iterable but not an array) + expect(() => { + Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: "/some/path" }); + }).toThrow(); - // Test with Set (which is iterable but not an array) - expect(() => { - Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: new Set(["/some/path"]) }); - }).toThrow(); + // Test with Set (which is iterable but not an array) + expect(() => { + Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: new Set(["/some/path"]) }); + }).toThrow(); - // Test with object (not iterable) - expect(() => { - Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: { 0: "/some/path" } }); - }).toThrow(); + // Test with object (not iterable) + expect(() => { + Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: { 0: "/some/path" } }); + }).toThrow(); - expect(Module._resolveFilename("path", fakeParent, false, { paths: "/some/path" })).toBe("path"); + // Node returns a builtin id before it reads `options.paths`. + expect(Module._resolveFilename("path", fakeParent, false, { paths: "/some/path" })).toBe("path"); + } finally { + cleanup(); + } }); -// Node turns each `options.paths` entry into a directory with path.resolve(): a relative entry is -// relative to process.cwd(), and only the host's separators separate. Each resolve runs in a child -// process so that the cwd is the fixture and the resolver starts with empty caches. +test("Module._resolveFilename reads options.paths one entry at a time for a relative request", () => { + const { path: dir, cleanup } = createTempDir("module-resolve-paths-lazy", { + "target.js": "", + }); + + try { + // Node stops at the entry that has the file and never reads the one after it. + const fakeParent = new Module("/some/other/directory/file.js"); + expect(Module._resolveFilename("./target.js", fakeParent, false, { paths: [dir, 0] })).toBe( + resolve(dir, "target.js"), + ); + } finally { + cleanup(); + } +}); + +// Node turns each `options.paths` entry into a directory with path.resolve(), so a relative entry +// is relative to process.cwd() and not to the calling file. The probe is in `sub/` and runs with +// the fixture root as the cwd, in a child process so that the resolver starts with empty caches. const probeSource = ` const Module = require("node:module"); const path = require("node:path"); @@ -243,26 +273,46 @@ console.log(JSON.stringify(results)); function resolveRowsInChild(order) { const isWindows = process.platform === "win32"; const files = { - "probe.cjs": probeSource, + "sub/probe.cjs": probeSource, // A node_modules directory at the root also keeps Bun's auto-install off. "node_modules/plugroot/index.js": "", + "node_modules/plugboth/index.js": "", "plugins/node_modules/plug/index.js": "", + "plugins/node_modules/plugboth/index.js": "", "plugins/file.js": "", + "deps/node_modules/dep/package.json": JSON.stringify({ name: "dep", main: "index.js" }), + "deps/node_modules/dep/index.js": "", + "deps/node_modules/vue-router/package.json": JSON.stringify({ + name: "vue-router", + exports: { "./volar/sfc-route-blocks": "./dist/volar/sfc-route-blocks.cjs" }, + }), + "deps/node_modules/vue-router/dist/volar/sfc-route-blocks.cjs": "", + "deps/node_modules/@scope/pkg/package.json": JSON.stringify({ name: "@scope/pkg", main: "lib/main.js" }), + "deps/node_modules/@scope/pkg/lib/main.js": "", }; if (!isWindows) { - files["back/slash/node_modules/plugc/index.js"] = ""; files["C:/plugins/node_modules/plugd/index.js"] = ""; } const { path: dir, cleanup } = createTempDir("resolve-paths-entries", files); const plug = "plugins/node_modules/plug/index.js"; const plugroot = "node_modules/plugroot/index.js"; + const dep = "deps/node_modules/dep/index.js"; const file = "plugins/file.js"; const missing = "MODULE_NOT_FOUND"; // [request, paths, expected, directory to chdir() into first] const rows = [ - // A bare request searches node_modules from the entry upward. - ["plug", ["./plugins"], plug], + // https://github.com/oven-sh/bun/issues/45706 + ["dep", ["./deps"], dep], + ["dep", ["../deps"], missing], + ["dep", [join(dir, "deps")], dep], + ["vue-router/volar/sfc-route-blocks", ["./deps"], "deps/node_modules/vue-router/dist/volar/sfc-route-blocks.cjs"], + ["@scope/pkg", ["deps"], "deps/node_modules/@scope/pkg/lib/main.js"], + // A package at two levels: the copy under the entry is the one to find. + ["plugboth", ["./plugins"], "plugins/node_modules/plugboth/index.js"], + ["plugboth", ["plugins"], "plugins/node_modules/plugboth/index.js"], + ["plugboth", ["nowhere"], "node_modules/plugboth/index.js"], + // The search starts at the entry and goes up. ["plug", ["plugins"], plug], ["plug", ["plugins/"], plug], ["plug", ["plugins/../plugins"], plug], @@ -272,17 +322,13 @@ function resolveRowsInChild(order) { ["plugroot", [""], plugroot], ["plugroot", ["."], plugroot], ["plugroot", ["./nowhere/deeper"], plugroot], + ["plugroot", ["nowhere/"], plugroot], ["plug", ["."], plug, "plugins"], ["plugroot", [".."], plugroot, "plugins"], - // A relative request is joined to the entry. The entry must be a directory unless the - // request leaves it. + // A relative request is joined to the entry. ["./node_modules/plug/index.js", ["plugins"], plug], - ["./node_modules/plug/index.js", ["./plugins"], plug], - ["./node_modules/plug/index.js", [join(dir, "plugins")], plug], - ["./node_modules/plug/index.js", ["nowhere", "plugins"], plug], ["./file.js", ["plugins"], file], ["./file.js", ["nowhere"], missing], - [".", ["plugins/file.js"], missing], ["../plugins/file.js", ["nowhere"], file], // A builtin id is resolved before `paths` is read. Any other bare request needs strings. ["node:fs", [0], "node:fs"], @@ -292,28 +338,19 @@ function resolveRowsInChild(order) { if (isWindows) { rows.push(["plug", ["plugins\\"], plug], ["plug", [".\\plugins"], plug]); } else { - const tooLong = Buffer.alloc(5000, "a").toString(); rows.push( - ["plug", [dir + "/nope/../plugins"], plug], // A backslash and a drive letter are file name characters on POSIX. ["plug", ["plugins\\"], missing], ["plug", [".\\plugins"], missing], - ["plug", [dir + "/plugins\\"], missing], ["plugroot", ["plugins\\"], plugroot], - ["plugc", ["back\\slash"], missing], + ["plugroot", ["./plugins\\"], plugroot], ["plugd", ["C:/plugins"], "C:/plugins/node_modules/plugd/index.js"], ["plugd", ["C:\\plugins"], missing], - ["./node_modules/plug/index.js", ["plugins\\"], missing], - ["./node_modules/plug/index.js", [".\\plugins"], missing], - ["./node_modules/plugc/index.js", ["back\\slash"], missing], - ["./node_modules/plugd/index.js", ["C:/plugins"], "C:/plugins/node_modules/plugd/index.js"], - ["../plugins/file.js", ["plugins\\"], file], - // The OS does not collapse "nowhere/..": the directory does not exist. - ["./node_modules/plugroot/index.js", ["nowhere/.."], missing], ["plug", ["plugins\0x"], missing], - ["./index.js", [dir + "/plugins/node_modules/plug\0"], missing], - ["plug", [tooLong], missing], - ["./file.js", [tooLong], missing], + ["plugroot", ["plugins\0x"], plugroot], + // Longer than PATH_MAX as written, short once resolved. + ["plug", [Buffer.alloc(4200, "./").toString() + "plugins"], plug], + ["plug", [Buffer.alloc(5000, "a").toString()], missing], ); } @@ -324,21 +361,28 @@ function resolveRowsInChild(order) { ); const { stdout, stderr, status } = spawnSync( process.execPath, - isBun ? ["--no-install", "probe.cjs", order] : ["probe.cjs", order], + isBun ? ["--no-install", "sub/probe.cjs", order] : ["sub/probe.cjs", order], { cwd: dir, env: childEnv, encoding: "utf8" }, ); let results; try { results = JSON.parse(stdout); } catch { - results = { stdout, stderr }; + results = null; } - expect(results).toEqual( - rows.map(([, , expected]) => ({ - "require.resolve": expected, - "Module._resolveFilename": expected, - "createRequire().resolve": expected, - })), + // One line per row and entry point, so that a failure names the row. + const shorten = entry => + typeof entry !== "string" ? entry : entry.length > 80 ? `<${entry.length} bytes>` : entry.replace(dir, ""); + const lines = valueOf => + rows.flatMap(([request, paths, , chdir], i) => + ["require.resolve", "Module._resolveFilename", "createRequire().resolve"].map( + name => + `${name}(${JSON.stringify(request)}, { paths: ${JSON.stringify(paths.map(shorten))} })` + + `${chdir ? ` in ${chdir}` : ""} => ${valueOf(i, name)}`, + ), + ); + expect(results === null ? { stdout, stderr } : lines((i, name) => results[i][name])).toEqual( + lines(i => rows[i][2]), ); expect(status).toBe(0); } finally { @@ -353,3 +397,56 @@ test("options.paths entries are resolved like path.resolve() does", () => { test("options.paths entries resolve the same in the reverse call order", () => { resolveRowsInChild("reverse"); }); + +if (isBun) { + // Nothing above the project has a node_modules directory, so Bun's auto-install is on. The + // first entry is outside the project and misses. The second entry has the package. + test("options.paths: no entry installs a package before every entry was searched", async () => { + const requests = []; + const registry = Bun.serve({ + port: 0, + fetch(request) { + requests.push(new URL(request.url).pathname); + return new Response("not found", { status: 404 }); + }, + }); + const { path: dir, cleanup } = createTempDir("resolve-paths-install-order", { + "a/b/project/plugins/node_modules/no-deps/index.js": "", + "a/b/project/bunfig.toml": `[install]\nregistry = "http://127.0.0.1:${registry.port}/"\n`, + "a/b/project/index.cjs": ` + const path = require("node:path"); + const resolved = require.resolve("no-deps", { paths: ["../..", "./plugins"] }); + console.log(path.relative(process.cwd(), resolved).split(path.sep).join("/")); + // On POSIX this entry names a directory that does not exist. The search goes on above + // it, and a miss there installs nothing. + if (process.platform !== "win32") { + try { + require.resolve("no-deps-2", { paths: ["plugins\\\\"] }); + } catch (error) { + console.log(error.code); + } + } + `, + }); + + try { + const proc = Bun.spawn({ + cmd: [process.execPath, "index.cjs"], + cwd: join(dir, "a", "b", "project"), + env: { ...childEnv, BUN_INSTALL_CACHE_DIR: join(dir, "cache") }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout, stderr, requests }).toEqual({ + stdout: "plugins/node_modules/no-deps/index.js\n" + (process.platform === "win32" ? "" : "MODULE_NOT_FOUND\n"), + stderr: "", + requests: [], + }); + expect(exitCode).toBe(0); + } finally { + registry.stop(true); + cleanup(); + } + }); +} From a45f95715fe12b62b9a6e86c6974add7b9ffd452 Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 26 Oct 2026 15:36:16 +0000 Subject: [PATCH 08/15] resolver: search every paths entry before one of several installs a package A call with one entry keeps the single search that main does. --- src/resolver/resolver.rs | 23 +++++++++++-------- .../module-resolve-filename-paths.test.js | 19 +++++++++------ 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 0ac31b9ed50c..f5eb503d5ae7 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -2104,21 +2104,27 @@ impl<'a> Resolver<'a> { kind: ast::ImportKind, global_cache: GlobalCache, ) -> ResultUnion { - // No entry installs a package before every entry was searched for it. - for cache in [GlobalCache::disable, global_cache] { + // With several entries, none installs a package before all of them were searched. + let passes: &[GlobalCache] = + if custom_paths.len() > 1 && global_cache != GlobalCache::disable { + &[GlobalCache::disable, global_cache] + } else { + &[global_cache] + }; + for (pass, &cache) in passes.iter().enumerate() { for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8(); let entry = custom_utf8.slice(); let mut buf; - let dir = if bun_paths::is_absolute(entry) { - entry + let (dir, cache) = if bun_paths::is_absolute(entry) { + (entry, cache) } else { buf = bun_paths::path_buffer_pool::get(); match self.custom_dir(entry, &mut buf) { + Some((dir, false)) => (dir, cache), // Nothing below the cut was searched, so a miss there installs nothing. - Some((_, true)) if cache != GlobalCache::disable => continue, - Some((dir, _)) => dir, - None => continue, + Some((dir, true)) if pass == 0 => (dir, GlobalCache::disable), + _ => continue, } }; match self.check_package_path(dir, import_path, kind, cache) { @@ -2126,9 +2132,6 @@ impl<'a> Resolver<'a> { found => return found, } } - if global_cache == GlobalCache::disable { - break; - } } ResultUnion::NotFound } diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index 031bb9f79af1..a9bb96dfc088 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -417,13 +417,16 @@ if (isBun) { const path = require("node:path"); const resolved = require.resolve("no-deps", { paths: ["../..", "./plugins"] }); console.log(path.relative(process.cwd(), resolved).split(path.sep).join("/")); - // On POSIX this entry names a directory that does not exist. The search goes on above - // it, and a miss there installs nothing. + // On POSIX the first entry names a directory that does not exist. The search goes on + // above it, and a miss there installs nothing. "plugins" has a node_modules directory, + // so a miss there installs nothing either. if (process.platform !== "win32") { - try { - require.resolve("no-deps-2", { paths: ["plugins\\\\"] }); - } catch (error) { - console.log(error.code); + for (const paths of [["plugins\\\\"], ["plugins\\\\", "plugins"]]) { + try { + require.resolve("no-deps-2", { paths }); + } catch (error) { + console.log(error.code); + } } } `, @@ -439,7 +442,9 @@ if (isBun) { }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect({ stdout, stderr, requests }).toEqual({ - stdout: "plugins/node_modules/no-deps/index.js\n" + (process.platform === "win32" ? "" : "MODULE_NOT_FOUND\n"), + stdout: + "plugins/node_modules/no-deps/index.js\n" + + (process.platform === "win32" ? "" : "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\n"), stderr: "", requests: [], }); From 81833593327a9238ba3c1a698e77205ba78ec2fc Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 26 Oct 2026 17:12:18 +0000 Subject: [PATCH 09/15] resolver: keep --install=force to one search of the paths entries The force mode never reads node_modules, so the search that installs nothing does not apply to it. The tests assert the error code of a non-array paths and spawn bun through the harness. --- src/resolver/resolver.rs | 19 ++- .../module-resolve-filename-paths.test.js | 144 +++++++++++------- 2 files changed, 103 insertions(+), 60 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index f5eb503d5ae7..877de63eea10 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -2104,13 +2104,18 @@ impl<'a> Resolver<'a> { kind: ast::ImportKind, global_cache: GlobalCache, ) -> ResultUnion { + // `force` never reads node_modules, so it has no search that installs nothing. + let local_only = if global_cache == GlobalCache::force { + global_cache + } else { + GlobalCache::disable + }; // With several entries, none installs a package before all of them were searched. - let passes: &[GlobalCache] = - if custom_paths.len() > 1 && global_cache != GlobalCache::disable { - &[GlobalCache::disable, global_cache] - } else { - &[global_cache] - }; + let passes: &[GlobalCache] = if custom_paths.len() > 1 && local_only != global_cache { + &[local_only, global_cache] + } else { + &[global_cache] + }; for (pass, &cache) in passes.iter().enumerate() { for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8(); @@ -2123,7 +2128,7 @@ impl<'a> Resolver<'a> { match self.custom_dir(entry, &mut buf) { Some((dir, false)) => (dir, cache), // Nothing below the cut was searched, so a miss there installs nothing. - Some((dir, true)) if pass == 0 => (dir, GlobalCache::disable), + Some((dir, true)) if pass == 0 => (dir, local_only), _ => continue, } }; diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index a9bb96dfc088..783272b53638 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -9,10 +9,13 @@ import { dirname, join, resolve } from "path"; const isBun = typeof Bun !== "undefined"; let test, expect; let childEnv = process.env; +let childExe = process.execPath; if (isBun) { ({ test, expect } = await import("bun:test")); - ({ bunEnv: childEnv } = await import("harness")); + const harness = await import("harness"); + childEnv = harness.bunEnv; + childExe = harness.bunExe(); } else { // Node.js const { createRequire } = await import("module"); @@ -200,20 +203,22 @@ test("Module._resolveFilename throws ERR_INVALID_ARG_TYPE if options.paths is no resolve(dir, "node_modules/resolve-test-pkg/index.js"), ); - // Test with string (which is iterable but not an array) - expect(() => { - Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: "/some/path" }); - }).toThrow(); - - // Test with Set (which is iterable but not an array) - expect(() => { - Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: new Set(["/some/path"]) }); - }).toThrow(); + // Node throws ERR_INVALID_ARG_VALUE here. Bun throws ERR_INVALID_ARG_TYPE. + const notAnArray = isBun ? "ERR_INVALID_ARG_TYPE" : "ERR_INVALID_ARG_VALUE"; + const codeOf = paths => { + try { + return Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths }); + } catch (error) { + return error.code; + } + }; - // Test with object (not iterable) - expect(() => { - Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: { 0: "/some/path" } }); - }).toThrow(); + // A string and a Set are iterable but not arrays. The object is not iterable. + expect([codeOf("/some/path"), codeOf(new Set(["/some/path"])), codeOf({ 0: "/some/path" })]).toEqual([ + notAnArray, + notAnArray, + notAnArray, + ]); // Node returns a builtin id before it reads `options.paths`. expect(Module._resolveFilename("path", fakeParent, false, { paths: "/some/path" })).toBe("path"); @@ -360,7 +365,7 @@ function resolveRowsInChild(order) { JSON.stringify(rows.map(([request, paths, , chdir]) => [request, paths, chdir])), ); const { stdout, stderr, status } = spawnSync( - process.execPath, + childExe, isBun ? ["--no-install", "sub/probe.cjs", order] : ["sub/probe.cjs", order], { cwd: dir, env: childEnv, encoding: "utf8" }, ); @@ -399,9 +404,10 @@ test("options.paths entries resolve the same in the reverse call order", () => { }); if (isBun) { + // Runs `source` in a project that has the package `no-deps` only under plugins/node_modules. // Nothing above the project has a node_modules directory, so Bun's auto-install is on. The - // first entry is outside the project and misses. The second entry has the package. - test("options.paths: no entry installs a package before every entry was searched", async () => { + // registry answers 404 and records each request. + async function runInProject(args, source) { const requests = []; const registry = Bun.serve({ port: 0, @@ -410,48 +416,80 @@ if (isBun) { return new Response("not found", { status: 404 }); }, }); - const { path: dir, cleanup } = createTempDir("resolve-paths-install-order", { - "a/b/project/plugins/node_modules/no-deps/index.js": "", - "a/b/project/bunfig.toml": `[install]\nregistry = "http://127.0.0.1:${registry.port}/"\n`, - "a/b/project/index.cjs": ` - const path = require("node:path"); - const resolved = require.resolve("no-deps", { paths: ["../..", "./plugins"] }); - console.log(path.relative(process.cwd(), resolved).split(path.sep).join("/")); - // On POSIX the first entry names a directory that does not exist. The search goes on - // above it, and a miss there installs nothing. "plugins" has a node_modules directory, - // so a miss there installs nothing either. - if (process.platform !== "win32") { - for (const paths of [["plugins\\\\"], ["plugins\\\\", "plugins"]]) { + try { + const { path: dir, cleanup } = createTempDir("resolve-paths-install", { + "a/b/project/plugins/node_modules/no-deps/index.js": "", + "a/b/project/bunfig.toml": `[install]\nregistry = "http://127.0.0.1:${registry.port}/"\n`, + "a/b/project/index.cjs": ` + const path = require("node:path"); + const resolve = (request, paths) => { try { - require.resolve("no-deps-2", { paths }); + return path.relative(process.cwd(), require.resolve(request, { paths })).split(path.sep).join("/"); } catch (error) { - console.log(error.code); + return error.code; } - } - } - `, - }); - - try { - const proc = Bun.spawn({ - cmd: [process.execPath, "index.cjs"], - cwd: join(dir, "a", "b", "project"), - env: { ...childEnv, BUN_INSTALL_CACHE_DIR: join(dir, "cache") }, - stdout: "pipe", - stderr: "pipe", + }; + ${source} + `, }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect({ stdout, stderr, requests }).toEqual({ - stdout: - "plugins/node_modules/no-deps/index.js\n" + - (process.platform === "win32" ? "" : "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\n"), - stderr: "", - requests: [], - }); - expect(exitCode).toBe(0); + try { + const proc = Bun.spawn({ + cmd: [childExe, ...args, "index.cjs"], + cwd: join(dir, "a", "b", "project"), + env: { ...childEnv, BUN_INSTALL_CACHE_DIR: join(dir, "cache") }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode, requests }; + } finally { + cleanup(); + } } finally { registry.stop(true); - cleanup(); } + } + + test("options.paths: no entry installs a package before every entry was searched", async () => { + // The first entry is outside the project and misses. The second entry has the package. + // On POSIX "plugins\\" names a directory that does not exist. The search goes on above it, + // and a miss there installs nothing. "plugins" has a node_modules directory, so a miss + // there installs nothing either. + const result = await runInProject( + [], + ` + console.log(resolve("no-deps", ["../..", "./plugins"])); + if (process.platform !== "win32") { + console.log(resolve("no-deps-2", ["plugins\\\\"])); + console.log(resolve("no-deps-2", ["plugins\\\\", "plugins"])); + } + `, + ); + expect(result).toEqual({ + stdout: + "plugins/node_modules/no-deps/index.js\n" + + (process.platform === "win32" ? "" : "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\n"), + stderr: "", + exitCode: 0, + requests: [], + }); + }); + + test("options.paths: --install=force does not read the node_modules of an entry", async () => { + const result = await runInProject( + ["--install=force"], + ` + console.log(resolve("no-deps", ["./plugins"])); + console.log(resolve("no-deps", ["./plugins", "."])); + `, + ); + // The registry has no such package, so both calls miss. A read of plugins/node_modules + // would find the local copy. + expect(result).toEqual({ + stdout: "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\n", + stderr: "", + exitCode: 0, + requests: ["/no-deps"], + }); }); } From 03f231a88f7c599256474beb158efa5bcd3edddb Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 26 Oct 2026 18:20:54 +0000 Subject: [PATCH 10/15] resolver: a relative paths entry outside the cwd installs nothing A relative entry of a bare request is searched once, in order. A miss installs a package only when the entry is in the cwd. An entry above or next to the cwd is searched with installs off, so a miss there does not ask the registry and does not create the package manager outside the project. With --install=force such an entry is skipped, because that mode does not read node_modules. --- src/resolver/resolver.rs | 77 ++++++++----------- .../module-resolve-filename-paths.test.js | 47 ++++++----- 2 files changed, 62 insertions(+), 62 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 877de63eea10..992d602fe92b 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -2069,29 +2069,32 @@ impl<'a> Resolver<'a> { rest.is_empty() || ResolvePath::is_sep_any(rest[rest.len() - 1]) } - /// Node's `path.resolve(entry)` for a relative `paths` entry, and whether it was cut short. + /// Node's `path.resolve(entry)` for a relative `paths` entry, and whether a miss there may install. fn custom_dir<'b>(&self, entry: &[u8], buf: &'b mut PathBuffer) -> Option<(&'b [u8], bool)> { + use ::bun_paths::resolve_path::{ParentEqual, is_parent_or_equal}; + let cwd = self.fs_ref().top_level_dir(); #[cfg(windows)] let path: &'b [u8] = self.fs_ref().abs_buf_checked(&[entry], &mut buf[..])?; #[cfg(not(windows))] let path: &'b [u8] = { use ::bun_paths::resolve_path::{join_z_buf_checked, platform}; - let cwd = self.fs_ref().top_level_dir(); join_z_buf_checked::(&mut buf[..], &[cwd, entry])?.as_bytes() }; // The cache reads a NUL as the end of a path and, on POSIX, a backslash as a separator. let misread: &[u8] = if cfg!(windows) { b"\0" } else { b"\\\0" }; - let Some(first) = strings::index_of_any(path, misread) else { - return Some((path, false)); - }; - #[cfg(windows)] - let root_len = bun_paths::windows_filesystem_root(path).len(); - #[cfg(not(windows))] - let root_len = 1; - let separators: &[u8] = if cfg!(windows) { b"/\\" } else { b"/" }; - let cut = strings::last_index_of_any(&path[..first], separators) - .map_or(root_len, |separator| separator.max(root_len)); - Some((&path[..cut], true)) + if let Some(first) = strings::index_of_any(path, misread) { + #[cfg(windows)] + let root_len = bun_paths::windows_filesystem_root(path).len(); + #[cfg(not(windows))] + let root_len = 1; + let separators: &[u8] = if cfg!(windows) { b"/\\" } else { b"/" }; + let cut = strings::last_index_of_any(&path[..first], separators) + .map_or(root_len, |separator| separator.max(root_len)); + return Some((&path[..cut], false)); + } + // A miss outside the cwd says nothing about the project, so it installs nothing. + let in_cwd = is_parent_or_equal(cwd, path) != ParentEqual::Unrelated; + Some((path, in_cwd)) } /// Node's search of `Module._nodeModulePaths(entry)` per `paths` entry, for a bare request. @@ -2104,38 +2107,26 @@ impl<'a> Resolver<'a> { kind: ast::ImportKind, global_cache: GlobalCache, ) -> ResultUnion { - // `force` never reads node_modules, so it has no search that installs nothing. - let local_only = if global_cache == GlobalCache::force { - global_cache - } else { - GlobalCache::disable - }; - // With several entries, none installs a package before all of them were searched. - let passes: &[GlobalCache] = if custom_paths.len() > 1 && local_only != global_cache { - &[local_only, global_cache] - } else { - &[global_cache] - }; - for (pass, &cache) in passes.iter().enumerate() { - for custom_path in custom_paths { - let custom_utf8 = custom_path.to_utf8(); - let entry = custom_utf8.slice(); - let mut buf; - let (dir, cache) = if bun_paths::is_absolute(entry) { - (entry, cache) - } else { - buf = bun_paths::path_buffer_pool::get(); - match self.custom_dir(entry, &mut buf) { - Some((dir, false)) => (dir, cache), - // Nothing below the cut was searched, so a miss there installs nothing. - Some((dir, true)) if pass == 0 => (dir, local_only), - _ => continue, + for custom_path in custom_paths { + let custom_utf8 = custom_path.to_utf8(); + let entry = custom_utf8.slice(); + let mut buf; + let (dir, cache) = if bun_paths::is_absolute(entry) { + (entry, global_cache) + } else { + buf = bun_paths::path_buffer_pool::get(); + match self.custom_dir(entry, &mut buf) { + Some((dir, true)) => (dir, global_cache), + // `force` never reads node_modules, so it has no search that installs nothing. + Some((dir, false)) if global_cache != GlobalCache::force => { + (dir, GlobalCache::disable) } - }; - match self.check_package_path(dir, import_path, kind, cache) { - ResultUnion::NotFound => {} - found => return found, + _ => continue, } + }; + match self.check_package_path(dir, import_path, kind, cache) { + ResultUnion::NotFound => {} + found => return found, } } ResultUnion::NotFound diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index 783272b53638..de914643a000 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -404,9 +404,9 @@ test("options.paths entries resolve the same in the reverse call order", () => { }); if (isBun) { - // Runs `source` in a project that has the package `no-deps` only under plugins/node_modules. - // Nothing above the project has a node_modules directory, so Bun's auto-install is on. The - // registry answers 404 and records each request. + // Runs `source` with `a/b/project` as the cwd. No directory from there up to the root has a + // node_modules directory, so Bun's auto-install is on. `a/b/modules` has one, so it is off there. + // The registry answers 404 and records each request. async function runInProject(args, source) { const requests = []; const registry = Bun.serve({ @@ -419,7 +419,7 @@ if (isBun) { try { const { path: dir, cleanup } = createTempDir("resolve-paths-install", { "a/b/project/plugins/node_modules/no-deps/index.js": "", - "a/b/project/bunfig.toml": `[install]\nregistry = "http://127.0.0.1:${registry.port}/"\n`, + "a/b/modules/node_modules/local-dep/index.js": "", "a/b/project/index.cjs": ` const path = require("node:path"); const resolve = (request, paths) => { @@ -436,7 +436,7 @@ if (isBun) { const proc = Bun.spawn({ cmd: [childExe, ...args, "index.cjs"], cwd: join(dir, "a", "b", "project"), - env: { ...childEnv, BUN_INSTALL_CACHE_DIR: join(dir, "cache") }, + env: { ...childEnv, BUN_CONFIG_REGISTRY: registry.url.href, BUN_INSTALL_CACHE_DIR: join(dir, "cache") }, stdout: "pipe", stderr: "pipe", }); @@ -450,28 +450,35 @@ if (isBun) { } } - test("options.paths: no entry installs a package before every entry was searched", async () => { - // The first entry is outside the project and misses. The second entry has the package. - // On POSIX "plugins\\" names a directory that does not exist. The search goes on above it, - // and a miss there installs nothing. "plugins" has a node_modules directory, so a miss - // there installs nothing either. + test("options.paths: only a relative entry in the cwd installs a package", async () => { + const isPosix = process.platform !== "win32"; const result = await runInProject( [], ` + // "../.." misses and is outside the cwd. "./plugins" has the package. console.log(resolve("no-deps", ["../..", "./plugins"])); - if (process.platform !== "win32") { - console.log(resolve("no-deps-2", ["plugins\\\\"])); - console.log(resolve("no-deps-2", ["plugins\\\\", "plugins"])); - } + // On POSIX "plugins\\\\" names a directory that does not exist, and the search goes on above it. + if (${isPosix}) console.log(resolve("no-deps-2", ["plugins\\\\"]), resolve("no-deps-2", ["plugins\\\\", "plugins"])); + // A project with a node_modules directory looks for an optional package that is absent. + process.chdir("../modules"); + console.log(resolve("local-dep", ["."]), resolve("no-deps-3", ["../..", "."])); + // "../project-2" is next to the cwd, not in it. + process.chdir("../project"); + console.log(resolve("no-deps-4", ["../project-2"])); + // An entry in the cwd is the same as its absolute form. + console.log(resolve("no-deps-5", ["."]), resolve("no-deps-6", [process.cwd()])); `, ); expect(result).toEqual({ stdout: "plugins/node_modules/no-deps/index.js\n" + - (process.platform === "win32" ? "" : "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\n"), + (isPosix ? "MODULE_NOT_FOUND MODULE_NOT_FOUND\n" : "") + + "node_modules/local-dep/index.js MODULE_NOT_FOUND\n" + + "MODULE_NOT_FOUND\n" + + "MODULE_NOT_FOUND MODULE_NOT_FOUND\n", stderr: "", exitCode: 0, - requests: [], + requests: ["/no-deps-5", "/no-deps-6"], }); }); @@ -481,12 +488,14 @@ if (isBun) { ` console.log(resolve("no-deps", ["./plugins"])); console.log(resolve("no-deps", ["./plugins", "."])); + console.log(resolve("local-dep", ["../modules"])); `, ); - // The registry has no such package, so both calls miss. A read of plugins/node_modules - // would find the local copy. + // The registry has no such package, so the calls miss. A read of plugins/node_modules or of + // ../modules/node_modules would find the local copy. "../modules" is outside the cwd, so it + // installs nothing. expect(result).toEqual({ - stdout: "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\n", + stdout: "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\nMODULE_NOT_FOUND\n", stderr: "", exitCode: 0, requests: ["/no-deps"], From 722c983829d53109c1b280700456fb33b3e99222 Mon Sep 17 00:00:00 2001 From: robobun Date: Tue, 27 Oct 2026 01:52:17 +0000 Subject: [PATCH 11/15] resolver: a relative paths entry installs only through one search from the cwd A relative entry of a bare request is searched with installs off. When every entry misses and a relative entry is in the cwd, the search from the cwd runs once, and only that search installs. So a package on disk under a later entry wins over the registry, the package manager is created from the project of the cwd, and a refusal to install does not hide a later entry. Module._resolveFilename converts the request once, so a request object gets the same entry check as a string. The entry check of Module._resolveFilename and require.resolve names the entry as Node does, "paths[0]". check_package_path asserts that its directory is absolute. --- src/jsc/bindings/ImportMetaObject.cpp | 3 +- src/jsc/modules/NodeModuleModule.cpp | 15 +- src/resolver/resolver.rs | 34 +-- .../module-resolve-filename-paths.test.js | 220 ++++++++++++++---- 4 files changed, 204 insertions(+), 68 deletions(-) diff --git a/src/jsc/bindings/ImportMetaObject.cpp b/src/jsc/bindings/ImportMetaObject.cpp index cb4be748d1af..18880825cdeb 100644 --- a/src/jsc/bindings/ImportMetaObject.cpp +++ b/src/jsc/bindings/ImportMetaObject.cpp @@ -295,8 +295,9 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlo JSValue path = userPathListArray->getIndex(globalObject, i); if (scope.exception()) [[unlikely]] goto cleanup; + // Node's name is the argument of path.resolve(entry), "paths[0]" for every entry: https://github.com/nodejs/node/blob/v26.3.0/lib/path.js#L1257 if (!path.isString()) { - Bun::ERR::INVALID_ARG_TYPE(scope, globalObject, makeString("paths["_s, i, "]"_s), "string"_s, path); + Bun::ERR::INVALID_ARG_TYPE(scope, globalObject, "paths[0]"_s, "string"_s, path); goto cleanup; } WTF::String pathStr = path.toWTFString(globalObject); diff --git a/src/jsc/modules/NodeModuleModule.cpp b/src/jsc/modules/NodeModuleModule.cpp index 3bf62455fa09..4295eb122336 100644 --- a/src/jsc/modules/NodeModuleModule.cpp +++ b/src/jsc/modules/NodeModuleModule.cpp @@ -355,13 +355,17 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, // Like Node: a builtin id wins before `paths` is read; any other non-relative request needs string entries. bool entriesMustBeStrings = false; - if (!pathsValue.isUndefinedOrNull() && moduleName.isString()) { + if (!pathsValue.isUndefinedOrNull()) { + bool isPrimitive = moduleName.isString(); auto request = moduleName.toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, {}); - if (Bun::isBuiltinModule(request)) + if (isPrimitive && Bun::isBuiltinModule(request)) { pathsValue = JSC::jsUndefined(); - else + } else { entriesMustBeStrings = !isRelativeRequest(request); + if (!isPrimitive) + moduleName = JSC::jsString(vm, request); + } } // If paths are provided, use Bun__resolveSyncWithPaths @@ -377,18 +381,17 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, } WTF::Vector paths; - size_t index = 0; // Iterate through the array using forEachInIterable forEachInIterable(globalObject, pathsValue, [&](JSC::VM&, JSC::JSGlobalObject* lexicalGlobalObject, JSC::JSValue item) { if (scope.exception()) return; + // Node's name is the argument of path.resolve(entry), "paths[0]" for every entry: https://github.com/nodejs/node/blob/v26.3.0/lib/path.js#L1257 if (entriesMustBeStrings && !item.isString()) { - Bun::ERR::INVALID_ARG_TYPE(scope, lexicalGlobalObject, makeString("paths["_s, index, "]"_s), "string"_s, item); + Bun::ERR::INVALID_ARG_TYPE(scope, lexicalGlobalObject, "paths[0]"_s, "string"_s, item); return; } - index++; WTF::String pathStr = item.toWTFString(lexicalGlobalObject); if (scope.exception()) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 992d602fe92b..37a583ea4780 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -2069,7 +2069,7 @@ impl<'a> Resolver<'a> { rest.is_empty() || ResolvePath::is_sep_any(rest[rest.len() - 1]) } - /// Node's `path.resolve(entry)` for a relative `paths` entry, and whether a miss there may install. + /// Node's `path.resolve(entry)` for a relative `paths` entry, and whether that is in the cwd. fn custom_dir<'b>(&self, entry: &[u8], buf: &'b mut PathBuffer) -> Option<(&'b [u8], bool)> { use ::bun_paths::resolve_path::{ParentEqual, is_parent_or_equal}; let cwd = self.fs_ref().top_level_dir(); @@ -2092,7 +2092,6 @@ impl<'a> Resolver<'a> { .map_or(root_len, |separator| separator.max(root_len)); return Some((&path[..cut], false)); } - // A miss outside the cwd says nothing about the project, so it installs nothing. let in_cwd = is_parent_or_equal(cwd, path) != ParentEqual::Unrelated; Some((path, in_cwd)) } @@ -2107,28 +2106,34 @@ impl<'a> Resolver<'a> { kind: ast::ImportKind, global_cache: GlobalCache, ) -> ResultUnion { + let mut entry_in_cwd = false; for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8(); let entry = custom_utf8.slice(); - let mut buf; - let (dir, cache) = if bun_paths::is_absolute(entry) { - (entry, global_cache) + let result = if bun_paths::is_absolute(entry) { + self.check_package_path(entry, import_path, kind, global_cache) } else { - buf = bun_paths::path_buffer_pool::get(); - match self.custom_dir(entry, &mut buf) { - Some((dir, true)) => (dir, global_cache), - // `force` never reads node_modules, so it has no search that installs nothing. - Some((dir, false)) if global_cache != GlobalCache::force => { - (dir, GlobalCache::disable) - } - _ => continue, + let mut buf = bun_paths::path_buffer_pool::get(); + let Some((dir, in_cwd)) = self.custom_dir(entry, &mut buf) else { + continue; + }; + entry_in_cwd |= in_cwd; + // A relative entry installs nothing, and a search under `force` always ends in an install. + if global_cache == GlobalCache::force { + continue; } + self.check_package_path(dir, import_path, kind, GlobalCache::disable) }; - match self.check_package_path(dir, import_path, kind, cache) { + match result { ResultUnion::NotFound => {} found => return found, } } + // Every entry missed. A relative entry installs only through this search, from the project of the cwd. + if entry_in_cwd { + let cwd = self.fs_ref().top_level_dir(); + return self.check_package_path(cwd, import_path, kind, global_cache); + } ResultUnion::NotFound } @@ -2287,6 +2292,7 @@ impl<'a> Resolver<'a> { kind: ast::ImportKind, global_cache: GlobalCache, ) -> ResultUnion { + debug_assert!(bun_paths::is_absolute(source_dir)); let mut import_path = unremapped_import_path; let mut source_dir_info: DirInfoRef = match self.dir_info_cached(source_dir) { Err(_) => return ResultUnion::NotFound, diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index de914643a000..a2aa9b087ee1 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -243,6 +243,38 @@ test("Module._resolveFilename reads options.paths one entry at a time for a rela } }); +test("a non-string options.paths entry throws the error of path.resolve(entry)", () => { + const { path: dir, cleanup } = createTempDir("module-resolve-paths-entry-type", { + "node_modules/resolve-test-pkg/index.js": "", + "target.js": "", + }); + + try { + const fakeParent = new Module(join(dir, "file.js")); + fakeParent.filename = join(dir, "file.js"); + fakeParent.paths = Module._nodeModulePaths(dir); + const errorOf = resolveIt => { + try { + return resolveIt(); + } catch (error) { + return `${error.code}: ${error.message}`; + } + }; + // The entry is the one argument of path.resolve(), so Node names it "paths[0]" at every index. + const invalid = received => + `ERR_INVALID_ARG_TYPE: The "paths[0]" argument must be of type string. Received ${received}`; + expect([ + errorOf(() => Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: [dir, null] })), + errorOf(() => require.resolve("resolve-test-pkg", { paths: [dir, null] })), + // The request can be an object that converts to a string, or an absolute path. + errorOf(() => Module._resolveFilename(new String("resolve-test-pkg"), fakeParent, false, { paths: [0] })), + errorOf(() => Module._resolveFilename(join(dir, "target.js"), fakeParent, false, { paths: [dir, dir, 5] })), + ]).toEqual([invalid("null"), invalid("null"), invalid("type number (0)"), invalid("type number (5)")]); + } finally { + cleanup(); + } +}); + // Node turns each `options.paths` entry into a directory with path.resolve(), so a relative entry // is relative to process.cwd() and not to the calling file. The probe is in `sub/` and runs with // the fixture root as the cwd, in a child process so that the resolver starts with empty caches. @@ -335,10 +367,13 @@ function resolveRowsInChild(order) { ["./file.js", ["plugins"], file], ["./file.js", ["nowhere"], missing], ["../plugins/file.js", ["nowhere"], file], - // A builtin id is resolved before `paths` is read. Any other bare request needs strings. + // A builtin id is resolved before `paths` is read. Any other request that is not relative + // needs strings, also an absolute one, which does not use the entries. ["node:fs", [0], "node:fs"], ["plugroot", [0], "ERR_INVALID_ARG_TYPE"], ["plugroot", [".", null], "ERR_INVALID_ARG_TYPE"], + [join(dir, "plugins", "file.js"), ["nowhere"], file], + [join(dir, "plugins", "file.js"), [0], "ERR_INVALID_ARG_TYPE"], ]; if (isWindows) { rows.push(["plug", ["plugins\\"], plug], ["plug", [".\\plugins"], plug]); @@ -404,27 +439,43 @@ test("options.paths entries resolve the same in the reverse call order", () => { }); if (isBun) { - // Runs `source` with `a/b/project` as the cwd. No directory from there up to the root has a - // node_modules directory, so Bun's auto-install is on. `a/b/modules` has one, so it is off there. - // The registry answers 404 and records each request. - async function runInProject(args, source) { + // Runs `source` as `index.cjs` of the directory `cwd` in the tree `files`. No directory from the + // temporary root up has a node_modules directory, so Bun's auto-install is on where the tree has + // none. The registry records each request. It serves test/cli/install/registry/packages when + // `packages` is true (no-deps has 2.0.0 as its latest version), and answers 404 when not. + async function runInProject({ args = [], cwd, files, packages = false, source }) { + const fixtures = join(import.meta.dir, "..", "..", "..", "cli", "install", "registry", "packages"); const requests = []; const registry = Bun.serve({ port: 0, - fetch(request) { - requests.push(new URL(request.url).pathname); + async fetch(request) { + const { pathname } = new URL(request.url); + requests.push(pathname); + const tarball = pathname.match(/^\/([a-z\d-]+)\/-\/(\1-[a-z\d.-]+\.tgz)$/); + if (packages && tarball) return new Response(Bun.file(join(fixtures, tarball[1], tarball[2]))); + const manifest = Bun.file(join(fixtures, pathname.slice(1), "package.json")); + if (packages && /^\/[a-z\d-]+$/.test(pathname) && (await manifest.exists())) { + return new Response((await manifest.text()).replaceAll("http://localhost:4873/", url), { + headers: { "content-type": "application/json" }, + }); + } return new Response("not found", { status: 404 }); }, }); + const url = `http://127.0.0.1:${registry.port}/`; try { const { path: dir, cleanup } = createTempDir("resolve-paths-install", { - "a/b/project/plugins/node_modules/no-deps/index.js": "", - "a/b/modules/node_modules/local-dep/index.js": "", - "a/b/project/index.cjs": ` + ...files, + [cwd + "/index.cjs"]: ` const path = require("node:path"); + const shown = file => { + const fromCache = path.relative(process.env.BUN_INSTALL_CACHE_DIR, file); + const shownFile = fromCache.startsWith("..") ? path.relative(process.cwd(), file) : "/" + fromCache; + return shownFile.split(path.sep).join("/"); + }; const resolve = (request, paths) => { try { - return path.relative(process.cwd(), require.resolve(request, { paths })).split(path.sep).join("/"); + return shown(require.resolve(request, { paths })); } catch (error) { return error.code; } @@ -435,13 +486,13 @@ if (isBun) { try { const proc = Bun.spawn({ cmd: [childExe, ...args, "index.cjs"], - cwd: join(dir, "a", "b", "project"), - env: { ...childEnv, BUN_CONFIG_REGISTRY: registry.url.href, BUN_INSTALL_CACHE_DIR: join(dir, "cache") }, + cwd: join(dir, cwd), + env: { ...childEnv, BUN_CONFIG_REGISTRY: url, BUN_INSTALL_CACHE_DIR: join(dir, "cache") }, stdout: "pipe", stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { stdout, stderr, exitCode, requests }; + return { stdout: stdout.trim().split("\n"), stderr, exitCode, requests }; } finally { cleanup(); } @@ -450,55 +501,130 @@ if (isBun) { } } - test("options.paths: only a relative entry in the cwd installs a package", async () => { - const isPosix = process.platform !== "win32"; - const result = await runInProject( - [], - ` - // "../.." misses and is outside the cwd. "./plugins" has the package. + const isPosix = process.platform !== "win32"; + // `project` has no node_modules directory up to the root. `modules` has one. + const projects = { + "a/b/project/plugins/node_modules/no-deps/index.js": "module.exports = 'on disk';", + "a/b/project/sub/file.js": "", + "a/b/modules/node_modules/local-dep/index.js": "", + }; + + test("options.paths: a relative entry installs nothing, and a miss at one in the cwd installs from the cwd", async () => { + const result = await runInProject({ + cwd: "a/b/project", + files: projects, + source: ` + // "../.." is outside the cwd and misses. "./plugins" has the package. console.log(resolve("no-deps", ["../..", "./plugins"])); - // On POSIX "plugins\\\\" names a directory that does not exist, and the search goes on above it. - if (${isPosix}) console.log(resolve("no-deps-2", ["plugins\\\\"]), resolve("no-deps-2", ["plugins\\\\", "plugins"])); - // A project with a node_modules directory looks for an optional package that is absent. + // An entry outside the cwd is searched, also when the directory does not exist. + console.log(resolve("local-dep", ["../modules"]), resolve("local-dep", ["../modules/nowhere"])); + console.log(resolve("no-deps-1", [".."]), resolve("no-deps-1", ["../project-2"])); + // On POSIX a backslash is a file name character: no such directory, and the search goes on above it. + if (${isPosix}) console.log(resolve("no-deps", ["plugins/a\\\\b"]), resolve("no-deps-2", ["plugins\\\\"])); + // The second argument of require() is Bun's own. It takes the same entries. + console.log(require("no-deps", { paths: ["plugins"] })); + // A project with a node_modules directory does not install. process.chdir("../modules"); - console.log(resolve("local-dep", ["."]), resolve("no-deps-3", ["../..", "."])); - // "../project-2" is next to the cwd, not in it. + console.log(resolve("no-deps-3", ["../..", "."])); + // Without one, a miss at an entry in the cwd installs from the cwd, as the absolute cwd does. process.chdir("../project"); - console.log(resolve("no-deps-4", ["../project-2"])); - // An entry in the cwd is the same as its absolute form. - console.log(resolve("no-deps-5", ["."]), resolve("no-deps-6", [process.cwd()])); + console.log(resolve("no-deps-4", ["."]), resolve("no-deps-5", [process.cwd()])); + console.log(resolve("no-deps-6", ["sub"]), resolve("no-deps-7", ["./sub", "../.."])); `, - ); + }); + const missing = "MODULE_NOT_FOUND"; expect(result).toEqual({ - stdout: - "plugins/node_modules/no-deps/index.js\n" + - (isPosix ? "MODULE_NOT_FOUND MODULE_NOT_FOUND\n" : "") + - "node_modules/local-dep/index.js MODULE_NOT_FOUND\n" + - "MODULE_NOT_FOUND\n" + - "MODULE_NOT_FOUND MODULE_NOT_FOUND\n", + stdout: [ + "plugins/node_modules/no-deps/index.js", + "../modules/node_modules/local-dep/index.js ../modules/node_modules/local-dep/index.js", + `${missing} ${missing}`, + ...(isPosix ? [`plugins/node_modules/no-deps/index.js ${missing}`] : []), + "on disk", + missing, + `${missing} ${missing}`, + `${missing} ${missing}`, + ], stderr: "", exitCode: 0, - requests: ["/no-deps-5", "/no-deps-6"], + requests: ["/no-deps-4", "/no-deps-5", "/no-deps-6", "/no-deps-7"], + }); + }); + + test("options.paths: a package on disk under any entry wins over the registry", async () => { + const result = await runInProject({ + cwd: "a/b/project", + files: { + ...projects, + // https://github.com/oven-sh/bun/issues/19419: nest-typed-config loads two of the project's + // dependencies in this way, from its own file in node_modules. + "a/b/modules/node_modules/typed-config/index.js": `module.exports = require.resolve("no-deps", { paths: ["../..", "."] });`, + "a/b/modules/node_modules/no-deps/index.js": "", + }, + packages: true, + source: ` + // The registry has no-deps too. Each list has it on disk. + console.log(resolve("no-deps", ["nowhere", "plugins"]), resolve("no-deps", ["./nowhere", "./plugins"])); + console.log(resolve("no-deps", [".", "plugins"]), resolve("no-deps", ["./plugins", "."])); + process.chdir("../modules"); + console.log(shown(require(path.resolve("node_modules/typed-config")))); + // No entry has it: the cwd installs it, once. + process.chdir("../project"); + console.log(resolve("no-deps", ["nowhere"]), resolve("no-deps", ["sub", "../.."])); + `, + }); + const onDisk = "plugins/node_modules/no-deps/index.js"; + expect(result).toEqual({ + stdout: [`${onDisk} ${onDisk}`, `${onDisk} ${onDisk}`, "node_modules/no-deps/index.js", expect.any(String)], + stderr: "", + exitCode: 0, + requests: ["/no-deps", "/no-deps/-/no-deps-2.0.0.tgz"], + }); + const [first, second] = result.stdout[3].split(" "); + expect({ first: first.startsWith("/no-deps@2.0.0"), second }).toEqual({ first: true, second: first }); + }); + + test("options.paths: the project of the cwd decides whether a miss installs", async () => { + const result = await runInProject({ + cwd: "root/app", + files: { + // The scanner turns auto-install off for the project "root". "sub" is a project of its own. + "root/bunfig.toml": `[install.security]\nscanner = "./scanner.ts"\n`, + "root/package.json": JSON.stringify({ name: "root" }), + "root/app/sub/package.json": JSON.stringify({ name: "nested" }), + "root/app/conf/file.js": "", + "tool/node_modules/no-deps/index.js": "", + }, + source: ` + console.log(resolve("no-deps-1", ["./sub"]), resolve("no-deps-2", ["sub"])); + // The refusal to install does not hide the package that the next entry has. + console.log(resolve("no-deps", ["conf", path.resolve("../../tool")])); + `, + }); + expect(result).toEqual({ + stdout: ["MODULE_NOT_FOUND MODULE_NOT_FOUND", "../../tool/node_modules/no-deps/index.js"], + stderr: "", + exitCode: 0, + requests: [], }); }); test("options.paths: --install=force does not read the node_modules of an entry", async () => { - const result = await runInProject( - ["--install=force"], - ` - console.log(resolve("no-deps", ["./plugins"])); - console.log(resolve("no-deps", ["./plugins", "."])); + const result = await runInProject({ + args: ["--install=force"], + cwd: "a/b/project", + files: projects, + source: ` + // The registry has neither package, so the calls miss. plugins/node_modules has no-deps. + console.log(resolve("no-deps", ["./plugins"]), resolve("no-deps-1", ["plugins", "."])); + // "../modules" is outside the cwd: it installs nothing, and this mode has no other search. console.log(resolve("local-dep", ["../modules"])); `, - ); - // The registry has no such package, so the calls miss. A read of plugins/node_modules or of - // ../modules/node_modules would find the local copy. "../modules" is outside the cwd, so it - // installs nothing. + }); expect(result).toEqual({ - stdout: "MODULE_NOT_FOUND\nMODULE_NOT_FOUND\nMODULE_NOT_FOUND\n", + stdout: ["MODULE_NOT_FOUND MODULE_NOT_FOUND", "MODULE_NOT_FOUND"], stderr: "", exitCode: 0, - requests: ["/no-deps"], + requests: ["/no-deps", "/no-deps-1"], }); }); } From bfda1587ac96f172e625c8c0916c9b42b0f20e35 Mon Sep 17 00:00:00 2001 From: robobun Date: Tue, 27 Oct 2026 07:22:20 +0000 Subject: [PATCH 12/15] test: do not block on the paths child processes, and pin a cwd with a backslash The row tests start their child with an async spawn. The tests that start a child process run concurrently under bun:test. Two POSIX rows pin the search from a cwd with a backslash in its name: the directory cache cannot read that directory, so the search starts above it. --- .../module-resolve-filename-paths.test.js | 44 ++++++++++++------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index a2aa9b087ee1..f43c930204ce 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -1,9 +1,11 @@ // Use bun:test in Bun, or node:test in Node.js -import { spawnSync } from "child_process"; +import { spawn } from "child_process"; +import { once } from "events"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "fs"; import Module from "module"; import { tmpdir } from "os"; import { dirname, join, resolve } from "path"; +import { text } from "stream/consumers"; // Detect runtime and import appropriate test framework const isBun = typeof Bun !== "undefined"; @@ -38,6 +40,9 @@ if (isBun) { }); } +// The tests that start a child process do not share state. node:test has no `test.concurrent`. +const concurrentTest = isBun ? test.concurrent : test; + // Helper to create temp directory - works in both Bun and Node function createTempDir(prefix, files) { // Use realpathSync to resolve symlinks (handles /tmp -> /private/tmp on macOS) @@ -307,7 +312,7 @@ for (const i of order) { console.log(JSON.stringify(results)); `; -function resolveRowsInChild(order) { +async function resolveRowsInChild(order) { const isWindows = process.platform === "win32"; const files = { "sub/probe.cjs": probeSource, @@ -329,6 +334,7 @@ function resolveRowsInChild(order) { }; if (!isWindows) { files["C:/plugins/node_modules/plugd/index.js"] = ""; + files["back\\slash/file.js"] = ""; } const { path: dir, cleanup } = createTempDir("resolve-paths-entries", files); @@ -391,6 +397,9 @@ function resolveRowsInChild(order) { // Longer than PATH_MAX as written, short once resolved. ["plug", [Buffer.alloc(4200, "./").toString() + "plugins"], plug], ["plug", [Buffer.alloc(5000, "a").toString()], missing], + // The cwd has a backslash in its name. Bun's directory cache cannot read it, so the search starts above it. + ["plugroot", ["."], plugroot, "back\\slash"], + ["plugroot", ["./nowhere"], plugroot, "back\\slash"], ); } @@ -399,11 +408,16 @@ function resolveRowsInChild(order) { join(dir, "rows.json"), JSON.stringify(rows.map(([request, paths, , chdir]) => [request, paths, chdir])), ); - const { stdout, stderr, status } = spawnSync( - childExe, - isBun ? ["--no-install", "sub/probe.cjs", order] : ["sub/probe.cjs", order], - { cwd: dir, env: childEnv, encoding: "utf8" }, - ); + const child = spawn(childExe, isBun ? ["--no-install", "sub/probe.cjs", order] : ["sub/probe.cjs", order], { + cwd: dir, + env: childEnv, + stdio: ["ignore", "pipe", "pipe"], + }); + const [stdout, stderr, [status]] = await Promise.all([ + text(child.stdout), + text(child.stderr), + once(child, "close"), + ]); let results; try { results = JSON.parse(stdout); @@ -430,12 +444,12 @@ function resolveRowsInChild(order) { } } -test("options.paths entries are resolved like path.resolve() does", () => { - resolveRowsInChild("forward"); +concurrentTest("options.paths entries are resolved like path.resolve() does", async () => { + await resolveRowsInChild("forward"); }); -test("options.paths entries resolve the same in the reverse call order", () => { - resolveRowsInChild("reverse"); +concurrentTest("options.paths entries resolve the same in the reverse call order", async () => { + await resolveRowsInChild("reverse"); }); if (isBun) { @@ -509,7 +523,7 @@ if (isBun) { "a/b/modules/node_modules/local-dep/index.js": "", }; - test("options.paths: a relative entry installs nothing, and a miss at one in the cwd installs from the cwd", async () => { + test.concurrent("options.paths: a relative entry installs nothing, the cwd installs after a miss", async () => { const result = await runInProject({ cwd: "a/b/project", files: projects, @@ -550,7 +564,7 @@ if (isBun) { }); }); - test("options.paths: a package on disk under any entry wins over the registry", async () => { + test.concurrent("options.paths: a package on disk under any entry wins over the registry", async () => { const result = await runInProject({ cwd: "a/b/project", files: { @@ -583,7 +597,7 @@ if (isBun) { expect({ first: first.startsWith("/no-deps@2.0.0"), second }).toEqual({ first: true, second: first }); }); - test("options.paths: the project of the cwd decides whether a miss installs", async () => { + test.concurrent("options.paths: the project of the cwd decides whether a miss installs", async () => { const result = await runInProject({ cwd: "root/app", files: { @@ -608,7 +622,7 @@ if (isBun) { }); }); - test("options.paths: --install=force does not read the node_modules of an entry", async () => { + test.concurrent("options.paths: --install=force does not read the node_modules of an entry", async () => { const result = await runInProject({ args: ["--install=force"], cwd: "a/b/project", From 61185440c167a41a6dc9c68f80fb99e65babd504 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:41:41 +0000 Subject: [PATCH 13/15] resolver: leave the paths loop in place and add the relative folder to it After the merge of main, the loop over the paths entries also asks a compiled executable. That loop is main's text again. A relative entry takes one branch at its top: the search from path.resolve(entry) with installs off, then what the executable holds there, as for an absolute folder on disk. The search from the cwd that installs runs after the loop. The test row with a request object checks only the error code: Node 26.12 names the request in the message, and Node 26.3 names the entry. --- src/resolver/resolver.rs | 114 +++++++++--------- .../module-resolve-filename-paths.test.js | 12 +- 2 files changed, 67 insertions(+), 59 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 2c31277b77c6..efe879b646e8 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -2360,12 +2360,51 @@ impl<'a> Resolver<'a> { if let Some(custom_paths) = self.custom_dir_paths { bun_core::hint::cold(); - return self.check_package_path_in_custom_dirs( - custom_paths, - import_path, - kind, - global_cache, - ); + let mut relative_in_cwd = false; + for custom_path in custom_paths { + let custom_utf8 = custom_path.to_utf8(); + // From each folder in its turn. From a folder on disk: the disk, as in an executable built without --aot, then what the executable + // holds there. From a folder of the executable: the executable first, as for a file of it that imports. + let given = custom_utf8.slice(); + if !bun_paths::is_absolute(given) { + match self.look_from_relative_folder( + given, + import_path, + kind, + global_cache, + &mut relative_in_cwd, + ) { + Some(answer) => return answer, + None => continue, + } + } + let is_of_executable = + ::bun_options_types::standalone_path::is_bun_standalone_file_path(given); + if is_of_executable + && let Some(answer) = + self.look_in_executable_from_given_folder(given, import_path, kind) + { + return answer; + } + let on_disk = self.folder_on_disk_of_given_folder(given); + match self.check_package_path(&on_disk, import_path, kind, global_cache) { + ResultUnion::Success(res) => return ResultUnion::Success(res), + ResultUnion::Pending(p) => return ResultUnion::Pending(p), + ResultUnion::Failure(p) => return ResultUnion::Failure(p), + ResultUnion::NotFound => {} + } + if !is_of_executable + && let Some(answer) = + self.look_in_executable_from_given_folder(given, import_path, kind) + { + return answer; + } + } + // Every folder missed. A relative folder installs only through this search, from the project of the cwd. + if relative_in_cwd { + let cwd = self.fs_ref().top_level_dir(); + return self.check_package_path(cwd, import_path, kind, global_cache); + } } else { match self.check_package_path(source_dir, import_path, kind, global_cache) { ResultUnion::Success(res) => return ResultUnion::Success(res), @@ -2425,65 +2464,28 @@ impl<'a> Resolver<'a> { Some((path, in_cwd)) } - /// Node's search of `Module._nodeModulePaths(entry)` per `paths` entry, for a bare request. + /// The search from one relative folder of `paths`, which Node reads as `path.resolve(folder)`. `None`: it has no answer, and the search goes on. #[cold] #[inline(never)] - fn check_package_path_in_custom_dirs<'r>( + fn look_from_relative_folder<'r>( &mut self, - custom_paths: &[bun_core::String], + folder: &[u8], import_path: &'r [u8], kind: ast::ImportKind, global_cache: GlobalCache, - ) -> ResultUnion<'r> { - let mut entry_in_cwd = false; - for custom_path in custom_paths { - let custom_utf8 = custom_path.to_utf8(); - let entry = custom_utf8.slice(); - if bun_paths::is_absolute(entry) { - // From each folder in its turn. From a folder on disk: the disk, as in an executable built without --aot, then what the executable - // holds there. From a folder of the executable: the executable first, as for a file of it that imports. - let is_of_executable = - ::bun_options_types::standalone_path::is_bun_standalone_file_path(entry); - if is_of_executable - && let Some(answer) = - self.look_in_executable_from_given_folder(entry, import_path, kind) - { - return answer; - } - let on_disk = self.folder_on_disk_of_given_folder(entry); - match self.check_package_path(&on_disk, import_path, kind, global_cache) { - ResultUnion::NotFound => {} - found => return found, - } - if !is_of_executable - && let Some(answer) = - self.look_in_executable_from_given_folder(entry, import_path, kind) - { - return answer; - } - continue; - } - // A relative entry is a folder on disk, and the executable holds a package for no relative folder: the disk alone is asked. - let mut buf = bun_paths::path_buffer_pool::get(); - let Some((dir, in_cwd)) = self.custom_dir(entry, &mut buf) else { - continue; - }; - entry_in_cwd |= in_cwd; - // A relative entry installs nothing, and a search under `force` always ends in an install. - if global_cache == GlobalCache::force { - continue; - } - match self.check_package_path(dir, import_path, kind, GlobalCache::disable) { + is_in_cwd: &mut bool, + ) -> Option> { + let mut buf = bun_paths::path_buffer_pool::get(); + let (on_disk, in_cwd) = self.custom_dir(folder, &mut buf)?; + *is_in_cwd |= in_cwd; + // A relative folder installs nothing, and a search under `force` always ends in an install. + if global_cache != GlobalCache::force { + match self.check_package_path(on_disk, import_path, kind, GlobalCache::disable) { ResultUnion::NotFound => {} - found => return found, + found => return Some(found), } } - // Every entry missed. A relative entry installs only through this search, from the project of the cwd. - if entry_in_cwd { - let cwd = self.fs_ref().top_level_dir(); - return self.check_package_path(cwd, import_path, kind, global_cache); - } - ResultUnion::NotFound + self.look_in_executable_from_given_folder(on_disk, import_path, kind) } pub(crate) fn check_relative_path( diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index f43c930204ce..1fd22ee963be 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -271,10 +271,16 @@ test("a non-string options.paths entry throws the error of path.resolve(entry)", expect([ errorOf(() => Module._resolveFilename("resolve-test-pkg", fakeParent, false, { paths: [dir, null] })), errorOf(() => require.resolve("resolve-test-pkg", { paths: [dir, null] })), - // The request can be an object that converts to a string, or an absolute path. - errorOf(() => Module._resolveFilename(new String("resolve-test-pkg"), fakeParent, false, { paths: [0] })), + // An absolute request does not use the entries. Node checks them all the same. errorOf(() => Module._resolveFilename(join(dir, "target.js"), fakeParent, false, { paths: [dir, dir, 5] })), - ]).toEqual([invalid("null"), invalid("null"), invalid("type number (0)"), invalid("type number (5)")]); + ]).toEqual([invalid("null"), invalid("null"), invalid("type number (5)")]); + + // A request object that converts to a string gets no path either. Node 26.12 names the request + // in the message, and Node 26.3 names the entry, so only the code is the same. + const request = new String("resolve-test-pkg"); + expect(errorOf(() => Module._resolveFilename(request, fakeParent, false, { paths: [0] })).split(":")[0]).toBe( + "ERR_INVALID_ARG_TYPE", + ); } finally { cleanup(); } From 3090e3b5b5d9b7deb04ad63451e548d0a0a39c8f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:33:36 +0000 Subject: [PATCH 14/15] resolver: a relative paths entry does not answer after a refusal in exports Node throws when the nearest copy of a package refuses the request in its "exports". load_node_modules returned a plain miss for that, so the two searches that this branch adds went on after it: the search of a later relative entry and the search from the cwd. They answered with another copy. With auto-install on, the search from the cwd asked the registry. load_node_modules now sets Resolver::refused_in_node_modules at its return for a refusal, when the refusing package is at /node_modules/ and the walk does not serve the target of a `#` import. The loop over the `paths` entries clears the flag one time. After a refusal, a relative entry and the search from the cwd do not answer. The search of an absolute entry is as before. require.resolve gives Node's text for a non-string entry of a relative request. --- src/jsc/bindings/ImportMetaObject.cpp | 10 +- src/jsc/bindings/ImportMetaObject.h | 2 + src/jsc/modules/NodeModuleModule.cpp | 5 +- src/resolver/resolver.rs | 42 +++++- ...-not-hang-on-the-working-directory.test.ts | 32 ++++ .../module-resolve-filename-paths.test.js | 137 +++++++++++++++++- 6 files changed, 219 insertions(+), 9 deletions(-) diff --git a/src/jsc/bindings/ImportMetaObject.cpp b/src/jsc/bindings/ImportMetaObject.cpp index d8c8e6433634..93d7a9dda508 100644 --- a/src/jsc/bindings/ImportMetaObject.cpp +++ b/src/jsc/bindings/ImportMetaObject.cpp @@ -342,9 +342,15 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlo JSValue path = userPathListArray->getIndex(globalObject, i); if (scope.exception()) [[unlikely]] goto cleanup; - // Node's name is the argument of path.resolve(entry), "paths[0]" for every entry: https://github.com/nodejs/node/blob/v26.3.0/lib/path.js#L1257 + // Node's text for a non-string entry. A bare request names the argument of path.resolve(entry) (https://github.com/nodejs/node/blob/v26.3.0/lib/path.js#L1257), a relative one names the list (https://github.com/nodejs/node/blob/v26.3.0/lib/internal/modules/cjs/loader.js#L769). if (!path.isString()) { - Bun::ERR::INVALID_ARG_TYPE(scope, globalObject, "paths[0]"_s, "string"_s, path); + auto request = moduleName.toWTFString(globalObject); + if (scope.exception()) [[unlikely]] + goto cleanup; + if (Bun::isRelativeRequest(request)) + Bun::ERR::INVALID_ARG_TYPE(scope, globalObject, "paths"_s, "array of strings"_s, userPathList); + else + Bun::ERR::INVALID_ARG_TYPE(scope, globalObject, "paths[0]"_s, "string"_s, path); goto cleanup; } WTF::String pathStr = path.toWTFString(globalObject); diff --git a/src/jsc/bindings/ImportMetaObject.h b/src/jsc/bindings/ImportMetaObject.h index ef0df109cea7..5f5cd29d8e5c 100644 --- a/src/jsc/bindings/ImportMetaObject.h +++ b/src/jsc/bindings/ImportMetaObject.h @@ -16,6 +16,8 @@ extern "C" JSC::EncodedJSValue Bun__resolveSyncWithSourceIfExists(JSC::JSGlobalO namespace Bun { class JSModuleGraph; +// The requests the resolver reads as relative to a directory instead of as a package name. +bool isRelativeRequest(const WTF::String& request); } namespace Zig { diff --git a/src/jsc/modules/NodeModuleModule.cpp b/src/jsc/modules/NodeModuleModule.cpp index 88a5ede42777..f3d61bae80da 100644 --- a/src/jsc/modules/NodeModuleModule.cpp +++ b/src/jsc/modules/NodeModuleModule.cpp @@ -284,8 +284,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleCreateRequire, RELEASE_AND_RETURN(scope, JSValue::encode(require)); } -// The requests the resolver reads as relative to a directory instead of as a package name. -static bool isRelativeRequest(const WTF::String& request) +bool isRelativeRequest(const WTF::String& request) { return request == "."_s || request == ".."_s || request.startsWith("./"_s) || request.startsWith("../"_s) #if OS(WINDOWS) @@ -359,7 +358,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, JSC::EncodedJSValue result; - // Like Node: a builtin id wins before `paths` is read; any other non-relative request needs string entries. + // Like Node: a builtin id wins before the entries of `paths` are checked; any other non-relative request needs string entries. bool entriesMustBeStrings = false; if (!pathsValue.isUndefinedOrNull()) { bool isPrimitive = moduleName.isString(); diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index efe879b646e8..689c586c1341 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -573,6 +573,9 @@ pub struct Resolver<'a> { /// Why "exports" or "imports" led to no file: the first time since this was last `None`. pub esm_failure: Option, + + /// `load_node_modules` stopped at a copy whose "exports" give no file. Node's `_findPath` does not catch that throw, so no later lookup directory answers: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/modules/cjs/loader.js#L776 + refused_in_node_modules: bool, } /// RAII guard returned by [`Resolver::scoped_log`]. Restores the previous @@ -641,6 +644,7 @@ impl<'a> Resolver<'a> { // never carried across worker init. custom_dir_paths: None, esm_failure: None, + refused_in_node_modules: false, } } @@ -997,6 +1001,7 @@ impl<'a> Resolver<'a> { prefer_module_field: true, custom_dir_paths: None, esm_failure: None, + refused_in_node_modules: false, } } @@ -2361,6 +2366,8 @@ impl<'a> Resolver<'a> { if let Some(custom_paths) = self.custom_dir_paths { bun_core::hint::cold(); let mut relative_in_cwd = false; + // Cleared here, one time for the list. The search of any folder sets it, and then no relative folder answers. + self.refused_in_node_modules = false; for custom_path in custom_paths { let custom_utf8 = custom_path.to_utf8(); // From each folder in its turn. From a folder on disk: the disk, as in an executable built without --aot, then what the executable @@ -2401,7 +2408,7 @@ impl<'a> Resolver<'a> { } } // Every folder missed. A relative folder installs only through this search, from the project of the cwd. - if relative_in_cwd { + if relative_in_cwd && !self.refused_in_node_modules { let cwd = self.fs_ref().top_level_dir(); return self.check_package_path(cwd, import_path, kind, global_cache); } @@ -2479,12 +2486,16 @@ impl<'a> Resolver<'a> { let (on_disk, in_cwd) = self.custom_dir(folder, &mut buf)?; *is_in_cwd |= in_cwd; // A relative folder installs nothing, and a search under `force` always ends in an install. - if global_cache != GlobalCache::force { + if !self.refused_in_node_modules && global_cache != GlobalCache::force { match self.check_package_path(on_disk, import_path, kind, GlobalCache::disable) { ResultUnion::NotFound => {} found => return Some(found), } } + // A refusal, by this folder or by one before it, is where Node throws. The executable and the folders after it do not answer. + if self.refused_in_node_modules { + return Some(ResultUnion::NotFound); + } self.look_in_executable_from_given_folder(on_disk, import_path, kind) } @@ -3253,6 +3264,13 @@ impl<'a> Resolver<'a> { if let Some(d) = self.debug_logs.as_mut() { d.decrease_indent(); } + // Node's walk reads a package at `/node_modules/` only. The own package of the importing folder can lie elsewhere, and a `#` name is the caller's. + self.refused_in_node_modules |= !forbid_imports + && (!is_self_reference + || is_node_modules_copy( + package_json.source.path.text, + esm.name, + )); return MatchStatus::NotFound; } } @@ -7212,6 +7230,26 @@ fn primary_side_effects( } } +/// Whether `package_json` is `/node_modules//package.json`, the one place where Node's walk reads the package `name`. +fn is_node_modules_copy(package_json: &[u8], name: &[u8]) -> bool { + let Some(mut rest) = bun_paths::dirname(package_json) else { + return false; + }; + for part in name + .rsplit(|&c| c == b'/') + .chain([b"node_modules".as_slice()]) + { + let Some((&separator, above)) = rest.strip_suffix(part).and_then(<[u8]>::split_last) else { + return false; + }; + if !bun_paths::is_sep_native(separator) { + return false; + } + rest = above; + } + true +} + #[inline] fn is_dot_slash(path: &[u8]) -> bool { #[cfg(not(windows))] diff --git a/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts b/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts index e608f3e00f7d..c95875c14639 100644 --- a/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts +++ b/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts @@ -44,3 +44,35 @@ test("a name made at run time is answered alike from every working directory", a const alike = "./held.cjs true true true\nmade-up-held true true true\n"; expect(said).toEqual({ elsewhere: alike, empty: alike }); }); + +// With --compile-autoload-package-json the program reads package.json on disk, so a copy on disk can refuse a file in its "exports". +// Node throws there. The program holds the copy of the root, which has that file, and must not answer with it for a relative entry. +test("a refusal by the exports of the copy on disk stands for a relative entry, whatever the program holds", async () => { + using dir = tempDir("require-resolve-refused-on-disk", { + "package.json": JSON.stringify({ name: "tool" }), + "main.cjs": ` + require("./plugins/local.cjs"), require("sealed/private.js"); + const codeOf = paths => { + try { return require.resolve("sealed/private.js", { paths }); } catch (error) { return error.code; } + }; + console.log(codeOf(["plugins"]), codeOf(["./plugins"]), codeOf(["plugins", "."]));`, + node_modules: { sealed: { "private.js": `exports.copy = "of the program";` } }, + plugins: { + "local.cjs": `exports.local = true;`, + node_modules: { + sealed: { + "package.json": JSON.stringify({ name: "sealed", exports: "./index.js" }), + "index.js": "", + "private.js": `exports.copy = "under plugins";`, + }, + }, + }, + }); + const program = join(String(dir), "program"); + const built = await run( + [bunExe(), "build", "--compile", "--aot", "--compile-autoload-package-json", "./main.cjs", "--outfile", program], + String(dir), + ); + expect(built.exitCode).toBe(0); + expect((await run([program], String(dir))).stdout).toBe("MODULE_NOT_FOUND MODULE_NOT_FOUND MODULE_NOT_FOUND\n"); +}); diff --git a/test/js/node/module/module-resolve-filename-paths.test.js b/test/js/node/module/module-resolve-filename-paths.test.js index 1fd22ee963be..293f7413d954 100644 --- a/test/js/node/module/module-resolve-filename-paths.test.js +++ b/test/js/node/module/module-resolve-filename-paths.test.js @@ -12,12 +12,14 @@ const isBun = typeof Bun !== "undefined"; let test, expect; let childEnv = process.env; let childExe = process.execPath; +let nodeForTheseTests = null; if (isBun) { ({ test, expect } = await import("bun:test")); const harness = await import("harness"); childEnv = harness.bunEnv; childExe = harness.bunExe(); + nodeForTheseTests = harness.nodeExeAtLeast("26.3.0"); } else { // Node.js const { createRequire } = await import("module"); @@ -248,7 +250,7 @@ test("Module._resolveFilename reads options.paths one entry at a time for a rela } }); -test("a non-string options.paths entry throws the error of path.resolve(entry)", () => { +test("a non-string options.paths entry throws Node's error", () => { const { path: dir, cleanup } = createTempDir("module-resolve-paths-entry-type", { "node_modules/resolve-test-pkg/index.js": "", "target.js": "", @@ -275,6 +277,11 @@ test("a non-string options.paths entry throws the error of path.resolve(entry)", errorOf(() => Module._resolveFilename(join(dir, "target.js"), fakeParent, false, { paths: [dir, dir, 5] })), ]).toEqual([invalid("null"), invalid("null"), invalid("type number (5)")]); + // A relative request reads the entries one at a time, so Node's text there is for the list. + expect(errorOf(() => require.resolve("./target.js", { paths: [5] }))).toBe( + `ERR_INVALID_ARG_TYPE: The "paths" argument must be array of strings. Received an instance of Array`, + ); + // A request object that converts to a string gets no path either. Node 26.12 names the request // in the message, and Node 26.3 names the entry, so only the code is the same. const request = new String("resolve-test-pkg"); @@ -337,6 +344,45 @@ async function resolveRowsInChild(order) { "deps/node_modules/vue-router/dist/volar/sfc-route-blocks.cjs": "", "deps/node_modules/@scope/pkg/package.json": JSON.stringify({ name: "@scope/pkg", main: "lib/main.js" }), "deps/node_modules/@scope/pkg/lib/main.js": "", + // Two copies of one package. The "exports" of the copy under `plugins` leave private.js out. + "node_modules/plugsealed/private.js": "", + "plugins/node_modules/plugsealed/package.json": JSON.stringify({ name: "plugsealed", exports: "./index.js" }), + "plugins/node_modules/plugsealed/index.js": "", + "plugins/node_modules/plugsealed/private.js": "", + // The "exports" of this copy name a file that does not exist. + "node_modules/plugsealed-gone/sub.js": "", + "plugins/node_modules/plugsealed-gone/package.json": JSON.stringify({ exports: { "./sub.js": "./dist/sub.js" } }), + // The entry `nested` is a package of the same name as a copy in node_modules. Its "exports" leave lib.js out. + "nested/package.json": JSON.stringify({ name: "plugnested", exports: "./main.js" }), + "nested/main.js": "", + "nested/lib.js": "", + "node_modules/plugnested/lib.js": "", + // A package in a directory of its own name, as in a workspace, with another copy in node_modules. + "packages/plugsame/package.json": JSON.stringify({ name: "plugsame", exports: "./main.js" }), + "packages/plugsame/main.js": "", + "packages/plugsame/lib.js": "", + "node_modules/plugsame/lib.js": "", + // A scoped package with two copies. The "exports" of the copy under `plugins` leave private.js out. + "node_modules/@plugscope/sealed/private.js": "", + "plugins/node_modules/@plugscope/sealed/package.json": JSON.stringify({ + name: "@plugscope/sealed", + exports: "./index.js", + }), + "plugins/node_modules/@plugscope/sealed/index.js": "", + "plugins/node_modules/@plugscope/sealed/private.js": "", + // The same two packages in a project that lies inside a node_modules directory. Rows chdir() into `node_modules/host`. + "node_modules/host/nested/package.json": JSON.stringify({ name: "plugnested", exports: "./main.js" }), + "node_modules/host/nested/main.js": "", + "node_modules/host/nested/lib.js": "", + "node_modules/host/node_modules/plugnested/lib.js": "", + // An alias, as `npm install plugalias2@npm:plugalias` leaves it: the directory `plugalias2` holds a package named `plugalias`. + "node_modules/plugalias2/package.json": JSON.stringify({ name: "plugalias", exports: "./index.js" }), + "node_modules/plugalias2/index.js": "", + "node_modules/plugalias/x.js": "", + // The package of the probe defines two `#` names. The packages of the entries `deps` and `plugins` define them in another way. + "package.json": JSON.stringify({ imports: { "#rootfile": "./plugins/file.js", "#sealed": "./plugins/file.js" } }), + "deps/package.json": JSON.stringify({ imports: { "#depsfile": "./node_modules/dep/index.js" } }), + "plugins/package.json": JSON.stringify({ imports: { "#sealed": "plugsealed/private.js" } }), }; if (!isWindows) { files["C:/plugins/node_modules/plugd/index.js"] = ""; @@ -349,6 +395,8 @@ async function resolveRowsInChild(order) { const dep = "deps/node_modules/dep/index.js"; const file = "plugins/file.js"; const missing = "MODULE_NOT_FOUND"; + // Node has a code of its own for a file that "exports" leave out. Bun throws MODULE_NOT_FOUND. + const refused = isBun ? missing : "ERR_PACKAGE_PATH_NOT_EXPORTED"; // [request, paths, expected, directory to chdir() into first] const rows = [ // https://github.com/oven-sh/bun/issues/45706 @@ -361,6 +409,37 @@ async function resolveRowsInChild(order) { ["plugboth", ["./plugins"], "plugins/node_modules/plugboth/index.js"], ["plugboth", ["plugins"], "plugins/node_modules/plugboth/index.js"], ["plugboth", ["nowhere"], "node_modules/plugboth/index.js"], + // The nearest copy answers alone. Its "exports" refuse the file, so no copy above it and no relative entry after it answers. + ["plugsealed", ["plugins"], "plugins/node_modules/plugsealed/index.js"], + ["plugsealed/private.js", ["plugins"], refused], + ["plugsealed/private.js", ["./plugins"], refused], + ["plugsealed/private.js", ["plugins/nowhere"], refused], + ["plugsealed/private.js", ["plugins", "."], refused], + ["plugsealed/private.js", ["plugins", dir], refused], + ["plugsealed/private.js", [join(dir, "plugins")], refused], + ["plugsealed/private.js", [join(dir, "plugins"), "."], refused], + ["plugsealed/private.js", [join(dir, "plugins"), "nowhere"], refused], + ["plugsealed/private.js", [".", "plugins"], "node_modules/plugsealed/private.js"], + ["plugsealed-gone/sub.js", ["plugins"], missing], + // An entry inside that copy: the walk from it reaches the same copy. + ["plugsealed/private.js", ["plugins/node_modules/plugsealed"], refused], + ["plugsealed/private.js", ["plugins/node_modules/plugsealed", "."], refused], + ["@plugscope/sealed/private.js", ["plugins"], refused], + ["@plugscope/sealed/private.js", ["plugins/node_modules/@plugscope/sealed"], refused], + // The call after a refusal starts anew. + ["plug", ["nowhere", "plugins"], plug], + // A package that holds an entry is not at `node_modules/`, so it does not end the search: Node reads a + // package's own name and `#` names from the caller. That holds inside a node_modules directory and for an alias. + ["plugnested/lib.js", ["nested"], "node_modules/plugnested/lib.js"], + ["plugnested/lib.js", ["./nested"], "node_modules/plugnested/lib.js"], + ["plugnested/lib.js", ["nested/nowhere"], "node_modules/plugnested/lib.js"], + ["plugsame/lib.js", ["packages/plugsame"], "node_modules/plugsame/lib.js"], + ["plugnested/lib.js", ["nested"], "node_modules/host/node_modules/plugnested/lib.js", "node_modules/host"], + ["plugnested/lib.js", ["./nested", "."], "node_modules/host/node_modules/plugnested/lib.js", "node_modules/host"], + ["plugalias/x.js", ["node_modules/plugalias2"], "node_modules/plugalias/x.js"], + ["plugalias/x.js", [join(dir, "node_modules", "plugalias2"), "."], "node_modules/plugalias/x.js"], + ["#rootfile", ["deps"], file], + ["#sealed", ["plugins"], file], // The search starts at the entry and goes up. ["plug", ["plugins"], plug], ["plug", ["plugins/"], plug], @@ -379,7 +458,7 @@ async function resolveRowsInChild(order) { ["./file.js", ["plugins"], file], ["./file.js", ["nowhere"], missing], ["../plugins/file.js", ["nowhere"], file], - // A builtin id is resolved before `paths` is read. Any other request that is not relative + // A builtin id is returned before the entries are checked. Any other request that is not relative // needs strings, also an absolute one, which does not use the entries. ["node:fs", [0], "node:fs"], ["plugroot", [0], "ERR_INVALID_ARG_TYPE"], @@ -459,6 +538,18 @@ concurrentTest("options.paths entries resolve the same in the reverse call order }); if (isBun) { + // The rows above are Node's own answers: this file is a node:test file too. + test.concurrent.skipIf(!nodeForTheseTests)("the options.paths tests pass in Node.js", async () => { + await using proc = Bun.spawn({ + cmd: [nodeForTheseTests, import.meta.path], + env: childEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ exitCode, output: exitCode === 0 ? "" : stdout + stderr }).toEqual({ exitCode: 0, output: "" }); + }); + // Runs `source` as `index.cjs` of the directory `cwd` in the tree `files`. No directory from the // temporary root up has a node_modules directory, so Bun's auto-install is on where the tree has // none. The registry records each request. It serves test/cli/install/registry/packages when @@ -525,6 +616,8 @@ if (isBun) { // `project` has no node_modules directory up to the root. `modules` has one. const projects = { "a/b/project/plugins/node_modules/no-deps/index.js": "module.exports = 'on disk';", + "a/b/project/plugins/node_modules/sealed/package.json": JSON.stringify({ name: "sealed", exports: "./index.js" }), + "a/b/project/plugins/node_modules/sealed/index.js": "", "a/b/project/sub/file.js": "", "a/b/modules/node_modules/local-dep/index.js": "", }; @@ -543,6 +636,8 @@ if (isBun) { if (${isPosix}) console.log(resolve("no-deps", ["plugins/a\\\\b"]), resolve("no-deps-2", ["plugins\\\\"])); // The second argument of require() is Bun's own. It takes the same entries. console.log(require("no-deps", { paths: ["plugins"] })); + // The copy under "plugins" refuses the file in its "exports": the registry is not asked. The calls after it install again. + console.log(resolve("sealed/private.js", ["plugins"]), resolve("sealed/private.js", ["./plugins", "."])); // A project with a node_modules directory does not install. process.chdir("../modules"); console.log(resolve("no-deps-3", ["../..", "."])); @@ -560,6 +655,7 @@ if (isBun) { `${missing} ${missing}`, ...(isPosix ? [`plugins/node_modules/no-deps/index.js ${missing}`] : []), "on disk", + `${missing} ${missing}`, missing, `${missing} ${missing}`, `${missing} ${missing}`, @@ -603,6 +699,43 @@ if (isBun) { expect({ first: first.startsWith("/no-deps@2.0.0"), second }).toEqual({ first: true, second: first }); }); + test.concurrent("options.paths: a refusal by the exports of a copy on disk does not reach the registry", async () => { + const result = await runInProject({ + cwd: "a/b/project", + files: { + // The registry has no-deps with an index.js. The "exports" of this copy on disk leave index.js out. + "a/b/project/sealed/node_modules/no-deps/package.json": JSON.stringify({ + name: "no-deps", + exports: { "./main": "./index.js" }, + }), + "a/b/project/sealed/node_modules/no-deps/index.js": "", + "a/b/project/sub/file.js": "", + }, + packages: true, + source: ` + const inside = "sealed/node_modules/no-deps"; + console.log(resolve("no-deps/index.js", ["sealed"]), resolve("no-deps/index.js", [path.resolve("sealed"), "sub"])); + // An entry inside the copy is a search from the package itself. + console.log(resolve("no-deps/index.js", [inside]), resolve("no-deps/index.js", [path.resolve(inside), "."])); + // The refusal comes after the relative entry here. The search from the cwd does not follow it. + console.log(resolve("no-deps/index.js", ["sub", path.resolve("sealed")])); + // The second argument of require() takes the same way, so it loads no other copy. + try { + console.log(require("no-deps/index.js", { paths: ["sealed"] })); + } catch (error) { + console.log(error.code); + } + `, + }); + const missing = "MODULE_NOT_FOUND"; + expect(result).toEqual({ + stdout: [`${missing} ${missing}`, `${missing} ${missing}`, missing, missing], + stderr: "", + exitCode: 0, + requests: [], + }); + }); + test.concurrent("options.paths: the project of the cwd decides whether a miss installs", async () => { const result = await runInProject({ cwd: "root/app", From 40cd6ea826c79501b46c61312374b11af469ba8a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:57:50 +0000 Subject: [PATCH 15/15] resolver: split the package name with strings::rsplit The AOT test for a refusal also checks the exit code of the program. --- src/resolver/resolver.rs | 5 +---- ...e-answers-does-not-hang-on-the-working-directory.test.ts | 6 +++++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 689c586c1341..0aba7096d036 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -7235,10 +7235,7 @@ fn is_node_modules_copy(package_json: &[u8], name: &[u8]) -> bool { let Some(mut rest) = bun_paths::dirname(package_json) else { return false; }; - for part in name - .rsplit(|&c| c == b'/') - .chain([b"node_modules".as_slice()]) - { + for part in strings::rsplit(name, b"/").chain([b"node_modules".as_slice()]) { let Some((&separator, above)) = rest.strip_suffix(part).and_then(<[u8]>::split_last) else { return false; }; diff --git a/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts b/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts index c95875c14639..feccbaa6bbce 100644 --- a/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts +++ b/test/aot/what-require-resolve-answers-does-not-hang-on-the-working-directory.test.ts @@ -74,5 +74,9 @@ test("a refusal by the exports of the copy on disk stands for a relative entry, String(dir), ); expect(built.exitCode).toBe(0); - expect((await run([program], String(dir))).stdout).toBe("MODULE_NOT_FOUND MODULE_NOT_FOUND MODULE_NOT_FOUND\n"); + const ran = await run([program], String(dir)); + expect({ stdout: ran.stdout, exitCode: ran.exitCode }).toEqual({ + stdout: "MODULE_NOT_FOUND MODULE_NOT_FOUND MODULE_NOT_FOUND\n", + exitCode: 0, + }); });