From a4591cd54cdae0bf35fea8252e5179842c552d81 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:46:11 +0000 Subject: [PATCH 01/10] compile: resolve a node_modules package through its package.json when package.json autoload is off A standalone executable turns the resolver's load_package_json off by default. That gate skipped every package.json, including the one of a package inside node_modules, so a require() of a dependency with a main or exports field failed with Cannot find module. The gate now applies to a directory outside node_modules only. A package inside node_modules is read either way: its main and exports are the resolution algorithm, not a config file of the runtime environment. --- docs/bundler/executables.mdx | 2 +- src/resolver/options.rs | 3 +++ src/resolver/resolver.rs | 6 +++-- test/bundler/bundler_compile.test.ts | 20 ++++++++++++-- test/bundler/bundler_compile_autoload.test.ts | 26 ++++++++++++++----- 5 files changed, 45 insertions(+), 12 deletions(-) diff --git a/docs/bundler/executables.mdx b/docs/bundler/executables.mdx index a05760ff47be..85196c63c841 100644 --- a/docs/bundler/executables.mdx +++ b/docs/bundler/executables.mdx @@ -447,7 +447,7 @@ BUN_OPTIONS="--smol --cpu-prof-md" ./myapp Standalone executables can automatically load configuration files from the directory where they are run. By default: -- **`tsconfig.json`** and **`package.json`** loading is **disabled** — these are typically only needed at development time, and the bundler already uses them when compiling +- **`tsconfig.json`** and **`package.json`** loading is **disabled** — these are typically only needed at development time, and the bundler already uses them when compiling. This applies to the project's own `package.json` (its `"type"`, `"imports"`, and self-reference through `"exports"`). A package inside `node_modules` is still resolved through its own `package.json`, so a `require()` of a dependency that is not embedded keeps working. - **`.env`** and **`bunfig.toml`** loading is **enabled** — these often contain runtime configuration that may vary per deployment diff --git a/src/resolver/options.rs b/src/resolver/options.rs index 5980b9ab38df..dcb96b3cb060 100644 --- a/src/resolver/options.rs +++ b/src/resolver/options.rs @@ -183,6 +183,9 @@ pub struct BundleOptions { // projects this from its own `Option>` field // (CLI-owned `Box`, process-lifetime). pub install: Option>, + /// Read the `package.json` of a directory outside `node_modules`. A package inside + /// `node_modules` is read either way: a standalone executable turns this off and still + /// resolves a dependency from disk by its `main` and `exports`. pub load_package_json: bool, pub load_tsconfig_json: bool, pub main_field_extension_order: Box<[Box<[u8]>]>, diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index a22e66c4e69d..9830523bdcd6 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -6427,8 +6427,10 @@ impl<'a> Resolver<'a> { } } - // Record if this directory has a package.json file - if self.opts.load_package_json { + // Record if this directory has a package.json file. A package inside `node_modules` is + // read with `load_package_json` off: its `main` and `exports` are the resolution + // algorithm, not a config file of the runtime environment. + if self.opts.load_package_json || info.is_inside_node_modules() { if let Some(lookup) = entries!().get_comptime_query(b"package.json") { // SAFETY: EntryStore-owned slot; `entries_mutex` held — read-only borrow, // dies (NLL) before any later `&mut` to this slot. diff --git a/test/bundler/bundler_compile.test.ts b/test/bundler/bundler_compile.test.ts index ac147a1d9dbd..8869bfa37f41 100644 --- a/test/bundler/bundler_compile.test.ts +++ b/test/bundler/bundler_compile.test.ts @@ -988,22 +988,38 @@ describe("bundler", () => { const req = (x) => require(x); const y = req('commonjs'); const z = req('esm').default; - console.log(JSON.stringify([w, x, y, z])); + const m = req('with-main'); + const e = req('with-exports/feature'); + console.log(JSON.stringify([w, x, y, z, m, e])); module.exports = null; `, "/node_modules/commonjs/index.js": "throw new Error('Must be runtime import.')", "/node_modules/esm/index.js": "throw new Error('Must be runtime import.')", "/node_modules/other/index.js": "throw new Error('Must be runtime import.')", "/node_modules/other-esm/index.js": "throw new Error('Must be runtime import.')", + "/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }), + "/node_modules/with-main/lib/main.js": "throw new Error('Must be runtime import.')", + "/node_modules/with-exports/package.json": JSON.stringify({ + name: "with-exports", + exports: { "./feature": "./lib/feature.js" }, + }), + "/node_modules/with-exports/lib/feature.js": "throw new Error('Must be runtime import.')", }, runtimeFiles: { "/node_modules/commonjs/index.js": "module.exports = 2; require('other');", "/node_modules/esm/index.js": "import 'other-esm'; export default 3;", "/node_modules/other/index.js": "globalThis.x = 1;", "/node_modules/other-esm/index.js": "globalThis.w = 0;", + "/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }), + "/node_modules/with-main/lib/main.js": "module.exports = 4;", + "/node_modules/with-exports/package.json": JSON.stringify({ + name: "with-exports", + exports: { "./feature": "./lib/feature.js" }, + }), + "/node_modules/with-exports/lib/feature.js": "module.exports = 5;", }, run: { - stdout: "[0,1,2,3]", + stdout: "[0,1,2,3,4,5]", setCwd: true, }, compile: true, diff --git a/test/bundler/bundler_compile_autoload.test.ts b/test/bundler/bundler_compile_autoload.test.ts index 6b4338c26985..315985a03e36 100644 --- a/test/bundler/bundler_compile_autoload.test.ts +++ b/test/bundler/bundler_compile_autoload.test.ts @@ -486,23 +486,35 @@ console.log("PRELOAD"); }, }); - // Test that package.json exports are NOT loaded when autoloadPackageJson: false (default) - // The import should fail because my-runtime-pkg/utils cannot be resolved without package.json exports + // Test that the project's own package.json is NOT loaded when autoloadPackageJson: false (default). + // A self-reference through its "exports" fails. A package inside node_modules is still resolved + // through its own package.json: that is the resolution algorithm, not a config file. itBundled("compile/AutoloadPackageJsonExportsDisabled", { compile: { autoloadPackageJson: false, }, files: { "/entry.js": /* js */ ` - // Without runtime package.json, my-runtime-pkg/utils cannot be resolved + const selfName = "my-app"; const pkgName = "my-runtime-pkg"; const subpath = "utils"; - import(pkgName + "/" + subpath) - .then(m => console.log(m.default)) - .catch(() => console.log("import-failed-as-expected")); + const self = import(selfName + "/" + subpath) + .then(m => m.default) + .catch(() => "self-reference-failed-as-expected"); + const dep = import(pkgName + "/" + subpath) + .then(m => m.default) + .catch(e => "import-failed: " + e.message); + Promise.all([self, dep]).then(lines => console.log(lines.join("\\n"))); `, }, runtimeFiles: { + "/package.json": JSON.stringify({ + name: "my-app", + exports: { + "./utils": "./src/utils.js", + }, + }), + "/src/utils.js": `export default "utils-from-self-reference";`, "/node_modules/my-runtime-pkg/package.json": JSON.stringify({ name: "my-runtime-pkg", exports: { @@ -512,7 +524,7 @@ console.log("PRELOAD"); "/node_modules/my-runtime-pkg/lib/utilities.js": `export default "utilities-from-package-exports";`, }, run: { - stdout: "import-failed-as-expected", + stdout: "self-reference-failed-as-expected\nutilities-from-package-exports", setCwd: true, }, }); From 68d8d259fc15ecd4e1407d7a545a9dc1f94dd372 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:38:42 +0000 Subject: [PATCH 02/10] test: add sibling compile tests for package.json main, --external, and the autoload flag on --- test/bundler/bundler_compile.test.ts | 56 ++++++++++++++++--- test/bundler/bundler_compile_autoload.test.ts | 30 ++++++++++ 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/test/bundler/bundler_compile.test.ts b/test/bundler/bundler_compile.test.ts index 8869bfa37f41..a0d63c70383a 100644 --- a/test/bundler/bundler_compile.test.ts +++ b/test/bundler/bundler_compile.test.ts @@ -988,15 +988,37 @@ describe("bundler", () => { const req = (x) => require(x); const y = req('commonjs'); const z = req('esm').default; - const m = req('with-main'); - const e = req('with-exports/feature'); - console.log(JSON.stringify([w, x, y, z, m, e])); + console.log(JSON.stringify([w, x, y, z])); module.exports = null; `, "/node_modules/commonjs/index.js": "throw new Error('Must be runtime import.')", "/node_modules/esm/index.js": "throw new Error('Must be runtime import.')", "/node_modules/other/index.js": "throw new Error('Must be runtime import.')", "/node_modules/other-esm/index.js": "throw new Error('Must be runtime import.')", + }, + runtimeFiles: { + "/node_modules/commonjs/index.js": "module.exports = 2; require('other');", + "/node_modules/esm/index.js": "import 'other-esm'; export default 3;", + "/node_modules/other/index.js": "globalThis.x = 1;", + "/node_modules/other-esm/index.js": "globalThis.w = 0;", + }, + run: { + stdout: "[0,1,2,3]", + setCwd: true, + }, + compile: true, + }); + // A package inside node_modules is resolved through its own package.json at runtime, even + // though the executable does not load the project's package.json by default. + itBundled("compile/DynamicRequirePackageJsonMainAndExports", { + files: { + "/entry.tsx": /* tsx */ ` + const req = (x) => require(x); + const m = req('with-main'); + const e = req('with-exports/feature'); + console.log(JSON.stringify([m, e])); + module.exports = null; + `, "/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }), "/node_modules/with-main/lib/main.js": "throw new Error('Must be runtime import.')", "/node_modules/with-exports/package.json": JSON.stringify({ @@ -1006,10 +1028,6 @@ describe("bundler", () => { "/node_modules/with-exports/lib/feature.js": "throw new Error('Must be runtime import.')", }, runtimeFiles: { - "/node_modules/commonjs/index.js": "module.exports = 2; require('other');", - "/node_modules/esm/index.js": "import 'other-esm'; export default 3;", - "/node_modules/other/index.js": "globalThis.x = 1;", - "/node_modules/other-esm/index.js": "globalThis.w = 0;", "/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }), "/node_modules/with-main/lib/main.js": "module.exports = 4;", "/node_modules/with-exports/package.json": JSON.stringify({ @@ -1019,7 +1037,29 @@ describe("bundler", () => { "/node_modules/with-exports/lib/feature.js": "module.exports = 5;", }, run: { - stdout: "[0,1,2,3,4,5]", + stdout: "[4,5]", + setCwd: true, + }, + compile: true, + }); + // A static import of an --external package is resolved at startup from the cwd's node_modules + // through the package's main field. + itBundled("compile/ExternalPackageWithMain", { + external: ["with-main"], + files: { + "/entry.tsx": /* tsx */ ` + import value from "with-main"; + console.log(value); + `, + "/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }), + "/node_modules/with-main/lib/main.js": "throw new Error('Must be runtime import.')", + }, + runtimeFiles: { + "/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }), + "/node_modules/with-main/lib/main.js": "module.exports = 'external-main';", + }, + run: { + stdout: "external-main", setCwd: true, }, compile: true, diff --git a/test/bundler/bundler_compile_autoload.test.ts b/test/bundler/bundler_compile_autoload.test.ts index 315985a03e36..045f6919ef2e 100644 --- a/test/bundler/bundler_compile_autoload.test.ts +++ b/test/bundler/bundler_compile_autoload.test.ts @@ -486,6 +486,36 @@ console.log("PRELOAD"); }, }); + // Test that the project's own package.json is loaded when autoloadPackageJson: true. + // A self-reference through its "exports" resolves. + itBundled("compile/AutoloadPackageJsonSelfReferenceEnabled", { + compile: { + autoloadPackageJson: true, + }, + files: { + "/entry.js": /* js */ ` + const selfName = "my-app"; + const subpath = "utils"; + import(selfName + "/" + subpath) + .then(m => console.log(m.default)) + .catch(e => console.log("import-failed: " + e.message)); + `, + }, + runtimeFiles: { + "/package.json": JSON.stringify({ + name: "my-app", + exports: { + "./utils": "./src/utils.js", + }, + }), + "/src/utils.js": `export default "utils-from-self-reference";`, + }, + run: { + stdout: "utils-from-self-reference", + setCwd: true, + }, + }); + // Test that the project's own package.json is NOT loaded when autoloadPackageJson: false (default). // A self-reference through its "exports" fails. A package inside node_modules is still resolved // through its own package.json: that is the resolution algorithm, not a config file. From 332adc9449e246bd771b9ea38701c3fc073064aa Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:00:28 +0000 Subject: [PATCH 03/10] resolver: shorten the load_package_json comments --- src/resolver/options.rs | 4 +--- src/resolver/resolver.rs | 5 ++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/resolver/options.rs b/src/resolver/options.rs index dcb96b3cb060..f93f027c785d 100644 --- a/src/resolver/options.rs +++ b/src/resolver/options.rs @@ -183,9 +183,7 @@ pub struct BundleOptions { // projects this from its own `Option>` field // (CLI-owned `Box`, process-lifetime). pub install: Option>, - /// Read the `package.json` of a directory outside `node_modules`. A package inside - /// `node_modules` is read either way: a standalone executable turns this off and still - /// resolves a dependency from disk by its `main` and `exports`. + /// Read the `package.json` of a directory outside `node_modules`. One inside is always read. pub load_package_json: bool, pub load_tsconfig_json: bool, pub main_field_extension_order: Box<[Box<[u8]>]>, diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 9830523bdcd6..f9aefcf1b32b 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -6427,9 +6427,8 @@ impl<'a> Resolver<'a> { } } - // Record if this directory has a package.json file. A package inside `node_modules` is - // read with `load_package_json` off: its `main` and `exports` are the resolution - // algorithm, not a config file of the runtime environment. + // Record if this directory has a package.json file. A package inside node_modules is + // read either way: its `main` and `exports` are resolution, not project config. if self.opts.load_package_json || info.is_inside_node_modules() { if let Some(lookup) = entries!().get_comptime_query(b"package.json") { // SAFETY: EntryStore-owned slot; `entries_mutex` held — read-only borrow, From f71926f2bf72b3dfa0f0161eff962be42eedcd48 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:02:02 +0000 Subject: [PATCH 04/10] resolver: keep the original package.json 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 f9aefcf1b32b..061d1c53bd0a 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -6427,8 +6427,7 @@ impl<'a> Resolver<'a> { } } - // Record if this directory has a package.json file. A package inside node_modules is - // read either way: its `main` and `exports` are resolution, not project config. + // Record if this directory has a package.json file if self.opts.load_package_json || info.is_inside_node_modules() { if let Some(lookup) = entries!().get_comptime_query(b"package.json") { // SAFETY: EntryStore-owned slot; `entries_mutex` held — read-only borrow, From e7b9b843167a0595ad5b1406b293a4c6df10e35e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:40:18 +0000 Subject: [PATCH 05/10] compile: gate package.json autoload on the cwd and its parents, not on node_modules The flag turns off the project's package.json: the cwd and its parent directories. Any other package.json is a resolution target and is read. That covers a package that node_modules reaches by symlink (a workspace or bun link), a NODE_PATH directory, and a directory required by path. Reword the --help text, the JSDoc, and the docs to the narrowed meaning. The flag-on tests now observe the flag through the project's own package.json (self-reference exports and #imports). --- docs/bundler/executables.mdx | 8 +- docs/snippets/cli/build.mdx | 4 +- packages/bun-types/bun.d.ts | 4 +- src/resolver/options.rs | 2 +- src/resolver/resolver.rs | 9 +- src/runtime/cli/Arguments.rs | 4 +- test/bundler/bundler_compile.test.ts | 53 ++++++++++- test/bundler/bundler_compile_autoload.test.ts | 94 ++++++++----------- 8 files changed, 110 insertions(+), 68 deletions(-) diff --git a/docs/bundler/executables.mdx b/docs/bundler/executables.mdx index 85196c63c841..4cbde9cd8d97 100644 --- a/docs/bundler/executables.mdx +++ b/docs/bundler/executables.mdx @@ -447,7 +447,7 @@ BUN_OPTIONS="--smol --cpu-prof-md" ./myapp Standalone executables can automatically load configuration files from the directory where they are run. By default: -- **`tsconfig.json`** and **`package.json`** loading is **disabled** — these are typically only needed at development time, and the bundler already uses them when compiling. This applies to the project's own `package.json` (its `"type"`, `"imports"`, and self-reference through `"exports"`). A package inside `node_modules` is still resolved through its own `package.json`, so a `require()` of a dependency that is not embedded keeps working. +- **`tsconfig.json`** and **`package.json`** loading is **disabled** — these are typically only needed at development time, and the bundler already uses them when compiling. This applies to the `package.json` of the directory the executable runs in and of its parent directories (the project's `"type"`, `"imports"`, and self-reference through `"exports"`). Any other `package.json`, such as a dependency's in `node_modules`, is always read, so a `require()` of a dependency that is not embedded keeps working. - **`.env`** and **`bunfig.toml`** loading is **enabled** — these often contain runtime configuration that may vary per deployment @@ -456,7 +456,7 @@ Standalone executables can automatically load configuration files from the direc ### Enabling config loading at runtime -If your executable needs to read `tsconfig.json` or `package.json` at runtime, opt in with these flags: +If your executable needs to read `tsconfig.json` or the project's `package.json` at runtime, opt in with these flags: ```bash icon="terminal" terminal # Enable runtime loading of tsconfig.json @@ -494,7 +494,7 @@ To disable `.env` or `bunfig.toml` loading for deterministic execution: compile: { // tsconfig.json and package.json are disabled by default autoloadTsconfig: true, // Enable tsconfig.json loading - autoloadPackageJson: true, // Enable package.json loading + autoloadPackageJson: true, // Enable the project's package.json loading // .env and bunfig.toml are enabled by default autoloadDotenv: false, // Disable .env loading @@ -1299,7 +1299,7 @@ interface CompileBuildOptions { execArgv?: string[]; // Runtime arguments (process.execArgv) executablePath?: string; // Bun executable to use instead of downloading one for target autoloadTsconfig?: boolean; // Load tsconfig.json (default: false) - autoloadPackageJson?: boolean; // Load package.json (default: false) + autoloadPackageJson?: boolean; // Load the project's package.json (default: false) autoloadDotenv?: boolean; // Load .env files (default: true) autoloadBunfig?: boolean; // Load bunfig.toml (default: true) bytecodeOrder?: string | string[] | false | null; // Order file(s) to lay the bytecode out by (requires bytecode: true) diff --git a/docs/snippets/cli/build.mdx b/docs/snippets/cli/build.mdx index f68cdee2a2b8..e7eea6066224 100644 --- a/docs/snippets/cli/build.mdx +++ b/docs/snippets/cli/build.mdx @@ -227,11 +227,11 @@ bun build - Enable autoloading of package.json at runtime in the standalone executable + Read the project's own package.json at runtime in the standalone executable. A dependency's package.json is always read - Disable autoloading of package.json at runtime in the standalone executable + Do not read the project's own package.json at runtime in the standalone executable diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 59aa530c8e58..6deceb33856d 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -3772,7 +3772,9 @@ declare module "bun" { */ autoloadTsconfig?: boolean; /** - * Whether the standalone executable loads package.json when it runs + * Whether the standalone executable reads the project's own package.json + * (its `type`, `imports`, and self-reference `exports`) when it runs. + * A dependency's package.json is always read. * * Equivalent CLI flags: `--compile-autoload-package-json`, `--no-compile-autoload-package-json` * diff --git a/src/resolver/options.rs b/src/resolver/options.rs index f93f027c785d..9670adf3237b 100644 --- a/src/resolver/options.rs +++ b/src/resolver/options.rs @@ -183,7 +183,7 @@ pub struct BundleOptions { // projects this from its own `Option>` field // (CLI-owned `Box`, process-lifetime). pub install: Option>, - /// Read the `package.json` of a directory outside `node_modules`. One inside is always read. + /// Read the `package.json` of the cwd and its parents. Any other `package.json` is always read. pub load_package_json: bool, pub load_tsconfig_json: bool, pub main_field_extension_order: Box<[Box<[u8]>]>, diff --git a/src/resolver/resolver.rs b/src/resolver/resolver.rs index 061d1c53bd0a..c2074d49adad 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -6428,7 +6428,7 @@ impl<'a> Resolver<'a> { } // Record if this directory has a package.json file - if self.opts.load_package_json || info.is_inside_node_modules() { + if self.opts.load_package_json || !self.is_project_config_dir(path) { if let Some(lookup) = entries!().get_comptime_query(b"package.json") { // SAFETY: EntryStore-owned slot; `entries_mutex` held — read-only borrow, // dies (NLL) before any later `&mut` to this slot. @@ -6700,6 +6700,13 @@ impl<'a> Resolver<'a> { Ok(None) } + /// `dir` is the cwd or one of its parents. Their `package.json` is the project's config, + /// which `load_package_json` gates. Any other `package.json` is a resolution target. + fn is_project_config_dir(&self, dir: &[u8]) -> bool { + use ResolvePath::resolve_path::{ParentEqual, is_parent_or_equal}; + is_parent_or_equal(dir, self.fs_ref().top_level_dir()) != ParentEqual::Unrelated + } + /// `opts.tsconfig_override`, which this resolver and its workers read in place of the /// configuration file of every directory. It is not in `DirInfo`, which every resolver of the /// process shares: the runtime, and every `Bun.build`. `None`: there is none. diff --git a/src/runtime/cli/Arguments.rs b/src/runtime/cli/Arguments.rs index 25d776264ca0..9b177e776d45 100644 --- a/src/runtime/cli/Arguments.rs +++ b/src/runtime/cli/Arguments.rs @@ -433,10 +433,10 @@ pub(crate) const BUILD_ONLY_PARAMS: &[ParamType] = concat_params!( "--no-compile-autoload-tsconfig Disable autoloading of tsconfig.json at runtime in standalone executable" ), parse_param!( - "--compile-autoload-package-json Enable autoloading of package.json at runtime in standalone executable (default: false)" + "--compile-autoload-package-json Read the project's package.json at runtime in standalone executable (default: false)" ), parse_param!( - "--no-compile-autoload-package-json Disable autoloading of package.json at runtime in standalone executable" + "--no-compile-autoload-package-json Do not read the project's package.json at runtime in standalone executable" ), parse_param!( "--compile-executable-path Path to a Bun executable to use for cross-compilation instead of downloading" diff --git a/test/bundler/bundler_compile.test.ts b/test/bundler/bundler_compile.test.ts index a0d63c70383a..6da7e31770c3 100644 --- a/test/bundler/bundler_compile.test.ts +++ b/test/bundler/bundler_compile.test.ts @@ -1,6 +1,6 @@ import { Database } from "bun:sqlite"; import { describe, expect, test } from "bun:test"; -import { rmSync } from "fs"; +import { rmSync, symlinkSync } from "fs"; import { bunEnv, bunExe, isWindows, tempDir } from "harness"; import { join } from "path"; import { BundlerTestInput, itBundled as itBundledBase } from "./expectBundled"; @@ -1601,6 +1601,57 @@ const server = serve({ }, 30_000); // When compiling with 8+ entry points, the main entry point should still run correctly. + // A package that node_modules reaches by symlink (a workspace or `bun link`) has its own + // package.json read at runtime: its main, its exports, and its #imports from the real path. + test.skipIf(isWindows)("compile resolves a symlinked node_modules package through its package.json", async () => { + await using dir = tempDir("compile-linked-pkg", { + "app.js": ` + const req = (x) => require(x); + console.log(JSON.stringify([req("linked-pkg"), req("linked-pkg/feature")])); + `, + "packages/linked-pkg/package.json": JSON.stringify({ + name: "linked-pkg", + main: "lib/main.js", + exports: { ".": "./lib/main.js", "./feature": "./lib/feature.js" }, + imports: { "#util": "./lib/util.js" }, + }), + "packages/linked-pkg/lib/main.js": `module.exports = require("#util") + "-main";`, + "packages/linked-pkg/lib/feature.js": `module.exports = require("#util") + "-feature";`, + "packages/linked-pkg/lib/util.js": `module.exports = "util";`, + "node_modules/.keep": "", + }); + symlinkSync(join(String(dir), "packages", "linked-pkg"), join(String(dir), "node_modules", "linked-pkg")); + + await Bun.$`${bunExe()} build --compile app.js --outfile app`.cwd(dir).env(bunEnv).throws(true); + + const result = await Bun.$`./app`.cwd(dir).env(bunEnv).nothrow(); + expect(result.stderr.toString()).toBe(""); + expect(result.stdout.toString().trim()).toBe('["util-main","util-feature"]'); + expect(result.exitCode).toBe(0); + }); + + // A directory on NODE_PATH is not the project's config, so its package.json is read. + test("compile resolves a NODE_PATH package through its package.json main", async () => { + await using dir = tempDir("compile-node-path-pkg", { + "app.js": ` + const req = (x) => require(x); + console.log(req("path-pkg")); + `, + "libs/path-pkg/package.json": JSON.stringify({ name: "path-pkg", main: "lib/main.js" }), + "libs/path-pkg/lib/main.js": `module.exports = "from-node-path";`, + }); + + await Bun.$`${bunExe()} build --compile app.js --outfile app`.cwd(dir).env(bunEnv).throws(true); + + const result = await Bun.$`./app` + .cwd(dir) + .env({ ...bunEnv, NODE_PATH: join(String(dir), "libs") }) + .nothrow(); + expect(result.stderr.toString()).toBe(""); + expect(result.stdout.toString().trim()).toBe("from-node-path"); + expect(result.exitCode).toBe(0); + }); + test("compile with 8+ entry points runs main entry correctly", async () => { await using dir = tempDir("compile-many-entries", { "app.js": `console.log("IT WORKS");`, diff --git a/test/bundler/bundler_compile_autoload.test.ts b/test/bundler/bundler_compile_autoload.test.ts index 045f6919ef2e..0ecbfdc1c97a 100644 --- a/test/bundler/bundler_compile_autoload.test.ts +++ b/test/bundler/bundler_compile_autoload.test.ts @@ -307,7 +307,7 @@ console.log("PRELOAD"); }, }); - // Test CLI backend with autoloadPackageJson: true using package.json exports + // Test CLI backend with autoloadPackageJson: true using the project's package.json "imports" itBundled("compile/AutoloadPackageJsonExportsCLI", { compile: { autoloadPackageJson: true, @@ -315,24 +315,23 @@ console.log("PRELOAD"); backend: "cli", files: { "/entry.js": /* js */ ` - const pkgName = "cli-pkg"; - const subpath = "feature"; - import(pkgName + "/" + subpath) + const specifier = "#" + "feature"; + import(specifier) .then(m => console.log(m.default)) .catch(e => console.log("import-failed: " + e.message)); `, }, runtimeFiles: { - "/node_modules/cli-pkg/package.json": JSON.stringify({ - name: "cli-pkg", - exports: { - "./feature": "./features/main.js", + "/package.json": JSON.stringify({ + name: "cli-app", + imports: { + "#feature": "./features/main.js", }, }), - "/node_modules/cli-pkg/features/main.js": `export default "feature-from-cli-package-exports";`, + "/features/main.js": `export default "feature-from-cli-package-imports";`, }, run: { - stdout: "feature-from-cli-package-exports", + stdout: "feature-from-cli-package-imports", setCwd: true, }, }); @@ -455,40 +454,9 @@ console.log("PRELOAD"); }, }); - // Test that package.json exports are loaded at runtime when autoloadPackageJson: true - // Uses a dynamic import path that the bundler cannot resolve at compile time - itBundled("compile/AutoloadPackageJsonExportsEnabled", { - compile: { - autoloadPackageJson: true, - }, - files: { - "/entry.js": /* js */ ` - // Use a dynamic path that can't be resolved at compile time - const pkgName = "my-runtime-pkg"; - const subpath = "utils"; - import(pkgName + "/" + subpath) - .then(m => console.log(m.default)) - .catch(e => console.log("import-failed: " + e.message)); - `, - }, - runtimeFiles: { - "/node_modules/my-runtime-pkg/package.json": JSON.stringify({ - name: "my-runtime-pkg", - exports: { - "./utils": "./lib/utilities.js", - }, - }), - "/node_modules/my-runtime-pkg/lib/utilities.js": `export default "utilities-from-package-exports";`, - }, - run: { - stdout: "utilities-from-package-exports", - setCwd: true, - }, - }); - // Test that the project's own package.json is loaded when autoloadPackageJson: true. - // A self-reference through its "exports" resolves. - itBundled("compile/AutoloadPackageJsonSelfReferenceEnabled", { + // A self-reference through its "exports" and a "#imports" specifier both resolve. + itBundled("compile/AutoloadPackageJsonExportsEnabled", { compile: { autoloadPackageJson: true, }, @@ -496,8 +464,9 @@ console.log("PRELOAD"); "/entry.js": /* js */ ` const selfName = "my-app"; const subpath = "utils"; - import(selfName + "/" + subpath) - .then(m => console.log(m.default)) + const hash = "#" + "helper"; + Promise.all([import(selfName + "/" + subpath), import(hash)]) + .then(([utils, helper]) => console.log(utils.default + " " + helper.default)) .catch(e => console.log("import-failed: " + e.message)); `, }, @@ -507,18 +476,23 @@ console.log("PRELOAD"); exports: { "./utils": "./src/utils.js", }, + imports: { + "#helper": "./src/helper.js", + }, }), "/src/utils.js": `export default "utils-from-self-reference";`, + "/src/helper.js": `export default "helper-from-imports";`, }, run: { - stdout: "utils-from-self-reference", + stdout: "utils-from-self-reference helper-from-imports", setCwd: true, }, }); // Test that the project's own package.json is NOT loaded when autoloadPackageJson: false (default). - // A self-reference through its "exports" fails. A package inside node_modules is still resolved - // through its own package.json: that is the resolution algorithm, not a config file. + // A self-reference through its "exports" and a "#imports" specifier both fail. A package inside + // node_modules is still resolved through its own package.json: that is the resolution + // algorithm, not a config file. itBundled("compile/AutoloadPackageJsonExportsDisabled", { compile: { autoloadPackageJson: false, @@ -528,13 +502,17 @@ console.log("PRELOAD"); const selfName = "my-app"; const pkgName = "my-runtime-pkg"; const subpath = "utils"; + const hash = "#" + "helper"; const self = import(selfName + "/" + subpath) .then(m => m.default) .catch(() => "self-reference-failed-as-expected"); + const imports = import(hash) + .then(m => m.default) + .catch(() => "imports-failed-as-expected"); const dep = import(pkgName + "/" + subpath) .then(m => m.default) .catch(e => "import-failed: " + e.message); - Promise.all([self, dep]).then(lines => console.log(lines.join("\\n"))); + Promise.all([self, imports, dep]).then(lines => console.log(lines.join("\\n"))); `, }, runtimeFiles: { @@ -543,8 +521,12 @@ console.log("PRELOAD"); exports: { "./utils": "./src/utils.js", }, + imports: { + "#helper": "./src/helper.js", + }, }), "/src/utils.js": `export default "utils-from-self-reference";`, + "/src/helper.js": `export default "helper-from-imports";`, "/node_modules/my-runtime-pkg/package.json": JSON.stringify({ name: "my-runtime-pkg", exports: { @@ -554,7 +536,7 @@ console.log("PRELOAD"); "/node_modules/my-runtime-pkg/lib/utilities.js": `export default "utilities-from-package-exports";`, }, run: { - stdout: "self-reference-failed-as-expected\nutilities-from-package-exports", + stdout: "self-reference-failed-as-expected\nimports-failed-as-expected\nutilities-from-package-exports", setCwd: true, }, }); @@ -621,7 +603,7 @@ console.log("PRELOAD"); "/entry.ts": /* ts */ ` // Both imports require runtime config files const tsconfigPath = "@utils/" + "helper"; - const pkgPath = "runtime-pkg/" + "utils"; + const pkgPath = "#" + "utils"; Promise.all([import(tsconfigPath), import(pkgPath)]) .then(([helper, utils]) => console.log(helper.default + " " + utils.default)) .catch(e => console.log("import-failed: " + e.message)); @@ -637,13 +619,13 @@ console.log("PRELOAD"); }, }), "/src/utils/helper.ts": `export default "tsconfig-helper";`, - "/node_modules/runtime-pkg/package.json": JSON.stringify({ - name: "runtime-pkg", - exports: { - "./utils": "./lib/utils.js", + "/package.json": JSON.stringify({ + name: "both-app", + imports: { + "#utils": "./lib/utils.js", }, }), - "/node_modules/runtime-pkg/lib/utils.js": `export default "package-utils";`, + "/lib/utils.js": `export default "package-utils";`, }, run: { stdout: "tsconfig-helper package-utils", From 62a74a7f11f803946a3af9b18ac2be3624d2b495 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:41:18 +0000 Subject: [PATCH 06/10] resolver: shorten the is_project_config_dir 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 c2074d49adad..d20933536455 100644 --- a/src/resolver/resolver.rs +++ b/src/resolver/resolver.rs @@ -6700,8 +6700,7 @@ impl<'a> Resolver<'a> { Ok(None) } - /// `dir` is the cwd or one of its parents. Their `package.json` is the project's config, - /// which `load_package_json` gates. Any other `package.json` is a resolution target. + /// `dir` is the cwd or one of its parents, whose `package.json` is `load_package_json`'s. fn is_project_config_dir(&self, dir: &[u8]) -> bool { use ResolvePath::resolve_path::{ParentEqual, is_parent_or_equal}; is_parent_or_equal(dir, self.fs_ref().top_level_dir()) != ParentEqual::Unrelated From 8ba74271bea54d26da1b361a36d3eb85f642af5c Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:42:48 +0000 Subject: [PATCH 07/10] [autofix.ci] apply automated fixes --- docs/snippets/cli/build.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/snippets/cli/build.mdx b/docs/snippets/cli/build.mdx index e7eea6066224..e101b3272ccf 100644 --- a/docs/snippets/cli/build.mdx +++ b/docs/snippets/cli/build.mdx @@ -227,7 +227,8 @@ bun build - Read the project's own package.json at runtime in the standalone executable. A dependency's package.json is always read + Read the project's own package.json at runtime in the standalone executable. A dependency's{" "} + package.json is always read From 981f916e5cca4f435037525e60ef05ac0353685e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:55:51 +0000 Subject: [PATCH 08/10] test: run the symlinked package test on Windows with a junction, match sibling timeouts --- test/bundler/bundler_compile.test.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/bundler/bundler_compile.test.ts b/test/bundler/bundler_compile.test.ts index 6da7e31770c3..a4e84b97e556 100644 --- a/test/bundler/bundler_compile.test.ts +++ b/test/bundler/bundler_compile.test.ts @@ -1603,7 +1603,7 @@ const server = serve({ // When compiling with 8+ entry points, the main entry point should still run correctly. // A package that node_modules reaches by symlink (a workspace or `bun link`) has its own // package.json read at runtime: its main, its exports, and its #imports from the real path. - test.skipIf(isWindows)("compile resolves a symlinked node_modules package through its package.json", async () => { + test("compile resolves a symlinked node_modules package through its package.json", async () => { await using dir = tempDir("compile-linked-pkg", { "app.js": ` const req = (x) => require(x); @@ -1620,7 +1620,11 @@ const server = serve({ "packages/linked-pkg/lib/util.js": `module.exports = "util";`, "node_modules/.keep": "", }); - symlinkSync(join(String(dir), "packages", "linked-pkg"), join(String(dir), "node_modules", "linked-pkg")); + symlinkSync( + join(String(dir), "packages", "linked-pkg"), + join(String(dir), "node_modules", "linked-pkg"), + "junction", + ); await Bun.$`${bunExe()} build --compile app.js --outfile app`.cwd(dir).env(bunEnv).throws(true); @@ -1628,7 +1632,7 @@ const server = serve({ expect(result.stderr.toString()).toBe(""); expect(result.stdout.toString().trim()).toBe('["util-main","util-feature"]'); expect(result.exitCode).toBe(0); - }); + }, 30_000); // A directory on NODE_PATH is not the project's config, so its package.json is read. test("compile resolves a NODE_PATH package through its package.json main", async () => { @@ -1650,7 +1654,7 @@ const server = serve({ expect(result.stderr.toString()).toBe(""); expect(result.stdout.toString().trim()).toBe("from-node-path"); expect(result.exitCode).toBe(0); - }); + }, 30_000); test("compile with 8+ entry points runs main entry correctly", async () => { await using dir = tempDir("compile-many-entries", { From 48b94e887e4fce22a4971ed44254b84276265a09 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:41:30 +0000 Subject: [PATCH 09/10] ci: retrigger From d4cea08397f10b7d78da9ff1d5791613895b6d17 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:43:12 +0000 Subject: [PATCH 10/10] test: drop the per-test timeouts, the test runner sets its own --- test/bundler/bundler_compile.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/bundler/bundler_compile.test.ts b/test/bundler/bundler_compile.test.ts index a4e84b97e556..28d807f1d03e 100644 --- a/test/bundler/bundler_compile.test.ts +++ b/test/bundler/bundler_compile.test.ts @@ -1632,7 +1632,7 @@ const server = serve({ expect(result.stderr.toString()).toBe(""); expect(result.stdout.toString().trim()).toBe('["util-main","util-feature"]'); expect(result.exitCode).toBe(0); - }, 30_000); + }); // A directory on NODE_PATH is not the project's config, so its package.json is read. test("compile resolves a NODE_PATH package through its package.json main", async () => { @@ -1654,7 +1654,7 @@ const server = serve({ expect(result.stderr.toString()).toBe(""); expect(result.stdout.toString().trim()).toBe("from-node-path"); expect(result.exitCode).toBe(0); - }, 30_000); + }); test("compile with 8+ entry points runs main entry correctly", async () => { await using dir = tempDir("compile-many-entries", {