diff --git a/src/resolver/dir_info.rs b/src/resolver/dir_info.rs index 399dda0c87ca..84b68a5a6d63 100644 --- a/src/resolver/dir_info.rs +++ b/src/resolver/dir_info.rs @@ -126,6 +126,11 @@ pub struct DirInfo { // ergonomics. If a write is ever added, retype to `Option>`. pub enclosing_package_json: Option<&'static PackageJSON>, + /// Nearest `package.json` walking up from this directory, regardless of + /// whether it has a `"name"` or parsed successfully. This is Node's + /// package-scope boundary for module-type (`"type"` field) resolution. + pub nearest_package_json: Option<&'static PackageJSON>, + // `NonNull` (not `&'static`) so `enqueue_dependency_to_resolve` can write // `package_manager_package_id` back through it without a const→mut // provenance cast. Read via `.package_json_for_dependencies()`. @@ -157,6 +162,7 @@ impl Default for DirInfo { package_json_for_browser_field: None, enclosing_tsconfig_json: None, enclosing_package_json: None, + nearest_package_json: None, package_json_for_dependencies: None, abs_path: b"", entries: Index::default(), diff --git a/src/resolver/package_json.rs b/src/resolver/package_json.rs index ebf773804acf..1e8d0038d645 100644 --- a/src/resolver/package_json.rs +++ b/src/resolver/package_json.rs @@ -138,6 +138,11 @@ pub struct PackageJSON { pub exports: Option, pub imports: Option, + + /// Set when the file is malformed JSON, a non-object, or has a non-string + /// `"type"`. Node throws `ERR_INVALID_PACKAGE_CONFIG` for `.js` files under + /// such a scope; the runtime loader surfaces this. + pub invalid: bool, } // hand-rolled `Default` because `#[derive(Default)]` would zero @@ -165,6 +170,7 @@ impl Default for PackageJSON { browser_map: BrowserMap::default(), exports: None, imports: None, + invalid: false, } } } @@ -335,6 +341,14 @@ impl FileSystemPackageJsonExt for crate::fs::FileSystem { } impl PackageJSON { + /// Poisoned (unparseable / non-object) placeholder returned by `parse()`. + /// Distinct from a parseable object whose `"type"` is not a string, which + /// also sets `invalid` but retains `source_contents`. + #[inline] + pub fn is_poisoned(&self) -> bool { + self.invalid && self.source_contents.is_empty() + } + pub fn parse_macros_json( macros: js_ast::Expr, log: &mut bun_ast::Log, @@ -500,15 +514,27 @@ impl PackageJSON { // On the success path it is *moved* (not leaked) into // `package_json.source_contents` at the bottom of this fn, so the heap // allocation lives for the life of the returned `PackageJSON`. On every - // early `return None` below `entry_contents` drops and frees normally, after - // `json_source` is already dead. `Box<[u8]>` heap address is stable - // across the move. + // early return below (the `invalid(...)` paths) `entry_contents` drops and + // frees normally after `json_source` is already dead; the poisoned entry's + // `source` uses `b""` and does not reference these bytes. `Box<[u8]>` heap + // address is stable across the move. let contents_static: &'static [u8] = unsafe { bun_ptr::detach_lifetime(&entry_contents) }; let json_source = bun_ast::Source::init_path_string(package_json_path, contents_static); + // An unparseable package.json is still a package scope boundary in + // Node (`ERR_INVALID_PACKAGE_CONFIG`); return a poisoned entry so + // `nearest_package_json` stops here instead of inheriting the parent. + let invalid = |path: &'static [u8]| { + Some(PackageJSON { + source: bun_ast::Source::init_path_string(path, b""), + invalid: true, + ..PackageJSON::default() + }) + }; + let parsed_json = match r.caches.json.parse_package_json(r_log, &json_source) { Ok(Some(v)) => v, - Ok(None) => return None, + Ok(None) => return invalid(package_json_path), Err(err) => { if cfg!(debug_assertions) { Output::print_error(format_args!( @@ -517,16 +543,13 @@ impl PackageJSON { bstr::BStr::new(err.name()) )); } - return None; + return invalid(package_json_path); } }; let json: js_ast::Expr = parsed_json.root; if !json.is_object() { - // Invalid package.json in node_modules is noisy. - // Let's just ignore it. - // (allocator.free dropped — entry.contents owned by `entry`) - return None; + return invalid(package_json_path); } let mut package_json = PackageJSON { @@ -550,6 +573,7 @@ impl PackageJSON { side_effects: SideEffects::Unspecified, exports: None, imports: None, + invalid: false, }; // shadow as `&Source`; the owned value is reconstructed at the bottom // (Source isn't `Clone`). @@ -602,6 +626,8 @@ impl PackageJSON { } } } else { + // Non-string `"type"` is `ERR_INVALID_PACKAGE_CONFIG` in Node. + package_json.invalid = true; r_log.add_warning( Some(json_source), type_json.loc, diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 0c6c7618f556..7f1faf779df8 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -6217,6 +6217,7 @@ impl<'a> Resolver<'a> { info.enclosing_package_json = info .enclosing_package_json .or(parent_.enclosing_package_json); + info.nearest_package_json = parent_.package_json().or(parent_.nearest_package_json); info.package_json_for_dependencies = info .package_json_for_dependencies .or(parent_.package_json_for_dependencies); @@ -6337,6 +6338,10 @@ impl<'a> Resolver<'a> { }; if let Some(pkg) = info.package_json() { + // Any package.json (named, nameless, or invalid) is + // Node's module-type scope boundary. + info.nearest_package_json = Some(pkg); + if pkg.browser_map.count() > 0 { info.enclosing_browser_scope = result.index; info.package_json_for_browser_field = Some(pkg); diff --git a/src/runtime/cli/filter_run.rs b/src/runtime/cli/filter_run.rs index 6f771aa805d5..065c10c7ea97 100644 --- a/src/runtime/cli/filter_run.rs +++ b/src/runtime/cli/filter_run.rs @@ -764,7 +764,8 @@ pub(crate) fn run_scripts_with_filter( bun_sys::Fd::invalid(), None, IncludeScripts::IncludeScripts, - ) else { + ) + .filter(|p| !p.is_poisoned()) else { bun_core::warn!( "Failed to read {}, skipping this workspace package\n", bun_core::fmt::quote(&*package_json_path), diff --git a/src/runtime/cli/multi_run.rs b/src/runtime/cli/multi_run.rs index 629fabd976c1..386d162004cf 100644 --- a/src/runtime/cli/multi_run.rs +++ b/src/runtime/cli/multi_run.rs @@ -891,7 +891,8 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result { dir_info .package_json() - .or(dir_info.enclosing_package_json) + .or(dir_info.nearest_package_json) .map(core::ptr::from_ref::) } _ => None, @@ -2754,7 +2754,7 @@ fn transpile_source_code_inner( .read_dir_info(source.path.name().dir) } { Ok(Some(dir_info)) => { - dir_info.package_json().or(dir_info.enclosing_package_json) + dir_info.package_json().or(dir_info.nearest_package_json) } _ => None, } @@ -3028,7 +3028,7 @@ fn transpile_source_code_inner( match unsafe { (*jsc_vm).transpiler.resolver.read_dir_info(dir) } { Ok(Some(dir_info)) => dir_info .package_json() - .or(dir_info.enclosing_package_json) + .or(dir_info.nearest_package_json) .map(|p| p.module_type), _ => None, } @@ -3922,7 +3922,7 @@ unsafe fn get_loader_and_virtual_source<'a>( // SAFETY: per fn contract — `transpiler.resolver` is a value field of // the VM; `read_dir_info` is re-entrant on the JS thread. match unsafe { (*jsc_vm).transpiler.resolver.read_dir_info(dir) } { - Ok(Some(dir_info)) => dir_info.package_json().or(dir_info.enclosing_package_json), + Ok(Some(dir_info)) => dir_info.package_json().or(dir_info.nearest_package_json), _ => None, } } else { @@ -4155,11 +4155,29 @@ unsafe fn transpile_file( } // regex /\.[jt]s$/ if ext.len() == b".ts".len() && (ext == b".js" || ext == b".ts") { - // Use the package.json module type if it exists. - break 'brk lr - .package_json - .map(|pkg| pkg.module_type) - .unwrap_or(ModuleType::Unknown); + // Node refuses `.js` under a malformed/non-string-`"type"` + // package.json; falling back to content-sniffing here would + // silently change module semantics vs Node. + if let Some(pkg) = lr.package_json { + if pkg.invalid { + let js = global_ref + .err( + bun_jsc::ErrCode::ERR_INVALID_PACKAGE_CONFIG, + format_args!( + "Invalid package config {}.", + bstr::BStr::new(pkg.source.path.text) + ), + ) + .to_js(); + // SAFETY: per fn contract — `ret` is a valid out-param. + unsafe { + *ret = ErrorableResolvedSource::err(bun_core::err!("JSErrorObject"), js); + } + return ptr::null_mut(); + } + break 'brk pkg.module_type; + } + break 'brk ModuleType::Unknown; } // For JSX/TSX and other extensions, let the file contents decide. ModuleType::Unknown diff --git a/test/cli/run/filter-workspace.test.ts b/test/cli/run/filter-workspace.test.ts index 00444ee553ae..6c015ca1eebe 100644 --- a/test/cli/run/filter-workspace.test.ts +++ b/test/cli/run/filter-workspace.test.ts @@ -661,4 +661,30 @@ describe("bun", () => { expect(stderr).toContain("skipping this workspace package"); expect(exitCode).toBe(0); }); + + test('non-string "type" does not stop --filter from running scripts', async () => { + // "type" is a module-loader concern; a non-string value must not make + // `bun run --filter` skip the package (npm/pnpm/yarn all run it). + const dir = tempDirWithFiles("filter-bad-type", { + packages: { + foo: { + "package.json": `{"name":"foo","type":42,"scripts":{"go":"echo built-foo"}}`, + }, + }, + "package.json": JSON.stringify({ name: "ws", workspaces: ["packages/*"] }), + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "run", "--filter", "*", "go"], + cwd: dir, + env: { ...bunEnv, NO_COLOR: "1" }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout).toContain("built-foo"); + expect(stderr).not.toContain("Failed to read"); + expect(stderr).not.toContain("skipping this workspace package"); + expect(exitCode).toBe(0); + }); }); diff --git a/test/cli/run/run_command.test.ts b/test/cli/run/run_command.test.ts index c2f298a26aff..29cd8fd20c0c 100644 --- a/test/cli/run/run_command.test.ts +++ b/test/cli/run/run_command.test.ts @@ -19,6 +19,24 @@ describe("bun", () => { expect(exitCode).toBe(1); }); + test('non-string "type" does not hide scripts from bun run', () => { + // "type" is a module-loader concern; a non-string value must not make + // `bun run