diff --git a/docs/bundler/executables.mdx b/docs/bundler/executables.mdx index a05760ff47be..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 +- **`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..e101b3272ccf 100644 --- a/docs/snippets/cli/build.mdx +++ b/docs/snippets/cli/build.mdx @@ -227,11 +227,12 @@ 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 5980b9ab38df..9670adf3237b 100644 --- a/src/resolver/options.rs +++ b/src/resolver/options.rs @@ -183,6 +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 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 a22e66c4e69d..d20933536455 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 { + 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,12 @@ impl<'a> Resolver<'a> { Ok(None) } + /// `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 + } + /// `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 ac147a1d9dbd..28d807f1d03e 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"; @@ -1008,6 +1008,62 @@ describe("bundler", () => { }, 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({ + 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/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: "[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, + }); itBundled("compile/DynamicImport", { files: { "/entry.tsx": /* tsx */ ` @@ -1545,6 +1601,61 @@ 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("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"), + "junction", + ); + + 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 6b4338c26985..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,54 +454,79 @@ 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 + // Test that the project's own package.json is loaded when autoloadPackageJson: true. + // A self-reference through its "exports" and a "#imports" specifier both resolve. 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 selfName = "my-app"; const subpath = "utils"; - import(pkgName + "/" + 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)); `, }, runtimeFiles: { - "/node_modules/my-runtime-pkg/package.json": JSON.stringify({ - name: "my-runtime-pkg", + "/package.json": JSON.stringify({ + name: "my-app", exports: { - "./utils": "./lib/utilities.js", + "./utils": "./src/utils.js", + }, + imports: { + "#helper": "./src/helper.js", }, }), - "/node_modules/my-runtime-pkg/lib/utilities.js": `export default "utilities-from-package-exports";`, + "/src/utils.js": `export default "utils-from-self-reference";`, + "/src/helper.js": `export default "helper-from-imports";`, }, run: { - stdout: "utilities-from-package-exports", + stdout: "utils-from-self-reference helper-from-imports", setCwd: true, }, }); - // 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" 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, }, 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 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, imports, dep]).then(lines => console.log(lines.join("\\n"))); `, }, runtimeFiles: { + "/package.json": JSON.stringify({ + name: "my-app", + 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: { @@ -512,7 +536,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\nimports-failed-as-expected\nutilities-from-package-exports", setCwd: true, }, }); @@ -579,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)); @@ -595,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",