Repository navigation
resolver: read package.json "type" from the nearest package.json, named or not - #41232
Conversation
…ed or not
The bundler picks the __toESM interop from the importer's module type.
The resolver took that type from the package.json that the resolution
recorded, or else from enclosing_package_json, which skips a
package.json without a "name". So it missed a { "type": "module" }
with no "name", in a project root or in a dual package's
dist/esm/package.json. A default import of a CommonJS module with
__esModule then got exports.default instead of the whole
module.exports that Node gives.
DirInfo now carries package_json_for_module_type: the nearest
package.json in the directory or above it, with or without a "name".
finalize_result reads "type" from it for the primary path. esbuild
uses the same rule.
|
Reproduced on main at 1b315c2 with the script in the Notes. Fail-before: 9 of the 10 new cases in |
|
Warning Review limit reached
On-demand reviews are free for the next 18 days. After that, they cost $0.25 per reviewed file. Or wait 7 minutes for your next included review. View limit detailsLimit details: You’ve used all 10 included reviews currently available. Review configuration: ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (4)
Comment |
There was a problem hiding this comment.
I reviewed this and didn't find any bugs. Because it changes core resolver semantics for module-type inference and the author flags a naming/semantics collision with open PR #40940 (same package_json_for_module_type field, different node_modules-boundary rule), a human should confirm the chosen rule and the coordination story before merge.
What was reviewed:
finalize_result:is_primaryis taken before theread_dir_infolet-else, so a failed primary dir read correctly prevents the secondary from settingmodule_type; extension override still runs afterward onpath_pair.primary.PathPair::iterskipsis_disabledentries, so a disabled primary would tag the secondary asprimary— same effective behavior as the old post-loopresult.package_jsonread, not a regression.dir_info_uncached: new field falls back to parent's value regardless ofis_node_modules/name, matching the doc comment;enclosing_package_jsonuntouched.package_json_refhas no remaining callers; tests 53–62 follow the file's existingitBundledfixtures and cover the nearest/nameless/no-type/above-node_modules/fallback-path matrix.
Extended reasoning...
Overview
The PR adds DirInfo::package_json_for_module_type — the nearest package.json (named or not, not stopping at node_modules) — populated in dir_info_uncached by info.package_json().or(parent.package_json_for_module_type). finalize_result now reads module_type from this field for the primary path inside the path-pair loop (guarded by a core::mem::take-based is_primary flag), replacing the post-loop read of result.package_json. The now-orphaned Result::package_json_ref helper is deleted (grep confirms no other callers). Ten itBundled cases (53–62) are added to test/bundler/bundler_cjs.test.ts covering nameless nested markers via main/module/relative/subdir, nameless project root, nested commonjs under module root, nearest-without-type as scope boundary, lookup crossing node_modules, and the primary-only rule for the main fallback.
Security risks
None. This is bundler module-resolution metadata (which package.json's "type" applies to a .js file). No untrusted input parsing, no auth/crypto/permissions, no new syscalls or FFI. The new field is an Option<&'static PackageJSON> following the exact pattern of the neighboring enclosing_package_json.
Level of scrutiny
Medium-high. The code change is small and mechanically simple — one new inherited field, one relocated conditional — but it alters how the bundler classifies every .js/.ts file's module type, which feeds __toESM's Node-mode flag and thus the shape of default imports across the entire bundle. Resolver semantics are subtle, historically regression-prone, and this PR itself is fixing a regression from #41150. The author explicitly notes four open PRs in this area, including #40940 which adds a field with the same name but a node_modules-stopping rule and runtime consumers; test 61 pins the crossing behavior for the bundler, but a maintainer should decide whether one field can serve both or the runtime read sites need their own. That coordination is a human call.
Other factors
The is_primary flag is taken before the read_dir_info let-else continue, so a primary whose directory can't be read won't let the secondary set module_type — intentional per test 62. PathPairIter::next() skips is_disabled paths, so a disabled primary would make the secondary the first yielded path and it would see primary == true; this mirrors the old behavior (which read result.package_json set by whichever path ran through the loop) and is not a new defect. Test coverage is thorough and follows the file's existing conventions (itBundled, shared cjsDepFiles/logDefaultAndNamed fixtures, onAfterBundle bundle-text assertion on case 53). No CODEOWNERS entries match the changed paths. The exit reason was dry_streak, so the hunt ran to exhaustion.
Problem
bun buildreads"type"from the wrong package.json, so it misses a{ "type": "module" }that has no"name". Two common places: a project root, and a dual package'sdist/esm/package.json..jsor.tsfile there getsexports.defaultfor the default import of a CommonJS module with__esModule. Node, esbuild and bun 1.4.0 give the wholemodule.exports. The bundle has__toESM(require_tsdep()), without, 1.finalize_result(src/resolver/resolver.rs:1669) read"type"from the package root, or else fromenclosing_package_json.dir_info_uncached(src/resolver/resolver.rs:6357) sets that field only for a named package.json (Support running package.json scripts from package.json without a name #229).Fix
DirInfogetspackage_json_for_module_type: the nearest package.json in the directory or above it, named or not.finalize_resultreads"type"from it for the primary path. The extension still wins."name"too.Result.module_type.enclosing_package_jsondoes not change. The four runtime lookups insrc/runtime/jsc_hooks.rsare out of scope.test/bundler/bundler_cjs.test.ts, 10 new cases, 9 fail on main. Self-reviewed: 3 concerns raised, 3 addressed. Other suites in Notes.Background
__toESM(mod, isNodeMode)builds the ESM view of a CommonJS module. With, 1(Node mode),defaultis the wholemodule.exports. Without it,defaultismod.defaultwhen__esModuleis set.DirInfois the resolver's cached record for one directory. Its "enclosing" fields come from the parent.Notes
Found by comparing
bun buildon main with bun 1.4.0, Node 26 and esbuild 0.25. No issue is open for it.Repro for the dual-package face:
For the project-root face, put
{ "type": "module" }(no"name") in the project's package.json and bundle a.jsfile that importstsdep.Faces of the bug on main. Each has a test:
"type"and no"name"(case 58)."main","module"or a relative path (cases 53, 55, 56). Through an exports map it worked, becausehandle_esm_resolutionreads the file's own directory."name", reached through"main"(case 54).result.package_jsonwas the package root, so the nested file was not read at all.Why a new field instead of widening
enclosing_package_json: that field also names the package forsideEffects, the auto-install version gate andbun runscript discovery. #33883 widens it for every consumer and had to rework thesideEffectsloop infinalize_resultto keep the DCE tests passing.Four cases pin the lookup rule. Each result matches esbuild 0.25.1:
{ "type": "commonjs" }below a"type": "module"package wins, because it is the nearest."type"is the scope. The lookup does not continue to a typed package root, so the importer is not ESM by type. Main read the root's"type"here. Node printsobject/functionfor this shape, but only because it detects ESM syntax in a file with no"type". bundler: pick the __toESM interop from the importer's module type #41150 chose the esbuild rule for such files.node_modulesdirectory. A package without a package.json of its own takes the"type"above it. Node prints the same result."module"is the primary path and"main"is the fallback forrequire(). The fallback's package.json does not count. esbuild has the same check. The case fails when the check is removed.Overlap with #40940: it adds a field with the same name, but its lookup stops at
node_modules, and the runtime reads it too. If #40940 lands after this PR, it must choose one rule for the field. Case 61 pins the crossing for the bundler. Node's stop can still apply at the runtime read sites. #40940 also calls the lookup for the fallback path, which case 62 rejects.Out of scope: the runtime's four lookups (
src/runtime/jsc_hooks.rslines 1474, 2972, 3220 and 4071) keeppackage_json().or(enclosing_package_json). Sobun runstill skips a nameless package.json above the file's own directory. That gap predates #41150. For this import,bun run1.4.1 givesexports.defaultfor every importer, even.mjs.Self-review, the three concerns and what changed:
node_modulesrule on the field. Done insrc/resolver/dir_info.rs."main"and"module". That is case 62.Suites run with the fix on a debug ASAN build, after a rebase on main:
bundler_cjs(62),esbuild/packagejson,esbuild/dce,esbuild/default,bundler_cjs2esm,bundler_npm,bundler_edgecase,bundler_regressions,bundler_splitting,bundler_barrel,cli/run/run-cjs,test/js/bun/resolve. All pass except the second case oftest/js/bun/resolve/load-same-js-file-a-lot.test.ts. It times out at 5 s on this build with and without this change (back-to-back runs on the same machine).[human-review] gate passed · iteration 0 · 4 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 0
evidence per changed file