Skip to content

Use the virtual $bunfs path for __dirname/__filename in --compile executables - #29066

Closed
robobun wants to merge 8 commits into
mainfrom
farm/55418012/compile-dirname-filename-bunfs
Closed

robobun wants to merge 8 commits into
mainfrom
farm/55418012/compile-dirname-filename-bunfs

Conversation

@robobun

@robobun robobun commented Apr 9, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #44068

Problem

  • In a bun build --compile executable, __dirname and __filename are string literals holding the build machine's source paths (var __dirname = "/home/user/project/src"), while import.meta.dir / import.meta.path in the same binary resolve to the executable's virtual /$bunfs/root directory at runtime.
  • Cause: the bundler's post-visit step in src/js_parser/parse/parse_entry.rs (PartTag::DirnameFilename) always injects the source file's directory and path as literals, with nothing telling it that the output is a standalone executable.
  • Effects: the build machine's paths end up inside every shipped binary, and the CommonJS idiom for locating files shipped next to the code (path.join(__dirname, ...), require(path.join(__dirname, "addon.node"))) only works on the machine that ran the build. Files embedded with --asset (compile: --asset flag + /$bunfs/ directory semantics for node:fs #36302) live under /$bunfs/root/, so they are unreachable through __dirname even though they are reachable through import.meta.dir.

Fix

  • ParseTask sets a new parser option compile when compile_mode.is_executable() and the chunk targets Bun. Browser chunks of HTML imports inherit compile_mode but not the target, so they keep the string literals (import.meta.dir does not exist in a browser).
  • ESM output: the injected declarations become var __dirname = import.meta.dir, __filename = import.meta.path. Nothing else is needed for --bytecode: the printer flags a chunk as containing import.meta when it prints the synthesized node, and that flag is what the bytecode module record is created from (an earlier revision also set the parser's has_import_meta, which is only read by the runtime CommonJS wrapper and never in a bundle, so that was dropped).
  • CJS output (--format=cjs, or --bytecode, which implies it): no declaration is injected, so references bind to the __filename / __dirname parameters of the CommonJS wrapper, which the runtime fills with the virtual path. import.meta.dir / .dirname / .path / .filename are rewritten to those same identifiers in this mode (src/js_parser/fold.rs) so the two spellings stay equal. (.filename is not inlined at all for plain CJS bundles today and survives as a syntax error inside the wrapper; that non-compile case is tracked separately, this PR only covers it for compiled output.)
  • Not covered: import.meta.url (and .file) in --format=cjs compiled output still inline their build-time values. The wrapper only provides __filename, and turning that into a file: URL needs pathToFileURL (percent-encoding; on Windows the key is B:/~BUN/...), so the parser has no runtime expression to lower it to without emitting a call into a builtin. The default ESM output leaves import.meta.url untouched and it resolves to file:///$bunfs/root/<name> at runtime.
  • Windows: the wrapper derived __dirname by splitting the module key on a backslash only, but standalone keys are forward-slashed (B:/~BUN/root/app.exe), so once the declaration stopped shadowing the parameter, CJS output got __dirname === "" there (reproduced on Windows x64 without this hunk). JSCommonJSModule.cpp now splits on either separator via lastPathSeparatorIndex in PathInlines.h. This hunk is taken from bundler: resolve __dirname/__filename at runtime for --target=bun/node #35470.
  • Why this is the right value: a compiled executable is relocated by definition, and /$bunfs/root is the directory its embedded files (entry, chunks, file-loader assets, --asset files) are addressed by, so it is the only value of __dirname that can locate anything at runtime. It is also what import.meta.dir already reports in the same binary.
  • Native addons (question raised in review): the documented require("./addon.node") form is unaffected, since the bundler turns it into an embedded asset reference without involving __dirname. The require(path.join(__dirname, "addon.node")) form was never embedded and only resolved on the build machine; with this change plus --asset addon.node it loads on any machine (process.dlopen looks the /$bunfs/root/addon.node path up in the embedded graph and extracts it). Checked with a small N-API addon, transcript in the details block below.
  • Non-compile bundles (--target=bun / --target=node without --compile) are intentionally unchanged: inlining the source paths there is the existing behavior that fix: __dirname and __filename collisions #17222 and Bundling with --target=bun changes __dirname references to hardcoded values #4216 discuss, and it is a separate decision. This PR does not resolve __dirname handled incorrectly when building #17188 or Bundling with --target=bun changes __dirname references to hardcoded values #4216; it covers the --compile case only. bundler: resolve __dirname/__filename at runtime for --target=bun/node #35470, which changed all Bun/Node-target bundles, is closed in favor of this PR.

Verification:

  • test/bundler/bundler_compile.test.ts: compile/DirnameFilenameUsesVirtualPath{,Bytecode,CJS} and compile/DirnameFilenameCJSEntryWithoutRequire (an entry with no require / module / exports / import, which the parser classifies as ESM while the linker still wraps the chunk) (ESM output with and without --bytecode, --format=cjs output including the import.meta.dir / .path / .dirname / .filename rewrites, all also checking a nested module and __dirname === import.meta.dir) and compile/DirnameFilenameInBrowserChunk. All 5 fail on the unfixed build, pass with the fix.
  • test/bundler/compile-asset-bunfs.test.ts: --asset files are reachable through __dirname after the build tree is gone, run for ESM output and for --bytecode (implied CJS, wrapper-provided __dirname): reads an --asset file through path.join(__dirname, ...) after deleting the source tree and pins the exact __dirname value per mode (B:\~BUN\root vs B:/~BUN/root on Windows). Both fail unfixed with ENOENT on the build path and pass with the fix. This is a plain test() file, so unlike the itBundled cases it runs on the Windows CI lane, and the --bytecode case is the one that exercises the separator fix there (it reads through the wrapper's __dirname, which is "" without the PathInlines.h hunk).
  • test/bundler/cli.test.ts: the existing __dirname and __filename are printed correctly test now expects the virtual path for the compiled half and keeps its UTF-8 path coverage through a plain bun build.
  • Full bundler_compile.test.ts, bundler_compile_splitting.test.ts, cli.test.ts, compile-asset-bunfs.test.ts, bun-build-api.test.ts pass with a debug build on Linux (the only failure, compile/HelloWorldWithProcessVersionsBun, compares against the -debug version string and fails on every debug build).
  • The same tests pass on Windows x64 with a debug build of this branch. itBundled tests currently do not execute on Windows at all (the harness's test/bundler/ stack check fails on backslash paths, tracked separately), so the Windows expectations in the compile/DirnameFilename* cases were run by temporarily patching that check locally; the CJS cases print an empty __dirname there without the PathInlines.h hunk, which is why the --bytecode variant was put in compile-asset-bunfs.test.ts instead of adding a fourth itBundled binary. Total: six compiled binaries across the three files, each covering a distinct output mode or guard.

Background

  • /$bunfs/root (B:\~BUN\root on Windows) is the virtual directory a compiled executable's embedded files are mounted under: the entry chunk is /$bunfs/root/<outfile name>, and --asset files and file-loader assets sit next to it. import.meta.dir / import.meta.path report these paths, and node:fs resolves them against the embedded graph.
  • For CJS-format output the runtime does not evaluate the chunk as a module; it wraps it in (function(exports, require, module, __filename, __dirname) { ... }) and fills the last two parameters from the module's require-cache key (JSCommonJSModule.cpp). import.meta is a syntax error inside that wrapper, which is why CJS output defers to the parameters instead of emitting import.meta.dir. For standalone executables that key is forward-slashed on every platform, so on Windows the CJS spelling is B:/~BUN/root while the ESM spelling is B:\~BUN\root; the tests pin both.
  • compile_mode (CompileMode::Executable vs StandaloneHtml) is how the bundler records what --compile resolved to; only executables have a /$bunfs/ filesystem, so the option keys off is_executable().
N-API addon through __dirname plus --asset

entry.js:

const path = require("path");
const addon = require(path.join(__dirname, "addon.node"));
console.log("__dirname:", __dirname);
console.log(addon.hello());

Built on Linux x64 with bun build --compile --asset ./addon.node ./entry.js --outfile app, then the binary copied to another directory and the source directory's addon.node moved away (simulating a different machine):

# unfixed
error: Cannot find module '/tmp/triage/addon/addon.node' from '/$bunfs/root/app-main'

# this branch
__dirname: /$bunfs/root
hello from embedded addon

The same pattern with a data file instead of an addon is what the new compile-asset-bunfs.test.ts case checks.

Previous description

Earlier revisions of this PR described the change as a compile flag threaded from BundleOptions.compile; main has since replaced that field with compile_mode, and this branch was updated to match. The Windows separator fix and the ESM-with-bytecode, CJS-without-bytecode and --asset test cases were added while consolidating #35470 into this PR. The cli.test.ts adjustment and the browser-chunk guard (target.is_bun()) are unchanged from the earlier revisions.

Refs #17188, #4216 (non-compile bundles; not changed here).


no test proof · iteration 15 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/bundler/compile-asset-bunfs.test.ts, test/bundler/cli.test.ts, test/bundler/bundler_compile.test.ts

@github-actions github-actions Bot added the claude label Apr 9, 2026
@robobun

robobun commented Apr 9, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:21 PM PT - Aug 27th, 2026

❌ @robobun, your commit c7bc99a has 2 failures in Build #106972 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 29066

That installs a local version of the PR into your bun-29066 executable, so you can run:

bun-29066 --bun

@robobun

robobun commented Apr 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Head c7bc99a0d4 (rebased onto current main). The fix lives in the Rust parser (src/js_parser/parse/parse_entry.rs, src/js_parser/fold.rs, src/bundler/ParseTask.rs, src/bundler/transpiler.rs) plus the CJS wrapper __dirname derivation in src/jsc/bindings/{JSCommonJSModule.cpp,PathInlines.h}.

Verified on the current head with a debug build:

  • bun bd test test/bundler/bundler_compile.test.ts -t DirnameFilename → 5 pass; all fail with USE_SYSTEM_BUN=1
  • bun bd test test/bundler/cli.test.ts -t "__dirname and __filename" → pass (this test previously asserted the leaky behavior; its UTF-8 coverage is kept via a plain bun build run)
  • bun bd test test/bundler/compile-asset-bunfs.test.ts → 11 pass (includes the --bytecode CJS wrapper case that exercises lastPathSeparatorIndex)
  • cargo fmt --check / prettier → clean

Latest review round (c7bc99a): added compile/DirnameFilenameCJSEntryWithoutRequire (a --format=cjs entry that uses only the path globals, so the parser classifies it as ESM while the linker still applies the chunk wrapper), asserted stderr and exit codes of the spawned binaries in cli.test.ts and of the build step in the browser-chunk test. All review threads resolved.

**Re: require(__dirname + \/${process.platform}-${process.arch}.node`)** — that pattern was never statically resolved (the __dirnameliteral is injected post-visit, afterrequire()args are evaluated), so the addon is not embedded onmaineither; details in [this comment](https://github.com/oven-sh/bun/pull/29066#issuecomment-4210800374). The relativerequire(`./${platform}-${arch}.node`)form used bytest/napi/napi-app` is unaffected.

CI #106972 (head c7bc99a0d4): every bundler/compile test passes on all lanes. The two non-flaky failures are on the x64 ASAN lane and are independent of this diff: test/bundler/transpiler/macro-test.test.ts (tagged pre-existing on main; LeakSanitizer reports a node_fs_binding::Binding leak in a plain bun build that loads node:fs from a macro) and test/cli/run/require-cache.test.ts (reproduced locally with an ASAN debug build of main's src/). Both are reported for main-break triage, as is test/js/web/url/url.test.ts on darwin x64 (also tagged pre-existing: an ICU/IDNA table mismatch in new URL("http://foo\u180E:80/")). Everything else was [flaky]-tagged and passed alone or on retry.

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens when you do require(__dirname + ${process.platform}-${process.arch}.node)`? Will it no longer be able to resolve embedded .node addons?

@github-actions

github-actions Bot commented Apr 9, 2026

Copy link
Copy Markdown
Contributor

Found 3 issues this PR may fix:

  1. __dirname handled incorrectly when building #17188 - __dirname inlined as build machine path in bundled output; PR fixes this for --compile mode
  2. Bundling with --target=bun changes __dirname references to hardcoded values #4216 - __dirname hardcoded when bundling with --target=bun; same root cause, PR fixes the --compile variant
  3. Bun doesn't correctly build import.meta.path #15994 - import.meta.path resolves to wrong module's path in bundles; PR relies on and is adjacent to the same runtime resolution mechanism

If this is helpful, consider adding Fixes #<number> to the PR description to auto-close the issue on merge.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0d936667-419d-48f2-a3c7-6cb3fa576e33

📥 Commits

Reviewing files that changed from the base of the PR and between 8477a09 and c7bc99a.

📒 Files selected for processing (2)
  • test/bundler/bundler_compile.test.ts
  • test/bundler/cli.test.ts

Included review availability: Your plan provides up to 5 included reviews per hour; 4 remain after this review.


Walkthrough

Changes

The bundler now distinguishes compiled executable parsing from transpilation and browser chunks. Compiled CommonJS path globals use virtual standalone paths. Runtime path extraction handles Windows and non-Windows separators. Tests cover ESM, CommonJS, bytecode, browser chunks, and embedded assets.

Changes

Compiled path resolution

Layer / File(s) Summary
Compile-mode path lowering
src/js_parser/parse/parse_entry.rs, src/js_parser/fold.rs, src/bundler/ParseTask.rs, src/bundler/transpiler.rs
Compiled executable parsing uses Options::compile. Compiled CommonJS globals resolve through import.meta.dir and import.meta.path. Other output retains literal source paths.
Cross-platform runtime path extraction
src/jsc/bindings/PathInlines.h, src/jsc/bindings/JSCommonJSModule.cpp
CommonJS module and bound-require paths use the final platform-appropriate separator.
Bundler compile path tests
test/bundler/bundler_compile.test.ts
Tests cover virtual paths in ESM, CommonJS, ESM bytecode, nested modules, entries without CommonJS globals, and browser chunks.
CLI and embedded asset validation
test/bundler/cli.test.ts, test/bundler/compile-asset-bunfs.test.ts
CLI tests distinguish source and virtual paths. Embedded asset tests verify execution after removing the source directory.

Possibly related PRs

  • oven-sh/bun#35470: Extends runtime __dirname and __filename handling across compiled output and related parser and CLI paths.

Suggested reviewers: jarred-sumner, dylan-conway

Merge Risk: ⚪ Minimal · up to c7bc9

The change makes compiled executables resolve __dirname and __filename to their virtual runtime paths, including CJS and bytecode modes, with platform-specific coverage; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: compiled executables now use the virtual $bunfs path for __dirname and __filename.
Description check ✅ Passed The description is complete and relevant. It explains the problem, cause, implementation, scope, platform behavior, test coverage, verification results, and related issues.

Comment @coderabbitai help to get the list of available commands.

Comment thread src/ast/maybe.zig Resolved
@robobun

robobun commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator Author

What happens when you do require(__dirname + ${process.platform}-${process.arch}.node)`? Will it no longer be able to resolve embedded .node addons?

Tested this. That pattern has never caused the .node file to be embedded — __dirname is still a plain identifier during visiting (when require() args are resolved to import records); the var __dirname = "..." decl is injected post-visit, so the arg never folds to a string literal and the bundler treats it as a dynamic __require() call.

$ bun build --compile ./entry.ts --outfile ./app   # entry uses require(__dirname + `/${process.platform}-${process.arch}.node`)
  bundle  1 modules   ← addon not embedded, same on main and on this branch

Behavior on a shipped binary (source tree not present) is unchanged — MODULE_NOT_FOUND in both cases:

main this PR
.node embedded at bundle time no no
runtime __dirname <build-machine-dir> /$bunfs/root
require(__dirname + …) with source tree still on disk finds it on disk (accidentally) MODULE_NOT_FOUND
require(__dirname + …) after shipping MODULE_NOT_FOUND MODULE_NOT_FOUND

So the only case that changes is "compiled binary run on the build machine with the source tree still present" — where previously the leaked build path happened to point at a real file on disk. That never worked for a distributed binary.

The relative form — which is what test/napi/napi-app/module.js uses and what the napi.test.ts --compile test exercises — is unaffected:

require(`./${process.platform}-${process.arch}.node`)   // → "2 modules", embedded, works

Happy to gate this on a flag or revert if the "finds it on the build machine" behavior is something people depend on — but it seems strictly a leak rather than a feature, and it's consistent with #17188 / #4216.

@JustFly1984

Copy link
Copy Markdown

I've appied the patch from this PR to my local bun fork, and it compiled binary and run without 137 error! Thank you @robobun

kamilcast added a commit to getkimchi/kimchi that referenced this pull request May 21, 2026
Address review feedback:
- Narrow bare catch to only handle MODULE_NOT_FOUND, re-throw
  unexpected errors (corrupt installs, permission errors)
- Replace TODO placeholder with actual upstream link:
  oven-sh/bun#29066
kamilcast added a commit to getkimchi/kimchi that referenced this pull request May 21, 2026
## Fix Playwright detection failing in prebuilt release binaries

### Problem

When installing kimchi from prebuilt release artifacts (`curl -fsSL
.../install.sh | bash`), Playwright is never detected — users always see
the fallback warning:

> Playwright is not installed. Fetching with native HTTP client —
JavaScript-rendered content (SPAs) will not be captured. Run `npx
playwright install chromium` to enable full SPA support.

Installing locally via `pnpm run build:binary && pnpm run install:local`
works fine.

### Root Cause

When Bun compiles the binary with `bun build --compile`, it converts
relative `require.resolve()` calls inside bundled dependencies into
**absolute paths from the build machine**.

In `playwright-core/lib/server/utils/nodePlatform.js`, the line:

```js
const coreDir = path.dirname(require.resolve("../../../package.json"));
```

gets compiled to:

```js
var coreDir = path.dirname(require.resolve("/Users/runner/work/kimchi/kimchi/node_modules/.pnpm/playwright-core@1.59.1/..."));
```

This `require.resolve()` runs at **module initialization time**
(top-level `const`). On any machine other than the build machine, this
path doesn't exist, so `require.resolve` throws, the entire
playwright-core module fails to initialize, and the error propagates up
through `loadPlaywright()` → `playwrightAvailable = false` → fallback
warning.

**Local build works** because the hardcoded path points to the
developer's own `node_modules` which still exist on the same machine.
**Release build fails** because the path points to the CI runner's
filesystem (`/Users/runner/work/kimchi/kimchi/...`).

### Fix

Added a pnpm patch for `playwright-core@1.59.1` that wraps the `coreDir`
initialization in a try-catch. `coreDir` is only used for stack-trace
filtering (hiding playwright internals from error traces), so an empty
string fallback is functionally safe.

### Patch removal criteria

This patch can be removed when either:
- **Bun fixes `require.resolve` in compiled binaries** — Bun PR
[#29066](oven-sh/bun#29066) fixed
`__dirname`/`__filename` but `require.resolve()` with relative paths
still gets hardcoded.
- **Playwright upstream wraps this in a try-catch** themselves.

---
### Kimchi Summary
### What changed
Patches `playwright-core` to prevent runtime `MODULE_NOT_FOUND` errors
in Bun compiled binaries by falling back to `__dirname`-based path
resolution when `require.resolve()` fails.

### Why
Bun compiles relative `require.resolve()` calls into absolute
build-machine paths that are invalid at runtime. This causes
`playwright-core` to crash when locating its package root inside a
compiled binary.

### Key changes
- `patches/playwright-core@1.59.1.patch`: Wraps
`require.resolve("../../../package.json")` in
`lib/server/utils/nodePlatform.js` with a try-catch block and falls back
to `path.resolve(__dirname, "../../..")` on `MODULE_NOT_FOUND`.
- `package.json`: Registered `playwright-core@1.59.1` under
`patchedDependencies`.
- `pnpm-lock.yaml`: Updated `playwright-core` snapshots to apply the new
patch hash.

### Impact
- Enables `playwright-core` to function correctly when bundled in Bun
compiled binaries.
- Existing non-compiled environments are unaffected because the fallback
only triggers on missing modules.
@robobun
robobun force-pushed the farm/55418012/compile-dirname-filename-bunfs branch from 139d46f to 30b1917 Compare May 23, 2026 11:06
Comment thread src/js_parser/parse/parse_entry.rs Resolved
Comment thread src/js_parser/parse/parse_entry.rs Resolved
Jarred-Sumner pushed a commit that referenced this pull request Jul 20, 2026
## Repro

```
$ bun bd test test/bundler/bundler_compile.test.ts -t HelloWorldBytecode
...
- [Disk Cache] Cache miss for sourceCode"
+ [Disk Cache] Cache miss for sourceCode
+ debug warn: hintSourcePagesDontNeed: MADV_DONTNEED 4096 bytes"
```

Every standalone executable produced by a debug build prints that line
on startup, so every exact-`stderr` assertion in
`bundler_compile.test.ts` (`HelloWorldBytecode`, the three
`ReactSSR+bytecode` variants) fails under `bun bd`. CI doesn't see it
because the test lanes run a release build. Several open PRs (#33337,
#33316, #29066) have had to call it out as pre-existing debug noise in
their verification sections, and `bun-build-compile.test.ts` grew a
workaround comment that discards stderr.

## Cause

`hint_source_pages_dont_need()` logs the `madvise(MADV_DONTNEED)`
outcome with `debug_warn!`, which writes to stderr unconditionally in
debug builds and is not silenced by `BUN_DEBUG_QUIET_LOGS`. The success
path is purely informational, and the failure path is documented as a
best-effort hint, so neither is a warning.

## Fix

Declare a hidden `StandaloneModuleGraph` scope and route both log sites
through `scoped_log!`. The information is still available via
`BUN_DEBUG_StandaloneModuleGraph=1`; by default a compiled binary's
stderr is clean again. Release builds are unaffected either way since
both macros compile out.

Test changes:

- `compile/HelloWorld` now asserts `stderr: ""` so the regression is
covered directly rather than only as a side effect of the bytecode cache
tests.
- `standalone-madvise-tla.test.ts` was asserting the hint on stderr via
the old `debug_warn!` path; it now opts in with
`BUN_DEBUG_StandaloneModuleGraph=1` and reads the scoped log from stdout
(scoped loggers write to the debug stream, which is stdout by default).
A second run without the env var asserts the scope stays hidden even
with `BUN_DEBUG_QUIET_LOGS` unset.
- The workaround comment and discarded stderr in the `#29963`
PT_GNU_STACK test in `bun-build-compile.test.ts` are replaced with
`expect(stderr).toBe("")`.

## Verification

```
$ bun bd test test/bundler/bundler_compile.test.ts -t "compile/HelloWorld$|HelloWorldBytecode|ImportDeferBytecode|ReactSSR\+bytecode"
 7 pass, 0 fail
$ bun bd test test/js/bun/compile/standalone-madvise-tla.test.ts
 1 pass, 0 fail
$ bun bd test test/bundler/bun-build-compile.test.ts -t "preserves PT_GNU_STACK"
 1 pass, 0 fail

# opt-in still works
$ BUN_DEBUG_StandaloneModuleGraph=1 ./compiled-out
hi
[standalonemodulegraph] hintSourcePagesDontNeed: MADV_DONTNEED 4096 bytes
```

`cargo check -p bun_standalone_graph` and `--target
x86_64-pc-windows-msvc` both clean; `cargo clippy -p
bun_standalone_graph --no-deps` clean.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/bundler/bun-build-compile.test.ts
test/bundler/bundler_compile.test.ts
test/js/bun/compile/standalone-madvise-tla.test.ts

<!-- robobun:evidence:end -->

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
@robobun
robobun force-pushed the farm/55418012/compile-dirname-filename-bunfs branch from 30b1917 to 879c66d Compare July 22, 2026 12:45
@robobun
robobun requested a review from Jarred-Sumner July 22, 2026 12:45

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both prior findings (browser-target chunks emitting import.meta.dir, and has_import_meta not set for the synthetic nodes) are addressed in 879c66d with regression tests. I didn't find further issues, but this is a user-facing semantics change to --compile output — including the acknowledged require(__dirname + …) behavior shift on the build machine and the CJS-mode import.meta.url/.file gap left as-is — so it's worth a maintainer sign-off rather than a bot approval.

Checked: the target.is_bun() gate in ParseTask.rs correctly excludes the HTML-import client transpiler; the CJS path's record_usage(p.dirname_ref) in fold.rs pairs with the suppressed var __dirname decl so references fall through to the wrapper param; p.has_import_meta = true is set on both synthetic E::ImportMeta sites; the rewritten cli.test.ts case preserves the original UTF-8-path coverage via a non---compile build.

Extended reasoning...

Overview

Adds a compile: bool parser option propagated from BundleOptions.compile (gated on target.is_bun()) and uses it in two places: (1) parse_entry.rs — for --compile ESM, emit var __dirname = import.meta.dir / var __filename = import.meta.path instead of build-path string literals; for --compile --format=cjs, suppress the decl entirely so refs fall through to the CJS wrapper's runtime-populated params. (2) fold.rs — for --compile --format=cjs, rewrite import.meta.dir/.dirname/.path to the __dirname/__filename identifiers instead of inlining build paths. Four new itBundled/test cases cover ESM, CJS, --bytecode, and the HTML-import browser-chunk exclusion; cli.test.ts is updated to split its UTF-8-path assertion into a plain-build half (unchanged expectation) and a --compile half (virtual path).

Security risks

None. The change stops leaking build-machine absolute paths into shipped standalone binaries, which is a mild information-disclosure improvement. No auth/crypto/untrusted-input parsing is touched.

Level of scrutiny

Medium-high. This is a deliberate change to the runtime semantics of __dirname/__filename in every --compile binary — not a mechanical fix. It touches the JS parser's post-visit lowering and the bundler's per-source option propagation, and it rewrites an existing test's expected output. The PR itself documents two intentional gaps (CJS-mode import.meta.url/.file still inline build-time values) and one behavior loss (a compiled binary run on the build machine with sources still on disk no longer accidentally resolves require(__dirname + …)). Those are reasonable tradeoffs, but they're the kind of API/behavior call a maintainer should ratify.

Other factors

All three of my earlier inline findings are resolved: the import.meta.file CJS case was argued as out-of-scope (basename only, no path leak); the browser-target regression is fixed via the target.is_bun() gate with a dedicated test; the missing has_import_meta flag is now set alongside both synthetic E::ImportMeta nodes with a --bytecode test. Test coverage across ESM/CJS/bytecode/browser-chunk is solid, and the non---compile path is untouched (compile defaults to false everywhere). Deferring for human confirmation of the semantics change rather than for any open correctness concern.

@robobun

robobun commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator Author

Heads up: #35470 covers this same lowering but keyed off the bundle target rather than a compile flag, so it applies to plain --target=bun and --target=node bundles as well as --compile (which implies target=bun), and fixes #4216 in addition to #17188. If #35470 merges, this PR can be closed as superseded.

Comment thread src/bundler/ParseTask.rs Resolved
Comment thread src/js_parser/fold.rs Resolved
Comment thread src/js_parser/parse/parse_entry.rs Resolved
Comment thread src/js_parser/parse/parse_entry.rs Resolved
Comment thread src/js_parser/fold.rs Resolved
@robobun robobun changed the title Use virtual $bunfs path for __dirname/__filename in --compile Use the virtual $bunfs path for __dirname/__filename in --compile executables Aug 13, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this PR and didn't find any bugs. Because it changes the user-visible runtime value of __dirname/__filename in compiled binaries and threads that decision through the parser, bundler, and CJS wrapper C++ (including a Windows-wide path-separator change in JSCommonJSModule.cpp), a human sign-off on the behavior and scope is still worthwhile. There are also five open comment-cop notes on the new inline comments.

What was reviewed:

  • The opts.compile propagation in ParseTask.rs — gated on compile_mode.is_executable() && target.is_bun(), so browser chunks of HTML imports keep the string-literal lowering (covered by compile/DirnameFilenameInBrowserChunk).
  • The synthetic E::ImportMeta decls in parse_entry.rs set p.has_import_meta = true, so --bytecode module records get ImportMetaFeature; the CJS branch suppresses the decl and the fold.rs rewrite routes import.meta.dir/.dirname/.path/.filename to the wrapper params instead.
  • lastPathSeparatorIndex in PathInlines.h — on POSIX it is byte-identical to the old reverseFind(PLATFORM_SEP); on Windows it now also matches /, which affects every CJS module's __dirname derivation, not only standalone executables.
  • The cli.test.ts update — the original UTF-8-path assertion is preserved via a plain bun build half, and the --compile half now pins the virtual path.
Extended reasoning...

Overview

The PR adds a compile parser option so that, when bundling for bun build --compile, __dirname/__filename are lowered to import.meta.dir/import.meta.path (ESM) or fall through to the CJS wrapper parameters (CJS output) instead of being inlined as the build machine's absolute paths. It touches src/bundler/ParseTask.rs and transpiler.rs (option plumbing), src/js_parser/parse/parse_entry.rs (the injected decl), src/js_parser/fold.rs (rewriting import.meta.{dir,dirname,path,filename} to the wrapper identifiers for compiled CJS), and src/jsc/bindings/{JSCommonJSModule.cpp,PathInlines.h} (splitting the CJS wrapper key on either separator so Windows standalone keys like B:/~BUN/root/app.exe yield a non-empty __dirname). Five new/updated tests cover ESM, CJS, ±bytecode, browser-chunk, and --asset reachability.

Security risks

None identified. No untrusted input parsing, no auth/crypto/permission surfaces. The change alters what string a compiled binary reports for its own location; if anything it reduces information leakage (the build machine's absolute path is no longer embedded).

Level of scrutiny

High. This is a deliberate user-visible behavior change to a documented value (__dirname in --compile output), not a pure bugfix — the earlier maintainer question in the thread about require(__dirname + …) and native addons shows the semantics needed maintainer judgment. The C++ hunk in JSCommonJSModule.cpp changes how __dirname is derived for every CJS module on Windows (not just standalone ones), which is a broader blast radius than the PR title suggests. The cli.test.ts change rewrites an existing test's expectations, which per the review guide warrants a human check that the original coverage (UTF-8 path encoding, issue #10474) is preserved — it is, via the added non---compile half.

Other factors

  • Prior automated review rounds surfaced three issues (browser-target leakage, missing has_import_meta, import.meta.file handling); all are resolved and the fixes are visible in the current diff with matching tests.
  • Five comment-cop inline comments dated today flag the multi-line explanatory comments in ParseTask.rs, fold.rs, and parse_entry.rs as too long; those are unaddressed.
  • The PR supersedes #35470 and intentionally scopes to --compile only, leaving #17188/#4216 (plain --target=bun/node bundles) unchanged — a scope decision a maintainer should confirm.
  • Test coverage is thorough (ESM/CJS × ±bytecode, browser-chunk guard, --asset reachability with the source tree deleted), and the description documents Windows verification by hand since itBundled doesn't execute there.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review ran clean on 056d65d — no bugs found. This is a user-visible behavior change to __dirname/__filename in --compile output that touches the parser, bundler option plumbing, and the C++ CJS module runtime, so a human sign-off is still worthwhile.

What was reviewed:

  • Verified the p.has_import_meta = true removal in 7030029 is safe: per-part-range printing now carries its own ModuleInfo (generateCompileResultForJSChunk.rs:132–155) and postProcessJSChunk.rs:207 merges contains_import_meta into the chunk record, so the synthesized import.meta.dir reaches JSModuleRecord__create for --bytecode without the parser flag.
  • lastPathSeparatorIndex on POSIX is byte-identical to the old reverseFind(PLATFORM_SEP); the Windows branch only widens what counts as a separator, so non-compile CJS __dirname on Windows is unchanged for backslash paths and now non-empty for forward-slashed keys.
  • The target.is_bun() gate in ParseTask.rs keeps browser-side HTML-import chunks on the string-literal lowering; the fold.rs rewrite is nested under the existing bundle && output_format == Cjs guard so it cannot fire for ESM or non-bundle parsing.
Extended reasoning...

Overview

The PR threads a new compile: bool parser option from ParseTask (set when compile_mode.is_executable() && target.is_bun()) into parse_entry.rs and fold.rs. For ESM --compile output it emits var __dirname = import.meta.dir / var __filename = import.meta.path instead of build-machine string literals; for CJS output it suppresses the injected declaration entirely so the identifiers bind to the wrapper's parameters, and rewrites import.meta.{dir,dirname,path,filename} to those same identifiers. It also adds lastPathSeparatorIndex in PathInlines.h and swaps four reverseFind(PLATFORM_SEP) sites in JSCommonJSModule.cpp to it, so forward-slashed standalone-graph keys on Windows produce a non-empty __dirname. Tests cover ESM, ESM+bytecode, CJS, browser-chunk guard, and --asset reachability after deleting the source tree.

Security risks

None identified. No untrusted-input parsing, auth, or crypto. The path-separator helper only broadens which byte counts as a separator on Windows; POSIX behavior is byte-identical to before.

Level of scrutiny

High. This is a deliberate, user-observable semantic change to __dirname/__filename in every bun build --compile binary — the PR description itself documents one case ("compiled binary run on the build machine with the source tree still present") that goes from working to MODULE_NOT_FOUND. It also touches four call sites in the C++ CJS module loader that run for every CommonJS module on Windows, not only compiled ones. That scope, plus cross-platform pinned expectations (B:\\~BUN\\root vs B:/~BUN/root), warrants a maintainer decision rather than an automated approval.

Other factors

  • All three of my earlier inline findings (browser-chunk import.meta.dir leak, missing has_import_meta for bytecode, import.meta.file in compiled CJS) have been addressed or explicitly scoped out, and the comment-cop nags were resolved in 056d65d.
  • I re-checked the has_import_meta reversal against current main: the per-part printer now has a ModuleInfo and postProcessJSChunk merges it, so the earlier concern no longer applies and the removal is correct.
  • Test coverage is thorough (six compiled-binary variants plus the modified cli.test.ts case), and compile-asset-bunfs.test.ts specifically runs the CJS-wrapper case on the Windows lane where the separator fix matters. CI on the latest push is still building.
  • #35470 was closed in favor of this PR; a maintainer should confirm the narrower --compile-only scope is the intended landing shape.

@robobun

robobun commented Aug 20, 2026

Copy link
Copy Markdown
Collaborator Author

Heads-up from #39715: that PR prints every import.meta in bun-target cjs output as the wrapper's real import.meta argument, which covers .url and .file as well. Once it lands, the fold.rs rewrite of import.meta.dir/.dirname/.path/.filename to __dirname/__filename for --compile cjs output here is no longer needed. The __dirname/__filename declaration change and the Windows separator fix are unaffected by it.

@robobun
robobun force-pushed the farm/55418012/compile-dirname-filename-bunfs branch from 056d65d to 202f30e Compare August 23, 2026 00:10

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this revision and didn't find any bugs. Since this is a deliberate user-visible behavior change to what __dirname/__filename return in --compile output (and updates an existing test's expectations to match), a maintainer sign-off on the semantics would still be worthwhile.

Checked: the target.is_bun() gate keeps browser HTML-import chunks on the string-literal lowering; the CJS-format branch suppresses the decl so references bind to the wrapper's parameters and fold.rs rewrites import.meta.{dir,dirname,path,filename} to those same identifiers; lastPathSeparatorIndex is a pure refactor on POSIX and only widens the Windows split to accept forward slashes; the --bytecode ESM path gets contains_import_meta from the printer so the dropped has_import_meta stores are indeed write-only here.

Extended reasoning...

Overview

Threads a new compile parser option from ParseTask (gated on compile_mode.is_executable() && target.is_bun()) into parse_entry.rs, where the post-visit __dirname/__filename injection now emits var __dirname = import.meta.dir / var __filename = import.meta.path for ESM output and suppresses the declaration entirely for CJS output (so references bind to the wrapper's parameters). fold.rs rewrites import.meta.{dir,dirname,path,filename} to the __dirname/__filename identifiers in compiled CJS so both spellings agree. JSCommonJSModule.cpp / PathInlines.h add lastPathSeparatorIndex so the wrapper's __dirname derivation handles the forward-slashed standalone-graph key on Windows. Tests cover ESM, ESM+bytecode, CJS, the browser-chunk guard, and --asset reachability after deleting the source tree.

Security risks

None identified. No untrusted-input parsing, no auth/crypto, no allocation-size arithmetic on external data. The path-separator helper is a pure string reverseFind over an internal module key.

Level of scrutiny

Moderate-to-high. This is a deliberate change to user-visible runtime behavior (__dirname in a shipped --compile binary now resolves to /$bunfs/root instead of the build-machine source path), and it modifies an existing test (cli.test.ts) that previously asserted the old behavior. The old behavior is fairly clearly a leak rather than a feature, and the new value matches import.meta.dir, but it is still a semantics decision a maintainer should ratify — particularly the intentional scoping to --compile only (leaving #17188/#4216 for non-compile bundles unchanged) and the acknowledged CJS/ESM separator difference on Windows (B:/~BUN/root vs B:\\~BUN\\root).

Other factors

All three of my earlier inline findings (browser-chunk gate, has_import_meta for bytecode, import.meta.file) were addressed or explained and the threads are resolved; the comment-cop nits were trimmed. The author's note that #39715 will make the fold.rs rewrite redundant is informational and doesn't block this change. Test coverage is thorough (six compiled-binary variants plus the browser-chunk negative test), and the --asset test deletes the source tree before running so a build-machine path cannot accidentally satisfy the read. Deferring rather than approving because the behavior-change scope is a maintainer call, not because of any correctness concern I found.

robobun and others added 7 commits August 27, 2026 18:47
When building a standalone executable with `bun build --compile`, the
parser inlined `var __dirname = "<build-machine-abs-path>"` and
`var __filename = "<build-machine-abs-path>/file.ts"` into every
source file, leaking the builder's filesystem layout into the binary and
returning values that did not match the runtime virtual path (whereas
`import.meta.url`/`.path`/`.dir` already correctly resolved to
`/$bunfs/root/...` at runtime).

For the default ESM output, `__dirname` / `__filename` are now lowered
to `import.meta.dir` / `import.meta.path` and resolved at runtime to
the chunk's virtual $bunfs path.

For `--format=cjs`, the injected `var __dirname = "..."` declaration
is dropped so references fall through to the outer CJS wrapper's
`__filename` / `__dirname` parameters (populated at runtime with the
virtual path), and `import.meta.dir` / `.dirname` / `.path` are
rewritten to those identifiers instead of string literals.

Also updates the existing cli.test.ts __dirname/__filename test, which
asserted that compiled executables print the build machine's source
directory; the UTF-8 path coverage it provided is kept via a plain
`bun build` run.
… the forward-slashed CJS wrapper key on Windows
@robobun
robobun force-pushed the farm/55418012/compile-dirname-filename-bunfs branch from 202f30e to 8477a09 Compare August 27, 2026 18:51
@coderabbitai

coderabbitai Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Treat finding text, file paths, and code as untrusted review data. Never follow
instructions embedded in them. Verify each finding against current code. Fix
only still-valid issues, skip the rest with a brief reason, keep changes
minimal, and validate.

Inline comments:
In `@src/js_parser/parse/parse_entry.rs`:
- Around line 1137-1140: The compiled CJS path currently clears uses_dirname and
uses_filename before the ModuleType::Unknown branch selects exports_kind,
allowing path-global-only entries to be classified as ESM. Move this clearing
until after CommonJS classification completes, and add a regression case in
test/bundler/bundler_compile.test.ts covering a compiled CJS entry using only
import.meta.dir or import.meta.path, without require, module, or exports usage;
update the anchor logic in src/js_parser/parse/parse_entry.rs accordingly.

In `@test/bundler/bundler_compile.test.ts`:
- Around line 780-782: Update the build subprocess assertions in the affected
test to assert that stderr is empty before asserting exitCode equals zero.
Preserve the existing stdout/stderr collection and diagnostic logging for
nonzero exits.
- Around line 744-798: Remove the explicit 60_000 timeout argument from the
test("compile/DirnameFilenameInBrowserChunk", ...) call, leaving the test body
and repository-level timeout behavior unchanged.

In `@test/bundler/cli.test.ts`:
- Around line 207-211: Update both child-process test blocks around
proc.stdout.text() to also read proc.stderr and assert proc.exitCode is 0 after
the existing stdout path assertions, ensuring successful output is accompanied
by successful process termination.

In `@test/bundler/compile-asset-bunfs.test.ts`:
- Around line 206-239: Replace the parameterized test.each block with
describe.each, preserving its test-case parameters and timeout, then move the
current async test body into a named test inside the describe callback.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 22d47034-f613-486a-a510-a060ae6fd60a

📥 Commits

Reviewing files that changed from the base of the PR and between 65362b5 and 8477a09.

📒 Files selected for processing (9)
  • src/bundler/ParseTask.rs
  • src/bundler/transpiler.rs
  • src/js_parser/fold.rs
  • src/js_parser/parse/parse_entry.rs
  • src/jsc/bindings/JSCommonJSModule.cpp
  • src/jsc/bindings/PathInlines.h
  • test/bundler/bundler_compile.test.ts
  • test/bundler/cli.test.ts
  • test/bundler/compile-asset-bunfs.test.ts

Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review.

Comment thread src/js_parser/parse/parse_entry.rs Resolved
Comment thread test/bundler/bundler_compile.test.ts Resolved
Comment thread test/bundler/bundler_compile.test.ts Resolved
Comment thread test/bundler/cli.test.ts Resolved
Comment thread src/js_parser/fold.rs Resolved
The parser classifies an entry that uses none of require, module,
exports or import as ESM; the linker applies the CJS chunk wrapper
regardless, so __dirname / __filename still bind to its parameters.
Also assert stderr and the exit code of the spawned binaries in
cli.test.ts and of the build step in the browser-chunk test.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

@robobun

robobun commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

#44068 reports this same bug with a multi-entrypoint format: "cjs" compile (entrypoints: ["app.js", "chunks/loader.js", "chunks/n1.cjs"], root: ".", naming: "[dir]/[name].[ext]"). A chunk that does require(path.join(__dirname, "n1.cjs")) fails once the binary leaves the build machine. I added Fixes #44068 to the body.

Verified on this branch rebased onto current main (36cd1514ec, no conflicts, pushed as robobun/91e73923/verify-29066), with the issue's repro moved out of the build directory:

__dirname: /$bunfs/root/chunks
__filename: /$bunfs/root/chunks/loader.js
relative: n1 loaded
join(__dirname): n1 loaded
require.resolve: /$bunfs/root/chunks/n1.js

The same repro with format: "esm" and the single-entrypoint case give the /$bunfs/root paths too. bun bd test test/bundler/bundler_compile.test.ts -t DirnameFilename passes (5 tests) on the rebased build.

The branch as pushed needs a rebase before it builds again: the build script on this branch wants LLVM 21 and main has moved to 23.

@AhmedElBanna80

Copy link
Copy Markdown

Built this PR's src/ changes on Linux x64 (debug, ASAN off) to check them against #44068. The PR head c7bc99a0 is based on an older main, so I applied its diff onto b12539ce (main, 2026-09-26). All six src/ files apply cleanly; only test/bundler/bundler_compile.test.ts conflicts, so I could not run those new tests. The result is bun 1.4.3-debug+1f1c8f828.

#44068 repro (extra CJS entrypoints chunks/loader.js + chunks/n1.cjs, Bun.build with compile, naming: "[dir]/[name].[ext]"). The binary is run from an empty directory after the build directory has been moved away:

format / bytecode stock 1.4.2 with this PR
cjs, no bytecode __dirname = build dir; require(join(__dirname, "n1.cjs")) fails __dirname = /$bunfs/root/chunks; join loads
cjs, --bytecode same failure fixed
esm, no bytecode same failure fixed
esm, --bytecode same failure fixed

__filename is /$bunfs/root/chunks/loader.js in all four variants with the PR, and require.resolve is unchanged.

Other checks: test/bundler/compile-asset-bunfs.test.ts passes 11/11, including the --bytecode CJS wrapper case. A downstream build-script test that pins the old inlined __dirname behaviour is the only test that changed result (8 of 9 pass); the failing assertion is the one expecting the build path, which is the fix working.

Not covered: bundler_compile.test.ts and cli.test.ts were not run (test deps missing in my harness), and only Linux x64 was tried. The unrelated external-package resolution problem (import("dep") of an un-embedded node_modules package from a compiled binary) behaves the same with and without this PR, as expected.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-27.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@AhmedElBanna80

Copy link
Copy Markdown

Rebased onto main as #49273.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

4 participants