Skip to content

bundler: restore the module.exports = {…} → ESM named-exports conversion - #107

Draft
crishoj wants to merge 636 commits into
claude/base-cjs-object-exportsfrom
claude/restore-cjs-object-named-exports
Draft

crishoj wants to merge 636 commits into
claude/base-cjs-object-exportsfrom
claude/restore-cjs-object-named-exports

Conversation

@crishoj

@crishoj crishoj commented Jul 3, 2026

Copy link
Copy Markdown
Owner

Parked. Deliberately opened against this fork (base branch = snapshot of upstream main @ 1498d7b) rather than oven-sh/bun, pending the reception of oven-sh#33280. Retarget/reopen upstream when ready.

What

bun build was meant to convert trivial module.exports = { foo: 'bar' } object literals into ESM named exports since upstream PR oven-sh#3103 (May 2023) — the PR is literally titled "Convert module.exports = { foo: 'bar'} to ESM in bun build". It never worked: the same commit introduced a Zig loop-else bug (the property-validation loop's only exit is return null, no break, so the else — intended as the empty-object de-opt — ran on every completed loop). The rewrite code was dead from day one. The Rust rewrite mirrored the shipped behavior faithfully, and the PORT-NOTE backlog audit (85534281c6) then documented the unconditional de-opt and deleted the dead rewrite code.

Found by auditing all 52 loop-else constructs in the pre-rewrite Zig tree against their Rust ports, after the same bug class produced the fetch Happy Eyeballs stall (oven-sh#33278 / oven-sh#33280). This was the only other live specimen.

How

The rewrite loop in fold.rs is reconstructed from the dead Zig (maybe.zig at 23427dbc12^): per property — visit + simplify the value, get-or-create the $key symbol in commonjs_named_exports, emit var $key = value (was_commonjs_export) plus export { $key as key }, stash everything in commonjs_replacement_stmts (whose splice consumer in visit_stmt.rs survived the port intact), and replace the assignment with E.Missing. The empty-object de-opt becomes an explicit props.is_empty() check.

Two deliberate deviations from the (never-executed) Zig original:

  1. esm_export_keyword is set, matching what the live exports.<name> = ... conversion in visit_stmt.rs does for the same emitted construct. The dead Zig omitted it, but it was never validated.
  2. Duplicate keys emit one export clause. module.exports = { foo: 1, foo: 2 } would have produced two export { $foo as foo } clauses (a duplicate-export error) in the Zig version; instead the second occurrence reassigns the ref, giving correct last-wins semantics.

Tests

Six new cases in bundler_cjs2esm.test.ts, all runtime-verified: the conversion (strings/numbers/identifiers/calls — the four allowed value kinds), namespace import, duplicate-key last-wins, and three pinned de-opts (empty object, method value, exports.foo interplay). The cjs2esm: true harness option asserts zero __commonJS wrappers remain. Verified the three conversion tests fail on an unfixed build. cjs2esm/UnwrappedModuleRequireAssigned's __toESM( assertion is updated (with a stronger not.toContain("__commonJS(")): its fixture's module.exports = { react: "react" } now unwraps fully, so no interop helper remains — its runtime stdout is unchanged.

Suite status: bundler_cjs2esm 22/22; bundler_cjs + bundler_edgecase + bundler_npm 136 pass / 0 fail. A full test/bundler/ run on the dev machine fails only in ways reproducible on unmodified main: --compile tests can't launch ASan-instrumented standalone executables (missing asan-dyld-shim.dylib in Homebrew llvm@21), and a pre-existing debug-JSC !m_topGCOwnedDataScope assertion fires in the macro runner under multi-file heap load (A/B-verified identical on main).

Caveat

This resurrects code that never ran in production. The behavior change is bundler output for CJS modules with trivial object-literal exports (they now become ESM named exports and tree-shake); modules that don't match the trivial shape keep de-opting exactly as before.

@autofix-troubleshooter

Copy link
Copy Markdown

Hi! I'm the autofix logoautofix.ci troubleshooter bot.

It looks like you correctly set up a CI job that uses the autofix.ci GitHub Action, but the autofix.ci GitHub App has not been installed for this repository. This means that autofix.ci unfortunately does not have the permissions to fix this pull request. If you are the repository owner, please install the app and then restart the CI workflow! 😃

robobun and others added 29 commits July 19, 2026 15:23
…always fires (oven-sh#33998)

Fixes `test/js/bun/jsc/bun-jsc.test.ts` going red on the debian 13 x64
lane in [build
72010](https://buildkite.com/bun/bun/builds/72010#019f546c-0875-422c-8f22-fa88eac52a1b):

```
215 |     expect(result2.stackTraces.traces.length).toBeGreaterThan(0);
error: expect(received).toBeGreaterThan(expected)
Expected: > 0
Received: 0
✗ bun:jsc > profile can be called multiple times [4.71ms]
```

### Cause

The test profiles `fib(26)` three times at a 50µs sample interval and
asserts each run collected at least one trace. oven-sh#33072 shrank the
workload from `fib(30)` to `fib(26)` so three runs fit inside the
per-test timeout on slow debug builds. On fast release hardware a
JIT-compiled `fib(26)` can finish inside one 50µs interval (the whole
3-call test completed in 4.71ms there), so the sampler thread simply
never fires during the second call.

This is the same race oven-sh#28873 addressed by lowering the sample interval;
lowering the instruction count in oven-sh#33072 reopened it.

### Fix

Loop `fib(18)` for a fixed 10ms of wall-clock per `profile()` call
instead of relying on a single `fib(n)` being slow enough. 10ms is ~200
sample intervals, so the sampler thread is guaranteed time to fire
regardless of JIT tier or how slowly it wakes after `pause()`/`start()`.
On debug builds the loop still exits after ~12ms of JS work (one
`fib(18)` of overshoot), so the test is no slower there than before.

The test still catches the original regression from oven-sh#25939 (using
`shutdown()` instead of `pause()`): a shut-down sampler returns zero
traces no matter how long the workload runs.

### Verification

- `USE_SYSTEM_BUN=1 bun test test/js/bun/jsc/bun-jsc.test.ts -t 'profile
can be called multiple times'`: 30/30 pass, ~80 traces per call
- `bun bd test test/js/bun/jsc/bun-jsc.test.ts`: 36 pass / 0 fail,
profile test ~1.6s (dominated by the profiler's JSON reporting, same as
before)

This is a timing flake that does not reproduce on the dev container
(`fib(26)` takes ~800µs there after JIT warmup, well above 50µs), so
there is no deterministic fail-before to show; the CI failure above is
the reproduction.

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

---

**no test proof** · iteration 2 · Platform-specific test-only change;
deferring to CI.

<!-- robobun:evidence:end -->
Deletes `src/ptr/owned.rs` and the `Owned<T>` / `OwnedIn<T>` /
`DynamicOwned<T>` type aliases from `src/ptr/lib.rs`.

These were all trivial `= Box<T>` aliases left over from the porting
pass, with no remaining callers. The file was ~260 lines of mapping
comments plus four helper functions, of which only `alloc_dupe_slice` (a
one-line wrapper over `Box::<[T]>::from`) had any users.

Callers updated:
- `src/s3_signing/credentials.rs`: `dupe_slice(&self.field)` on
`Box<[u8]>` fields replaced with `self.field.clone()`
- `src/runtime/test_runner/diff/diff_match_patch.rs`: `alloc_dupe_slice`
import replaced with a local `fn dupe<T: Clone>(s: &[T]) -> Box<[T]>`
(30+ call sites, not worth inlining each)

Also updates two stale doc comments in `bun_alloc` that referenced the
deleted aliases.

Net: +23 / -304.
Follow-up to oven-sh#34763. Removes Zig-port scaffolding that had zero callers
across the workspace (verified by `rg` per item).

### Whole files deleted

| File | Contents | Callers |
|---|---|---|
| `src/ptr/shared.rs` | `Shared<T>=Rc<T>`, `Weak<T>=rc::Weak<T>` + ~100
lines of mapping comments | 0 |
| `src/bun_alloc/maybe_owned.rs` | `MaybeOwned<A>` struct wrapping
`Option<A>` | 0 |
| `src/bun_alloc/BufferFallbackAllocator.rs` | vtable over
FixedBufferAllocator + heap fallback | 0 |
| `src/bun_alloc/fallback.rs` + `fallback/z.rs` | libc-malloc
`CAllocator` + zeroing wrapper; duplicates `basic.rs` | 0 |
| `src/bun_alloc/memory.rs` | `rebase_slice()` | 0 |

### Dead code removed from existing files

- `bun_alloc/lib.rs`: `FixedBufferAllocator` (only caller was
`BufferFallbackAllocator`, deleted above)
- `bun_ptr/lib.rs`: `pub use std::borrow::Cow` +
`CowSlice`/`CowSliceZ`/`CowString` type aliases; `TaggedPointerUnion`
long-name alias
- `bun_collections/array_list.rs` + `lib.rs`:
`ArrayList`/`ArrayListIn`/`ArrayListAligned`/`ArrayListAlignedDefault`
(all aliased to the same struct; `ArrayListDefault` kept, 1 caller)
- `bun_threading/lib.rs`: `pub use std::sync::Once`
- `bun_core/util.rs`: `Guarded<T> = Mutex<T>`
- `bun_core/deprecated.rs`: `DoublyLinkedList`/`DoublyLinkedNode` (~230
lines + unit tests, zero callers)

### Callers updated

- `runtime/jsc_hooks.rs` (2 sites): `bun_ptr::Cow::Borrowed` →
`std::borrow::Cow::Borrowed`
- `runtime/api/bun/subprocess/Readable.rs`,
`runtime/cli/pack_command.rs`: stale comment refs to deleted
`bun_ptr::CowString` alias removed

### Verification

- `bun bd` builds
- `bun run rust:check-all` passes on all 10 targets
(linux/macos/windows/freebsd/android × x64/aarch64)

Net: +14 / -1027.
## Summary

Supersedes oven-sh#33653 (the TinyCC upgrade; the first commit here is that
PR's content) and oven-sh#29476. Enables `bun:ffi` on Windows ARM64: drops the
windows-arm64 exclusion from `cfg.tinycc`, the generated `ENABLE_TINYCC`
constant, and the `tcc_sys` link stubs, un-skips the FFI tests that were
gated on the platform, and bumps the TinyCC pin to
[`oven-sh/tinycc@05f0fafa`](oven-sh/tinycc@05f0faf)
(which is
[`8a6cbc12`](oven-sh/tinycc@8a6cbc1)
plus oven-sh/tinycc#3).

### The windows-arm64 bug this uncovered (root-caused and fixed in the
TinyCC fork)

Enabling the platform made the windows-11-aarch64 CI lane run the FFI
suites on real hardware for the first time, which exposed wrong doubles
(`sum(0.5…9.5)` = 46 instead of 50) and segfaults in every JSCallback
test. Root cause, proven with an in-CI probe that dumped the JIT machine
code from the runner:

TinyCC's arm64 backend decides whether a 64-bit constant fits an ADD/SUB
immediate with `!(val & ~0xffful)`. On an **LLP64 host** (which is
exactly how Bun builds TinyCC into `bun.exe` on Windows via clang-cl)
`unsigned long` is 32 bits, so `~0xffful` zero-extends to
`0x00000000fffff000`, and any constant with no bits in [12,32) "fits".
`1ll << 49` is JSC's `DoubleEncodeOffset`, used by every `bun:ffi`
trampoline, and it compiled to `add xN, xN, #0`:

- machine code on the CI runner: `… ldur x0,[x29,#-8]; add x0,x0,#0 …`
- same source, LP64-built tcc: `… mov x30,#0x2000000000000; add
x0,x0,x30 …`

So every double crossing the FFI boundary lost the NaN-boxing offset (JS
saw `bits − 2^49`: 12.25→11.25, 50→46) and pointer arguments decoded to
wild addresses (the segfaults). LP64-built TinyCC (Linux/macOS) is
unaffected; the fix produces byte-identical output there, which is why
the bug only ever existed on Windows ARM64. Fixed in the fork
(`arm64_gen_opic`, `arm64_check_offset`, `arm64_sym`) by using
`uint64_t`-typed masks; TinyCC's own test suite passes, and
oven-sh/tinycc#3 adds regression cases to `tests2/73_arm64`. This also
affects any natively-built windows-arm64 TinyCC upstream.

### Known parity notes (pre-existing, unchanged)

- `cc()` code with a >4 KB stack frame needs `__chkstk`, which Bun
doesn't provide on any Windows target.
- `long double` soft-float helpers aren't provided on any arm64 target.

## Test plan

- [x] Linux/macOS/Windows-x64 behavior unchanged (same suites as oven-sh#33653;
LP64 tcc output byte-identical across the fix)
- [x] Cross-built windows-arm64 `bun.exe` from Linux links with TinyCC
enabled
- [x] windows-11-aarch64 CI lane: `bun:ffi` suites green with the LLP64
fix (build #71302, and re-verified locally on Windows 11 ARM64 at
`e83d3d00`)

Fixes oven-sh#28055

---------

Co-authored-by: robobun <117481402+robobun@users.noreply.github.com>
`GitHandler::wait()` in `src/runtime/cli/create_command.rs` was calling
`Futex::wait(&SUCCESS, 0, Some(1000))` in a loop. `Futex::wait`'s
timeout is in nanoseconds, so this re-armed a 1 microsecond wait for the
entire duration of the background `git init`/`add`/`commit`, generating
roughly 18k futex syscalls per second on the main thread once `bun
install` had returned.

The git thread already stores the result and calls
`Futex::wake(&SUCCESS, 1)`, so no timeout is needed; switch to
`Futex::wait_forever` and keep the surrounding `while` loop to tolerate
spurious wakeups.

### Verification

Local template with a `file:` dependency (so `bun install` returns in
~20 ms) and a stub `git` on `PATH` that does `sleep 0.5`, so the main
thread spends ~1.5 s in `GitHandler::wait()`:

| | wall | `ru_nvcsw` |
|---|---|---|
| before | 1509 ms | 27,013 |
| after | 1636 ms (debug+ASAN) | 36 |

The new test asserts `resourceUsage().contextSwitches.voluntary < 2000`
for this scenario (POSIX only; the stub `git` is a shell script and
`ru_nvcsw` is always 0 on Windows).

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

---

**[stamp-90s]** gate passed · iteration 1 · 2 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 1 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/bun-create.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (653760d)

test/cli/install/bun-create.test.ts:
(pass) should not crash > ["create"] [110.29ms]
(pass) should not crash > ["create",""] [100.94ms]
(pass) should not crash > ["create","--"] [94.18ms]
(pass) should not crash > ["create","--",""] [100.68ms]
(pass) should not crash > ["create","--help"] [99.58ms]
(pass) should create selected template with @ prefix [491.10ms]
(pass) should create selected template with @ prefix implicit `/create` [485.04ms]
(pass) should create selected template with @ prefix implicit `/create` with version [414.43ms]
(pass) handles a close-delimited GitHub tarball body split across packets [796.53ms]
204 |   const stderr = proc.stderr.toString();
205 |   expect(stderr).not.toContain("error:");
206 |
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (f5781d8)

test/cli/install/bun-create.test.ts:
(pass) should not crash > ["create"] [4.05ms]
(pass) should not crash > ["create",""] [2.05ms]
(pass) should not crash > ["create","--"] [1.90ms]
(pass) should not crash > ["create","--",""] [1.96ms]
(pass) should not crash > ["create","--help"] [2.23ms]
(pass) should create selected template with @ prefix [88.33ms]
(pass) should create selected template with @ prefix implicit `/create` [52.33ms]
(pass) should create selected template with @ prefix implicit `/create` with version [42.99ms]
(pass) handles a close-delimited GitHub tarball body split across packets [39.92ms]
(pass) does not busy-wait on the futex while git runs [1513.85ms]
Copying files... 

[17.00ms] git

[18.00ms] bun create /tmp/cr8-10WJUPSC/bun-create/test-template

Come hang out in bun's Discord: https://bun.com/discord

Created test-template project successfully

# To get started, run:

  cd test-template
  bun dev

(pass) should create template from local folder [22.83ms]
(pass) should name GitHub in the error when the tarball request gets 503 [18.83ms]
(pass) should name GitHub in the error when the tarball request gets 
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/bun-create.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (653760d)

test/cli/install/bun-create.test.ts:
(pass) should not crash > ["create"] [117.21ms]
(pass) should not crash > ["create",""] [100.06ms]
(pass) should not crash > ["create","--"] [102.36ms]
(pass) should not crash > ["create","--",""] [104.29ms]
(pass) should not crash > ["create","--help"] [107.74ms]
(pass) should create selected template with @ prefix [416.20ms]
(pass) should create selected template with @ prefix implicit `/create` [412.45ms]
(pass) should create selected template with @ prefix implicit `/create` with version [414.28ms]
(pass) handles a close-delimited GitHub tarball body split across packets [788.37ms]
(pass) does not busy-wait on the futex while git runs [1665.16ms]
Copying files... 

[16.00ms] git
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
[configured] bun-profile → bun (stripped) in 701ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/6] gen generated_host_exports.rs
generated_host_exports.rs: 91 exports (host=3, lazy=10, generic=78, rust=0); 244 extern-C blocks audited
[1/6] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: component rust-std is up to date

info: checking for self-update (current version: 1.29.0)
  nightly-2026-05-06-x86_64-unknown-linux-gnu unchanged - rustc 1.97.0-nightly (e95e73209 2026-05-05)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_alloc v0.0.0 (/workspace/bun/src/bun_alloc)
�
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/runtime/cli/create_command.rs   |  2 +-
 test/cli/install/bun-create.test.ts | 39 ++++++++++++++++++++++++++++++++++++-
 2 files changed, 39 insertions(+), 2 deletions(-)
```

</details>

**gate history** · 2 passed · 0 rejected · iteration 1

<details><summary>evidence per changed file</summary>

```
file                                 reads  edits  tests
src/runtime/cli/create_command.rs        2      1      0
test/cli/install/bun-create.test.ts      1      5      0
```

</details>

<!-- robobun:evidence:end -->
… on Windows (oven-sh#34769)

On Windows, `path.resolve("C:foo")` returns corrupted output instead of
resolving against the per-drive cwd stored in the `=C:` environment
variable.

## Repro (Windows, pwsh)

```
> bun -e 'console.log(require("path").resolve("C:foo"))'
C:\Users\azureusC:\C:\U
> node -e 'console.log(require("path").resolve("C:foo"))'
C:\Users\azureuser\foo
```

## Cause

`resolve_windows_t` in `src/runtime/node/path.rs` keeps the accumulated
path tail in `buf2[0..resolved_tail_len]`. When a drive-relative input
has been seen (`resolvedDevice == "C:"`, `resolvedTail == "foo\\"`,
`resolvedAbsolute == false`), the final loop iteration reads the `=C:`
env var via `GetEnvironmentVariableW` and writes the value into `buf2`
starting at index 0, clobbering the tail that was already there. The
subsequent `resolvedTail = ${path.slice(rootEnd)}\\${resolvedTail}` step
then splices fragments of the env value into itself.

In Node's JS implementation this is a fresh string so it can never
alias; the Rust port reuses caller-provided buffers and picked the one
already occupied.

## Fix

Write the env value into `tmp_buf` after the resolved device prefix
(`tmp_buf[resolved_device_len..]`) instead of `buf2`. That region is
scratch at this point: the device occupies `tmp_buf[0..2]`, and nothing
reads past it until the UNC builder (which is guarded away when a device
is already set). `path_ptr` is adjusted to point there. The later
tail-prepend copies from `tmp_buf` into `buf2` with no overlap.

## Verification

Fail-before on Windows with the released binary:

```
USE_SYSTEM_BUN=1 bun test test/js/node/path/resolve.test.js
...
(fail) path.resolve > win32 drive-relative input resolves against the per-drive cwd (=X: env var)
  Expected: ["C:\\known\\dir\\foo", ...]
  Received: ["C:\\known\\dC:\\C:\\k", ...]
```

Pass-after with the debug build: `bun bd test test/js/node/path/` on
Windows, 122 pass / 0 fail. Full `test/js/node/path/` on Linux also 122
pass / 0 fail (new test skipped there). `cargo check -p bun_runtime
--target x86_64-pc-windows-msvc` clean.

The new test is `skipIf(!isWindows)` because the env-lookup branch is
inside `#[cfg(windows)]`; on a non-Windows host `resolve_windows_t`
takes the cwd fallback instead, so this code path does not exist. The
Linux gate cannot observe a fail-before for a `#[cfg(windows)]`-only
code path; the Windows fail-before/pass-after above is the evidence.

Related: oven-sh#31735 fixes the adjacent non-Windows cwd fallback and the
drive-mismatch fallback (different branches of the same else-block);
this PR does not overlap with it.

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

---

**no test proof** · iteration 1 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/node/path/resolve.test.js

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

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
… (Windows) (oven-sh#34776)

## What

`process.dlopen({exports:{}}, "x".repeat(40000))` on Windows panics
across the `extern "C"` boundary instead of returning an error:

```
panic: range end index 40000 out of range for slice of length 32767
oh no: Bun has crashed. This indicates a bug in Bun, not your code.
```

## Why

`Bun__LoadLibraryBunString` (`src/sys/windows/mod.rs`) wrote the
JS-supplied path into a fixed `WPathBuffer` (`[u16; 32767]`) with
unbounded `buf[..src.len()]` slicing in the Latin-1/UTF-16 arms and a
panicking `convert_utf8_to_utf16_in_buffer` in the UTF-8 arm. The
sibling `DynLib::open` already returns `ENAMETOOLONG` for the same
input.

## Fix

Add `String::encode_into_utf16_buf_z`, a bounds-checked helper on
`bun_core::String` that covers all three backing encodings (reusing
`try_convert_utf8_to_utf16_in_buffer` and `copy_latin1_into_utf16`,
mirroring the `to_w_path_maybe_dir` shape) and returns `None` on
overflow. `Bun__LoadLibraryBunString` now uses it and, on overflow, sets
`ERROR_FILENAME_EXCED_RANGE` and returns null so the existing C++
`GetLastError()` path yields `ERR_DLOPEN_FAILED: LoadLibrary failed: The
filename or extension is too long.`, matching POSIX behavior.

## Verification

```
> bun bd -e "try { process.dlopen({exports:{}}, Buffer.alloc(40000, 'x').toString()) } catch (e) { console.log('CAUGHT:', e.code, String(e.message).slice(0,80)) }"
CAUGHT: ERR_DLOPEN_FAILED LoadLibrary failed: The filename or extension is too long.
```

Test added in `test/js/node/process/process.test.js` alongside the other
dlopen tests; fails on Windows before the fix (subprocess aborts with
the panic above), passes after on both Windows and POSIX.

<!-- 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/js/node/process/process.test.js

<!-- robobun:evidence:end -->
…4779)

## Problem

The timer heap inserts and drains
`setTimeout`/`setInterval`/`AbortSignal.timeout` deadlines against
`Timespec::now()` (`src/runtime/timer/mod.rs`). On unix this reads
`CLOCK_MONOTONIC`, but on Windows `Timespec::now_real()` fell through to
`time::nano_timestamp()`, which is `GetSystemTimePreciseAsFileTime`
(wall clock):

```
> bun --expose-internals -e "console.log(require('bun:internal-for-testing').timerInternals.timerClockMs(), Date.now())"
1784526245451 1784526245451
```

So an NTP correction, manual clock change, or VM-suspend/restore step
would stall every pending timer (backward step) or fire them all at once
(forward step). The `uv_timer` wakeup is also armed against libuv's
monotonic clock while the heap used wall time, so the two could
disagree.

## Fix

Route the Windows arm of `Timespec::now_real()` through the existing
`clock_gettime_monotonic` QPC shim in `c-bindings.cpp`. This is the same
monotonic clock that libuv (`uv_hrtime`), uSockets' sweep
(`io::Loop::update_timespec`), `performance.now()`
(`std::time::Instant`) and `WTF::MonotonicTime::now()` already use.

After:

```
> bun-debug --expose-internals -e "console.log(require('bun:internal-for-testing').timerInternals.timerClockMs(), Date.now(), require('os').uptime())"
448690 1784526554334 448.671
```

## Caller audit

All `Timespec::now` / `ms_from_now` / `since_now` call sites were
checked. Every site uses the value as a delta or for ordering against
another `Timespec::now`-derived deadline (timer heap inserts,
elapsed-time logging, debugger wait loops, DNS cache TTL comparison), so
changing the Windows epoch from 1970 to boot is safe. Absolute-value
uses:

- Heap/CPU profiler default filenames (`{timestamp}.{pid}`): already
boot-relative on unix, so Windows now matches.
- `InspectorHTTPServerAgent::notify_server_started`
(`src/runtime/server/mod.rs`): was sending `Timespec::now().ms()` while
its sibling `notify_server_stopped` sends wall-clock
`milli_timestamp()`. Switched to `milli_timestamp()` so DevTools
receives start/stop on the same clock on every platform.

## Cleanup

- `c-bindings.cpp`: `clock_gettime_monotonic`'s `static LARGE_INTEGER
ticksPerSec` is now a C++11 thread-safe static (lambda initializer).
This PR makes the shim reachable from multiple threads (Worker timer
heaps, install threadpool) for the first time; the previous
unsynchronized lazy-init was a benign-in-practice data race.
- Removed the dead calibrated-TSC `src/perf/hw_timer.rs` (zero callers;
docstring referenced a `now_ns()` that was never ported).
- Replaced the stale "monotonic-ish rough tick / routes through
getRoughTickCount" doc comment on `Timespec::now` with an accurate one.

## Testing

Added a test asserting `timerInternals.timerClockMs()` is non-decreasing
and `< Date.now() / 2` (boot-relative vs epoch). Verified it fails on
Windows canary and passes with this change on both Windows (`a793f869b`)
and Linux. Full `setTimeout.test.js` suite passes on Windows debug.

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

---

**no test proof** · iteration 1 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/web/timers/setTimeout.test.js

<!-- robobun:evidence:end -->
…s mode (oven-sh#34773)

## Repro

```js
const fs = require("fs");
fs.writeFileSync("f.txt", "0123456789");
fs.writeFileSync("f.txt", "ZZ", { flag: fs.constants.O_WRONLY | fs.constants.O_CREAT });
fs.readFileSync("f.txt", "utf8");
// node, bun linux:  "ZZ23456789"
// bun windows:      "ZZ"
```

The inverse also fails: `O_WRONLY | O_CREAT | O_APPEND | O_TRUNC` is
supposed to empty the file at open and then append, but on Windows it
appends to the existing content (the test for this was added in oven-sh#33355
and left `skipIf(isWindows)` pointing at this bug).

## Cause

`openat_windows_impl` (the POSIX-flag to `NtCreateFile` bridge used by
`bun_sys::openat` on Windows) picked its create disposition from the
access mode:

```rust
let overwrite = (flags & O::WRONLY) != 0 && (flags & O::APPEND) == 0;
```

`O::TRUNC` was never consulted, so `O_WRONLY|O_CREAT` became
`FILE_OVERWRITE_IF` (truncates) while `O_RDWR|O_CREAT|O_TRUNC` became
`FILE_OPEN_IF` (preserves). `Dir::create_file_z({ read: true, truncate:
true })` and any other `O_RDWR|O_TRUNC` caller silently did not
truncate.

The user-visible symptom above is `fs.writeFileSync`, whose
`write_file_with_path_buffer` opens via `sys::openat` (the NtCreateFile
path, not libuv) since oven-sh#33355 gated the post-write resize on `O_TRUNC`.

## Fix

Derive the create disposition from `O_CREAT`/`O_EXCL`/`O_TRUNC` alone;
the read/write access mode only affects `access_mask`.

```rust
match (creat, excl, truncate) {
    (true,  true,  _)     => FILE_CREATE,
    (true,  false, true)  => FILE_OVERWRITE_IF,
    (true,  false, false) => FILE_OPEN_IF,
    (false, _,     true)  => FILE_OVERWRITE,
    (false, _,     false) => FILE_OPEN,
}
```

Two internal callers were relying on the old `O_WRONLY` implying
truncation and now pass `O::TRUNC` explicitly:
`CopyFileWindows::prepare_pathlike` and the resolver's Windows tmpfile.

Sites where the new mapping changes behavior and that change is kept:

- `libarchive/lib.rs:1639` opens `O_WRONLY` then reads `get_file_size`;
the old `FILE_OVERWRITE` left it reading zero, so the existing-content
branch was dead on Windows.
- `FileSink::Options::flags()` returns `O_WRONLY|O_CREAT` (no `O_TRUNC`)
and its `truncate: bool` field is never read. On POSIX this already
meant no truncation; Windows now matches. `Bun.file(path).writer()` on
Windows is unaffected either way since it pre-opens via libuv before
FileSink is constructed, so only the narrow `sink.start({path})` surface
sees the alignment. The dead `truncate` field is pre-existing and
cross-platform; fixing it here would flip the main POSIX writer entry,
so it is left for a separate change.

## Verification

`test/js/node/fs/fs.test.ts` gains a `writeFileSync numeric open-flag
matrix` block that walks every `{O_WRONLY, O_RDWR} x {0, O_CREAT,
O_TRUNC, O_CREAT|O_TRUNC, O_CREAT|O_EXCL, O_CREAT|O_EXCL|O_TRUNC}`
combination plus the four `O_WRONLY|O_APPEND` variants, each against
both an existing and a missing file (16 cases x 2), and asserts the
exact resulting contents or error code against Node's behavior.
`writeFileSync` opens via `bun_sys::openat` on Windows, so the matrix
exercises the NtCreateFile disposition mapping directly; on POSIX it is
the plain `openat(2)` behavior.

Four rows fail on Windows before this change (`WRONLY` and
`WRONLY|CREAT` with `"ZZ"` instead of `"ZZ23456789"`, and
`WRONLY|APPEND|TRUNC` / `WRONLY|CREAT|APPEND|TRUNC` with
`"0123456789ZZ"` instead of `"ZZ"`) and all 16 pass after on both
platforms. The previously-`skipIf(isWindows)` `O_APPEND|O_TRUNC` test
from oven-sh#33355 is removed in favor of the matrix row.

<!-- 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/js/node/fs/fs.test.ts

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

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…it) (oven-sh#34768)

## What

Implements `--no-orphans` / `BUN_FEATURE_FLAG_NO_ORPHANS` / `[run]
noOrphans` on Windows. Previously `ParentDeathWatchdog` was a no-op stub
there, so a `TerminateProcess` on Bun's parent left Bun running, and a
`TerminateProcess` on Bun left its descendant tree running.

## How

`enable()` on Windows now does two things:

**Descendant cleanup.** Create an anonymous Job Object with
`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` and `AssignProcessToJobObject(job,
GetCurrentProcess())`. The handle is leaked for the process lifetime.
Children inherit Job membership via nested jobs (Win8+), so when Bun
exits for any reason, including `TerminateProcess`, the kernel closes
the Job handle and terminates every descendant. This is the same
primitive already used in `test/parallel/Coordinator.rs` and the
`--watch` manager, just applied to the current process instead of a
specific child.

libuv's `uv_spawn` already maintains a per-process kill-on-close job for
direct `Bun.spawn` children, but it sets
`JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK` so membership is not inherited
recursively: anything a `Bun.spawn`'d child itself spawns (cmd.exe ->
tool, npm script -> compiler, a shell wrapper, etc.) breaks away
silently and survives. The `--no-orphans` job omits
`SILENT_BREAKAWAY_OK` so the whole tree is covered.

**Parent watch.** Read `InheritedFromUniqueProcessId` via
`NtQueryInformationProcess(ProcessBasicInformation)`,
`OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION)` on it,
and `RegisterWaitForSingleObject(..., WT_EXECUTEONLYONCE)`. When the
parent's process object is signaled (i.e. has terminated) the system
thread-pool callback calls `ExitProcess(129)`, which in turn closes the
Job handle and reaps descendants.

`InheritedFromUniqueProcessId` is frozen at our creation (Windows has no
reparenting), so a PID-reuse guard compares `GetProcessTimes` creation
times: a real creator was created no later than us, a recycled PID
strictly later. If the creator is already gone at `enable()` time we
exit immediately, matching the Linux/macOS race branches.

## Tests

`test/cli/run/no-orphans.test.ts`:

- `spawnTree()` now uses cmd.exe as the supervisor on Windows, so the
five core parent-watch tests ("bun exits when its parent is SIGKILLed",
"grandchildren are reaped", "=0 is unset", "does not fire while parent
is alive", and the negative control) run on all three platforms.
- New Windows-only tests for the recursive Job Object: test -> bun ->
cmd.exe -> leaf, where cmd.exe is the non-libuv link that escapes
libuv's `SILENT_BREAKAWAY` job but not the `--no-orphans` job. Covers
`--no-orphans`, `BUN_FEATURE_FLAG_NO_ORPHANS=1`, and bunfig `[run]
noOrphans`.
- POSIX-mechanism-specific tests (pdeathsig re-arm, subreaper, libproc
walk, perl setsid daemons, TTY job control) stay `skipIf(!isPosix)`.

Verified on windows-x64: canary fails 6/9 (3 negative controls pass),
this build passes 9/9. Linux: 18 pass, 4 Windows tests skip, one
pre-existing root-only uid/gid failure unrelated to this change.

<!-- 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/cli/run/no-orphans.test.ts

<!-- robobun:evidence:end -->
Follow-up to oven-sh#34763 and oven-sh#34767. Third pass removing zero-caller `pub
type` / `pub use` aliases left over from the Zig port, this time
reaching into mid-tier crates (jsc, http, io, install, ast, bundler,
runtime) in addition to the foundation tier.

### Zero-caller aliases deleted

| Crate | Items |
|---|---|
| `bun_alloc` | `VTable`, `Bump`, `IndexMapManaged` |
| `bun_ptr` | `IntrusiveArc`, `weak_ptr::Data` |
| `bun_collections` | `StaticBitSet` |
| `bun_threading` | `guarded::Debug`, `DebugGuarded` |
| `bun_core` | `util::PollFlag`, `output::LogFunction`, `wtf::{RefPtr,
StringImpl}`, `windows_sys::{UnicodeString, kernel32 as c}`,
`deprecated::RapidHash` re-export + SinglyLinkedList tombstone comment |
| `bun_jsc` | `IntegerRangeOptions`, `ErrorableZigString`,
`ErrorableJSValue` |
| `bun_http` | `H2`, `new_http_context`, `HttpContext`, `HttpThread`,
`http_client_result` |
| `bun_io` | `EventLoopKind`, `PipeReader` |
| `bun_install` | `lockfile::{SerializerLoadResult, ScriptsListKind}` |
| `bun_ast` | `ExprInit` |
| `bun_bundler` | `GraphStruct`, `Cache` |
| `bun_runtime` | `valkey_jsc::valkey_body`, `test_runner::HookKind`,
orphaned comment in JSTranspiler.rs |

### Caller rewrites (1 call site each)

- `runtime/allocators/LinuxMemFdAllocator.rs`: `bun_ptr::IntrusiveArc` →
`bun_ptr::RefPtr` (IntrusiveArc was a type alias for RefPtr)
- `bun_core/util.rs`: `crate::deprecated::RapidHash` →
`bun_hash::RapidHash` (direct path to canonical impl)

### Stale comment refs updated

- `url/lib.rs`: StaticBitSet → IntegerBitSet
- `runtime/socket/Listener.rs`: PipeReader → BufferedReader
- `runtime/allocators/LinuxMemFdAllocator.rs`: IntrusiveArc → RefPtr

### Verification

- `bun bd` builds
- `bun run rust:check-all` passes on all 10 targets

Net: +13 / -110.

No test added: every deleted item had zero callers (verified by
workspace-wide `rg` per item); the two rewrites are to the type the
alias already resolved to.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…es (oven-sh#34787)

## What

Posts a fallback Buildkite error annotation for any step that exits
non-zero without having reported its own failure, so infra failures show
up in the build's annotation list instead of only in the raw job log.

## Why

`scripts/runner.node.mjs` (test steps) and `scripts/build/ci.ts` (build
steps) post failure annotations themselves. Anything that kills the step
before they get that far (agent command-hook failures such as a tart
guest that never boots, artifact download failures, `node` missing, or
the reporter script itself crashing) leaves the job red with nothing in
the annotation list.

Example:
https://buildkite.com/bun/bun/builds/76001#019f7df3-f093-4bdd-b34d-f332071e98ae
failed with

```
guest never up after retry
The number of VMs exceeds the system limit (other running VMs: warmkeeper, sc-019f7df3-f094-4e69-9dac-02bf41b9f3bb, bk-019f7df3-f094-4e69-9dac-02bf41b9f3bb)
```

but the build's annotation list showed nothing for that lane.

## How

- `scripts/utils.mjs`: new `markBuildkiteStepReported()` sets build
meta-data `reported-<job-id>=1`. Meta-data is server-side, so it
survives the tart host/guest boundary (the darwin tart agents forward
the Job API socket into the guest).
- `scripts/runner.node.mjs`, `scripts/build/ci.ts`,
`scripts/verify-baseline.ts`, `scripts/binary-size.ts`: call it at their
controlled exit points, after posting their own annotations.
- `.buildkite/hooks/pre-exit` (repository hook, runs on every posix
agent): if `BUILDKITE_COMMAND_EXIT_STATUS != 0` and the
`reported-<job-id>` marker is missing, post a `step failed outside
runner` error annotation. On tart hosts it also includes the tail of
`/tmp/{bk,sc}-<job-id>.log` (the `tart run` output) when that contains
anything other than `Stopping VM...`. Always exits 0. Windows agents
look for `pre-exit.{bat,ps1}` and ignore this file.

## Verification

Hook picked up and run on a real tart job from this branch's build 76102
(the log shows `~~~ Running local pre-exit hook` / `$
.buildkite/hooks/pre-exit`); the job passed so the hook correctly did
nothing.

Hook logic tested locally and on a tart host under bash 3.2 against the
real failed-job log above, a clean-stop log, a missing log, and
with/without the `reported-` marker set.

`bunx tsc --noEmit -p scripts/build/tsconfig.json` output unchanged.

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

---

**no test proof** · iteration 0 · build/CI scripts only; test-proof not
applicable

<!-- robobun:evidence:end -->
…tring (oven-sh#34797)

## What

Two functions in `src/dns/lib.rs` declared `Result<_, AllocError>`
return types but the `Err` variant was provably unreachable. Change them
to return the value directly and drop the dead error-handling at call
sites.

- `GetAddrInfoResult::to_list` (lib.rs:331): body only calls
`Vec::with_capacity` / `push`, which abort on OOM; no `?` or `return
Err` anywhere.
- `address_to_string` (lib.rs:364): every match arm returned `Ok(...)`;
`BunString::create_format` / `clone_latin1` / `EMPTY` all yield
`BunString` directly, not `Result`.

Call sites carried dead handling:
- `dns_jsc/dns.rs:1287`:
`bun_core::handle_oom(GetAddrInfoResult::to_list(...))` on a function
that cannot return `Err`
- `dns_jsc/dns.rs:1600` (Windows): `.unwrap_or_default()`, which would
have silently swallowed a real error into an empty list had one ever
been introduced
- `dns_jsc/options_jsc.rs:250`: a dead `Err(_) => throw_out_of_memory()`
match arm

Also drops `bun_alloc` as a direct dependency of the `bun_dns` crate
(`AllocError` was its only use).

## Why

The signature lied about fallibility. `Vec::push` in Rust never returns
`Err` on OOM; it aborts via the global allocator's error hook. Declaring
`Result<_, AllocError>` on top of infallible operations forces callers
to write error branches that can never execute, and the
`.unwrap_or_default()` at the Windows call site was a quiet footgun: if
this function ever became genuinely fallible, OOM would produce an empty
result list instead of a crash.

## Verification

Behavior-preserving refactor; no runtime change. Verified:
- `cargo check -p bun_dns` and `cargo check -p bun_runtime` clean on
both `x86_64-unknown-linux-gnu` and `x86_64-pc-windows-msvc`
- `cargo clippy -p bun_dns --no-deps` clean
- `bun bd test test/js/bun/dns/resolve-dns.test.ts -t localhost`
(exercises `to_list` via the libc/system backends and
`address_to_string` via `address_to_js`): 27 pass / 0 fail
- `bun bd test test/js/node/dns/node-dns.test.js -t localhost`: 3 pass /
0 fail

Net: +12 / -22.
Six dead-by-construction predicates in the shell parser, all carried
over from the original Zig source. No behavior change.

### `Parser::delimits` (parse.rs)

```rust
tag == TokenTag::Delimit
    || tag == TokenTag::Semicolon
    || tag == TokenTag::Semicolon   // same comparison twice
    || tag == TokenTag::Eof
```

The duplicate is not a placeholder for a missing tag: the sibling
`expect_delimit` (which `debug_assert!`s on `delimits`) checks exactly
`{Delimit, Semicolon, Newline, Eof, subshell-closer}` once each.

### `|` and `&` lexer arms (parse.rs)

```rust
} else if next.escaped || next.char != u32::from(b'&') {
    self.tokens.push(Token::Ampersand);
} else if next.char == u32::from(b'&') {   // already implied by negating the line above
    ...
} else {                                    // unreachable
```

Reaching the third arm means `!(next.escaped || next.char != b'&')`,
i.e. `!next.escaped && next.char == b'&'`, so the guard is always true
and the trailing `else` is dead. Collapsed to a plain `else`. The `|`
arm ~55 lines above has the byte-identical `else if next.char == b'|'`
shape (without the trailing dead `else`) and is collapsed the same way.

### `SmolList::init_with` / `init_with_slice` (parse.rs)

```rust
let mut this = Self::zeroes();                      // always SmolList::Inlined(..)
if let SmolList::Inlined(inlined) = &mut this { ... }
```

`zeroes()` unconditionally returns the `Inlined` variant, so the `if
let` is always taken and reads as though the value(s) could be silently
dropped. Both constructors now build the `SmolListInlined` directly and
wrap it. (`zeroes()` itself stays: it has other callers.)

### `parse_expansion` loop (braces.rs)

```rust
while !self.match_any(&[TokenTag::Close, TokenTag::Eof]) {
    if self.r#match(TokenTag::Eof) { break; }       // peek() is already known not to be Eof here
```

`match_any` peeks, advances only on a match, and returns `false` without
advancing otherwise. Entering the body therefore guarantees `peek()` is
neither `Close` nor `Eof`, so the inner `Eof` check can never fire.

### Verification

`cargo clippy -p bun_shell_parser` is clean.
`test/js/bun/shell/{parse,lex,brace,bunshell}.test.ts` pass on the debug
build. There is no fail-before test to add: none of these branches are
observable from JS (the conditions are tautologies, not
mis-evaluations), so any test exercising them passes identically before
and after.
…orbid_lexical_decl (oven-sh#34795)

## What

Five helpers on `P<'a, ...>` returned `Result<T, crate::Error>` with no
reachable `Err` path. This changes them to return `T` directly and
deletes the `?` / `.expect("unreachable")` / `.expect("oom")` noise at
~95 call sites across 16 files.

| function | was | now | why it cannot fail |
|---|---|---|---|
| `new_symbol` | `Result<Ref, Error>` | `Ref` | arena-Vec `push`
(infallible) + `Ref::new` |
| `store_name_in_ref` | `Result<Ref, Error>` | `Ref` | pointer-range
check + arena-Vec `push` |
| `forbid_lexical_decl` | `Result<(), Error>` | `()` | `Log::add_error`
returns `()` |
| `create_default_name` | `Result<LocRef, Error>` | `LocRef` | only
fallible step was `new_symbol` |
| `declare_generated_symbol` | `Result<Ref, Error>` | `Ref` | only
fallible step was `new_symbol` |

The `ParserLike::store_name_in_ref` trait method is updated to match.

## Why

Every single caller already treated failure as impossible: either `?`
threading an error that never materializes, or `.expect("unreachable")`
/ `.expect("oom")` encoding the invariant as a runtime panic string.
This moves the invariant to the type system where the compiler enforces
it, and deletes ~50 lines of ceremony.

This is the parser's `P::new_symbol`; `AstBuilder::new_symbol` in the
bundler is a different function that can return `OOM` and is unchanged.

`mark_strict_mode_feature` has the same shape (logs and returns
`Ok(())`) but unwrapping it cascades through `declare_symbol` and
`declare_binding` into a much larger diff; left for a follow-up.

## Verification

No behavior change is possible here: the removed `Err` arms were dead.
`cargo check -p bun_js_parser -p bun_bundler` is clean, and the existing
suites pass unchanged under the debug build:

- `test/bundler/transpiler/transpiler.test.js` (182 pass)
-
`test/bundler/transpiler/{decorators,export-default,react-compiler}.test.*`
(57 pass)
- `test/bundler/esbuild/ts.test.ts` (57 pass)

Because there is no observable runtime delta, a fail-before/pass-after
test is not constructible; the compiler is the proof.

Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
… let-else (oven-sh#34790)

## What

Several sites in `src/js_printer/lib.rs` check an enum variant with
`matches!()` and then immediately re-match the same value with a `_ =>
unreachable!()` wildcard to extract the payload:

```rust
if matches!(e.left.data, ExprData::EPrivateIdentifier(_)) && e.op == Op::Code::BinIn {
    let private = match &e.left.data {
        ExprData::EPrivateIdentifier(p) => p,
        _ => unreachable!(),
    };
    ...
}
```

The `matches!()` guard already proves the wildcard arm dead, so the
second match is redundant. `if let` / `let else` matches once and binds
the payload in the same step:

```rust
if let ExprData::EPrivateIdentifier(private) = &e.left.data
    && e.op == Op::Code::BinIn
{
    ...
}
```

Sites touched:

- `binary_check_and_prepare`: `#foo in bar` private-identifier special
case
- `print_decls` (`SAME_TARGET_BECOMES_DESTRUCTURING`): the `var a =
obj.foo, b = obj.bar` to `var {foo: a, bar: b} = obj` minification,
three occurrences

## Why

The adjacent code in `print_decls` already uses `let else` for the exact
same shape (the `target_value` / `target_e_dot` bindings right above).
This brings the rest of the block in line with that idiom and drops six
provably-dead `unreachable!()` arms plus the `.as_ref().unwrap()` pairs
that went with them. Net -23 lines.

## Verification

This is a no-behavior-change refactor. Output is byte-identical before
and after:

```
$ bun -e 'const t = new Bun.Transpiler({minifyWhitespace: true});
  console.log(t.transformSync("var a = obj.foo, b = obj.bar, c = obj.baz;"));
  console.log(t.transformSync("class Foo { #foo; check(o) { return #foo in o; } }"));
  console.log(t.transformSync("var a = obj.foo, b = other.bar;"));
  console.log(t.transformSync("var a = obj?.foo, b = obj.bar;"));
  console.log(t.transformSync("var a = obj.foo, b;"));
  console.log(t.transformSync("var {x} = obj.foo, b = obj.bar;"));'
var{foo:a,bar:b,baz:c}=obj;
class Foo{#foo;check(o){return#foo in o}}
var a=obj.foo,b=other.bar;
var a=obj?.foo,b=obj.bar;
var a=obj.foo,b;
var{x}=obj.foo,b=obj.bar;
```

`bun bd test test/bundler/transpiler/transpiler.test.js`: 182 pass, 0
fail.

Because there is no observable behaviour change, there is no fail-before
test to add; the existing `private identifiers` cases in
`transpiler.test.js` continue to cover the first site.
…sh#34804)

Three no-op statements left over from the Zig port, all provably
unreachable or redundant. No behavior change.

### `List::and_range` (`SemverQuery.rs`)

```rust
let mut tail = Box::new(Query { range: *range, next: None });
tail.range = *range;
```

`range: &Range` is an immutable reference and `Range` is `Copy`, so the
second store writes the same value it already holds.

### `query::parse` hyphen lookahead (`SemverQuery.rs`)

```rust
i += strings::length_of_leading_whitespace_ascii(&input[i..]);
if i == input.len() { break 'possibly_hyphenate false; }
if !(i < input.len() && matches!(input[i], b'0'..=b'9' | b'X' | b'x' | b'*')) { ... }
```

`length_of_leading_whitespace_ascii` returns at most its slice's length,
so after the addition `i <= input.len()`. The preceding `i ==
input.len()` check then leaves `i < input.len()` as the only remaining
case, so the guard in the next condition is always true.

### `Version::parse` tag arm (`Version.rs`)

```rust
b'-' | b'+' => {
    ...
    part_start_i = i;
    while i < input.len() && matches!(input[i], b' ') { i += 1; }
```

This arm is entered via `match input[i]` with `i` unchanged between
dispatch and the loop, so `input[i]` is `-` or `+` and the loop
condition is false on the first iteration. `Tag::parse` reads from
`part_start_i` (set before the loop) regardless.

### Why no new test

These are identity transformations on the compiled function: the dropped
store writes the value already present, and the dropped guards evaluate
to the branch already taken on every input. There is no input that can
distinguish before from after. Regression coverage is the existing
`test/cli/install/semver.test.ts`, which exercises `List::and_range`
(multi-comparator ranges), the hyphen-range lookahead, and version tag
parsing.

### Verification

```
$ cargo clippy -p bun_semver
    Finished `dev` profile
$ bun bd test test/cli/install/semver.test.ts
 28 pass
 0 fail
 1946 expect() calls
```
…er (oven-sh#34792)

## What

Removes four dead guards in `src/sql/` that are porting artifacts from
the Zig rewrite (oven-sh#30412). In Zig the original code initialized buffers
with `undefined` and had different slice-length contracts; in Rust these
checks are provably unreachable.

No behaviour change.

## Why each one is dead

**`src/sql/mysql/protocol/PreparedStatement.rs` `write_null_bitmap`:**
`[0u8; MYSQL_MAX_PARAMS]` is zero-initialized by the language, so the
subsequent `.fill(0)` on a sub-slice writes zeros over zeros. The
sibling `NewWriter::write_null_bitmap`
(src/sql/mysql/protocol/NewWriter.rs:104) already omits the fill.

**`src/sql/mysql/protocol/HandshakeV10.rs`:** `auth_plugin_data_len` is
floored to 21 before the subtraction, so `auth_plugin_data_len - 8 >=
13` and `.max(13)` is a no-op. Collapsed the `if` clamp and the later
`.max(13)` into a single `.max(21)`, which also lets the binding lose
`mut`.

**`src/sql/postgres/CommandTag.rs`:** `strings::index_of_char` wraps
`highway::index_of_char`, which returns `None` when the byte is absent
and otherwise an index strictly inside the slice (the implementation
`debug_assert!`s `haystack[result] == needle`). So `idx + 1 <= len` and
`.min(len)` on `idx + 1` is a no-op. Three call sites.

**`src/sql/postgres/protocol/NewReader.rs` `int<Int>`:** both concrete
postgres `ReaderContext::read` implementations, the shared
`StackReader::read` (src/sql/shared/StackReader.rs:94) and the
live-socket `Reader::read`
(src/sql_jsc/postgres/PostgresSQLConnection.rs:1743), either return
`Err(ShortRead)` or a slice of exactly `count` bytes. The `slice.len() <
Int::SIZE` re-check is unreachable under every extant impl, and
`from_be_slice` already slices `[..SIZE]` internally so an undersized
input from a future implementation would still fail loudly rather than
silently. Added a doc comment on the trait method stating the contract.

## Verification

`cargo check -p bun_sql` and `cargo clippy -p bun_sql` are clean. The
existing fault-injection protocol tests that exercise `HandshakeV10`
decoding and `NewReaderWrap::int` still pass under `bun bd`:

```
test/js/sql/sql-mysql-auth-short-nonce.test.ts        2 pass
test/js/sql/postgres-invalid-message-length.test.ts  10 pass
```

This is a pure refactor with no observable difference on any input, so
there is no test that can fail on the released binary and pass on this
branch; the justification is the analysis above plus the existing
coverage.
…oven-sh#34806)

Follow-up to oven-sh#34763, oven-sh#34767, oven-sh#34778.

### bumpalo dependency removed

`bumpalo` is dropped from the workspace root and 10 member crates (ast,
base64, bundler, css, js_parser, js_printer, parsers, resolver,
shell_parser, sourcemap). The last code-level use was the `pub type Bump
= bumpalo::Bump` alias deleted in oven-sh#34778; every remaining `bumpalo`
reference in `src/` is in a comment (verified: `rg 'bumpalo' --type rust
src/ | grep -v '//'` returns nothing).

### TaggedPointer → TaggedPtr

The long-name `TaggedPointer` alias existed in both `bun_ptr` and
`bun_collections`, both resolving to `tagged_pointer::TaggedPtr`.
Rewrote the 5 call sites to use `TaggedPtr` directly and replaced both
aliases with plain re-exports of the canonical name:
- `io/posix_event_loop.rs` (3 sites, via `bun_collections::`)
- `runtime/server/mod.rs`, `runtime/server/NodeHTTPResponse.rs` (2
sites, via `bun_ptr::`)

### Duplicate/compat aliases consolidated

- `bun_ast::ToSourceOpts` → `ToSourceOptions` (1 caller in `ini/lib.rs`)
- `bundler::options::OutputValue` → `OutputFileValue` (2 callers in
`StandaloneModuleGraph.rs`; both names aliased the same
`output_file::Value` on adjacent lines)

### Verification

- `bun bd` builds
- `bun run rust:check-all` passes on all 10 targets

Net: +11 / -39 (including Cargo.lock regen).

No test added: bumpalo was already unreferenced in code (dead dep
removal has no fail-before state); the alias rewrites are identity
substitutions to the type each alias already resolved to.
…ranch (oven-sh#34805)

Three small simplifications in `src/runtime/cli/` where an inner
condition re-checks something the enclosing branch already guarantees.
No behavior change.

### `shell_completions.rs`

`ShellCompletions::print` returns early when `commands.is_empty()`, so
at the point of the loop `commands.len() >= 1` and `&commands[1..]` is
always in bounds (an empty slice when `len() == 1`, which the `for` loop
handles). The `len() > 1` wrapper adds nothing.

### `update_interactive_command.rs`, `ensure_cursor_in_viewport`

Inside `if !state.packages.is_empty()` the length is at least 1, so
`len() - 1` cannot underflow. When `len() == 1` the expression is `0`,
which is exactly what the removed `else` branch returned.

### `update_interactive_command.rs`, `update_viewport`

The third `else if` arm is guarded by `state.viewport_height >
context_below && ...`. Neither `viewport_height` nor `context_below` is
mutated inside the arm, so re-testing `viewport_height > context_below`
before computing `desired_start` always takes the true branch. Both
subtractions remain safe: `viewport_height - context_below` is covered
by the outer guard, and `cursor - (viewport_height - context_below)` is
covered by the second conjunct (`cursor > viewport_start +
viewport_height - context_below` with `viewport_start: usize >= 0`).

### Verification

`cargo clippy -p bun_runtime` is clean and the existing `getcompletes`
and `update --interactive` snapshot tests pass unchanged with the debug
build. Because the change preserves behavior exactly, there is no input
that distinguishes before from after, so no new regression test is
added.
…nd a redundant state store (oven-sh#34796)

Three dead branches in `src/runtime/server/`, all carried over from the
Zig port.

## What

### `RequestContext::handle_resolve` (was line 742)

```rust
if ctx.is_aborted_or_ended() || ctx.did_upgrade_web_socket() {
    return;
}
if ctx.server.is_none() {            // unreachable
    ctx.render_missing_invalid_response(value);
    return;
}
```

### `RequestContext::do_sendfile` (was line 1750)

```rust
if self.is_aborted_or_ended() { return; }
if self.flags.has_sendfile_ctx() { return; }
if self.resp.is_none() || self.server.is_none() {   // unreachable
    return;
}
let global_this = self.server().global_this();
let resp = self.resp.expect("infallible: resp bound");
```

### `ServePlugins::handle_on_reject` (was line 1142)

```rust
let ServePluginsState::Pending { .. } =
    mem::replace(&mut self.state, ServePluginsState::Err)  // stores Err
else { unreachable!() };
drop(plugin);
drop(promise);
self.state = ServePluginsState::Err;   // redundant: already Err
```

## Why these are provably dead

`is_aborted_or_ended()` is:

```rust
self.resp.is_none()
    || self.flags.aborted()
    || self.server.is_none()
    || self.server().terminated()
```

so once it returns `false`, both `resp` and `server` are `Some`. Between
the guard and the removed check the only calls are
`did_upgrade_web_socket()` (pure read of `self.upgrade_context`) and
`flags.has_sendfile_ctx()` (bitflag getter via `flag_accessor!`);
neither mutates `resp`/`server` and neither yields to JS, the event
loop, or any callback that could reach `detach_response()` /
`clear_server()`. The `.expect("infallible: ...")` lines that
immediately follow already encode the same invariant and would have
panicked first had it ever been violated.

For `handle_on_reject`, `mem::replace` writes `ServePluginsState::Err`
into `self.state` and returns the old value. The intervening
`drop(plugin)` / `drop(promise)` operate on owned values moved out of
that old state (their `Drop` impls release a GC slot and free the
plugin, with no path back into `ServePlugins`). The Zig original mutated
the union in place and then assigned `.err`, which is why the second
store appeared in the port; the sibling `handle_on_resolve` uses the
same `mem::replace` pattern but reassigns to `Loaded(..)`, so only the
reject path ended up redundant.

## Verification

No observable behaviour changes, so there is nothing a regression test
can distinguish. Existing coverage that runs through these paths still
passes with the debug build:

- `test/js/bun/http/bun-serve-file.test.ts` (sendfile path): 83 pass / 0
fail
- `test/bake/serve-plugins-dev-server.test.ts`
(`handle_on_reject`/`handle_on_resolve`): 2 pass / 0 fail
- `test/js/bun/http/serve.test.ts` (`handle_resolve`): 255 pass; the 4
remaining failures reproduce identically on `main` and on the installed
release build (container networking / egress proxy, unrelated)
…ert! (oven-sh#34809)

### What

`debug_assert!(x)` expands to `if cfg!(debug_assertions) { assert!(x)
}`, so
wrapping it in another `if cfg!(debug_assertions) { ... }` is a no-op
double-gate: the inner macro already short-circuits in release, and the
outer
`if` adds nothing in debug. This PR unwraps those to a bare
`debug_assert!`.

126 sites across 69 files, net -248 lines. No behavior change in debug
or
release builds.

### Why this is correct

For `if cfg!(debug_assertions) { debug_assert!(x) }` the argument `x` is
already
type-checked in release builds with or without the outer `if` (the body
of an
`if false { ... }` is compiled, not evaluated), so dropping the outer
`if` is a
pure deletion of dead control flow. 115 of the 126 sites are this shape.

The remaining 11 are `#[cfg(debug_assertions)]` attributes directly on a
`debug_assert!`. Those *do* change whether `x` is type-checked in
release, so
only the ones whose expression references no
`#[cfg(debug_assertions)]`-gated
field or function were touched. Each was checked individually:
`posix_event_loop.rs` (`fd.native()`, `INVALID_FD`), `INotifyWatcher.rs`
(`name_len`), `Request.rs` (`size_of_url()`),
`WebSocketUpgradeClient.rs`
(`socket.is_shutdown()`), `repository.rs` (`Formatter::label`),
`pm_trusted_command.rs` (locals), `renamer.rs`
(`js_lexer::is_identifier`),
`PackageJSONEditor.rs` (`request.e_string`).

Left alone on purpose:

- `#[cfg(debug_assertions)]` attributes guarding a `debug_assert!` that
reads a
debug-only field: `HotReloadEvent::debug_mutex`,
`Ipc::has_written_version`,
`DeferredBatchTask::running`, `GlobWalker::Iterator::fds_open`. Removing
the
  attribute there would break the release build.
- `if cfg!(debug_assertions) { ... }` blocks that contain anything
besides
`debug_assert!` (loops, `let` bindings, `debug_warn!`/`scoped_log!`,
compound
  `&&` conditions, `else` branches). Those are not redundant.

Also removed one now-stale comment in `TextEncoderStreamEncoder.rs` that
claimed the outer guard was needed to keep simdutf out of release; the
inner
`debug_assert!` already guarantees that.

### Verification

- `bun bd` (debug + ASAN) builds clean.
- `cargo check --workspace --release` passes (confirms the
attribute-variant
  expressions compile without `debug_assertions`).
- `cargo check --workspace --target {x86_64-pc-windows-msvc,
aarch64-apple-darwin, x86_64-unknown-linux-gnu}`
  passes in both dev and release profiles.
- `cargo fmt --all -- --check` passes.
- `cargo clippy --workspace --no-deps` reports nothing new in the
touched files.
- Smoke-tested `test/js/bun/resolve/resolve.test.ts` and
`test/bundler/esbuild/default.test.ts` with the debug build; both pass.

This is a mechanical no-behavior-change cleanup, so there is no test
that fails
before and passes after.
…#31688)

### What

Crash reports from Rust-port builds always encode `_` ("pre-init") as
the command character — 206 of 213 crashes on 1.4.0-canary are tagged
`(pre-init)`, including crashes that are demonstrably mid-`bun install`.
On Zig builds this dimension worked (`InstallCommand`, `AutoCommand`,
…).

### Repro

```
BUN_CRASH_REPORT_URL=http://localhost:<port> BUN_ENABLE_CRASH_REPORTING=1 \
  bun test/cli/run/fixture-crash.js panic
```

stderr trace string before: `http://…/1.4.0/l_2561eb8f…` — the byte
after the platform char is `_` for every subcommand.

### Cause

The port has the storage and the reader but the setter was never ported:

- `cli_state::CMD_CHAR` (`src/crash_handler/lib.rs`) is declared with a
`cmd_char()` getter consumed by the trace-string encoder, but no
`set_cmd_char` exists and nothing in the tree stores to it.
- `bun_runtime::cli::CMD` *is* written at dispatch
(`create_context_data`, the port of Zig's `Cli.cmd = command`), but the
crash handler is a lower-tier crate and can't read it — `cli_state`
exists precisely so `bun_runtime` can mirror the value down, like the
adjacent `set_main_thread_id` already does.

### Fix

- Add `cli_state::set_cmd_char(u8)`.
- Call it from `create_context_data` with `cmd.char()` — the single
dispatch point every subcommand funnels through, matching Zig's write
site. `Tag::char()` was already ported byte-for-byte from
`Command.Tag.char()` (kept in sync with bun.report's decoder).

After: `http://…/1.4.0/la2561eb8f…` (`a` = AutoCommand); bun.report can
again pick the per-command issue template and Sentry's command facet
works for Rust builds.

Also syncs `Cargo.lock` with the `bstr` dependency added to `bun_bin` in
90f334a (lockfile wasn't regenerated in that commit).

### Verification

New tests in `test/cli/run/crash-report-command-char.test.ts` self-host
the report URL, crash under three different subcommands via the debug
crash hooks, and decode the command byte from the trace string: `bun
<file>` → `a`, `bun run <file>` → `r`, `bun test` → `t`. All three fail
with `_` before the fix and pass after.

The tests live in their own file (rather than
`run-crash-handler.test.ts`) because that file is skip-listed in
`test/expectations.txt` — its pre-existing segfault-reporter test is
broken — so anything added there is silently skipped on every CI lane.
## What

Bare `cd` (no operand) in the Bun shell was a no-op that returned
success without changing directory. It now changes to `$HOME`
(`$USERPROFILE` on Windows), matching POSIX and the file's own header
comment.

When `$HOME` is unset or empty, `cd` now prints `cd: HOME not set` to
stderr with exit code 1, matching bash.

## Repro

```js
import { $ } from "bun";
// run from a directory other than $HOME
console.log(await $`cd && pwd`.text());
```

Before: prints the current working directory.
After: prints `$HOME`.

## Cause

`src/runtime/shell/builtin/cd.rs` only handled the `args.len() == 1`
case; with zero args it fell straight through to `Builtin::done(interp,
cmd, 0)`.

## Fix

Handle the zero-arg case by looking up the home directory via
`ShellExecEnv::get_homedir()` (the same helper `~` expansion uses) and
calling `change_cwd()` with it. Empty result means
`$HOME`/`$USERPROFILE` is unset, which is an error.

## Verification

```
bun bd test test/js/bun/shell/bunshell.test.ts -t "cd with no args"
```

Both new tests fail on the released bun and pass with this change.

<!-- 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/js/bun/shell/bunshell.test.ts

<!-- robobun:evidence:end -->
robobun and others added 29 commits July 27, 2026 01:27
…ing patterns (oven-sh#35970)

## Problem

Parser diagnostics that use `Source::range_of_operator_before` pointed
at the wrong column.

```
$ bun build -e '((...a = 1) => {})'
1 | ((...a = 1) => {})
                    ^
error: A rest argument cannot have a default initializer
    at <stdin>:1:17
```

The caret should point at the `=` (column 8). esbuild reports column 7
(0-indexed) for the same input.

With a preceding `=` it gets worse, since the first match in the file is
used rather than the last one before the initializer:

```
$ bun build -e 'a;b;(([]) = []) => {}'
1 | a;b;(([]) = []) => {}
              ^
error: Unexpected parentheses in binding pattern
    at <stdin>:1:11
```

The caret should point at the inner `(` (column 6).

## Cause

`Source::range_of_operator_before` in `src/ast/lib.rs` diverged from
esbuild's
[`RangeOfOperatorBefore`](https://github.com/evanw/esbuild/blob/main/internal/logger/logger.go)
in two ways:

1. It called `strings::index` (first match) instead of a last-index
search, so it found the first occurrence of the operator in the file
rather than the one immediately preceding the target location.
2. The search slice is `&self.contents[0..loc.i()]`, so the returned
index is already absolute; adding `loc.start` to it doubled the offset.

## Fix

Use `bun_core::strings::last_index_of` and return the index directly as
the absolute location (via the existing `usize2loc` helper), matching
esbuild.

This was the last caller of `bun_core::strings::index` (the
`i32`/`-1`-sentinel wrapper over `index_of`), so that helper is removed
as well.

After:

```
1 | ((...a = 1) => {})
           ^
error: A rest argument cannot have a default initializer
    at <stdin>:1:8

1 | a;b;(([]) = []) => {}
         ^
error: Unexpected parentheses in binding pattern
    at <stdin>:1:6
```

## Tests

Added position assertions in
`test/bundler/transpiler/transpiler.test.js` covering all three call
sites (`=` before rest initializer, `(` before parenthesized array
binding, `(` before parenthesized object binding).

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

---

**[stamp-90s]** gate passed · iteration 0 · 3 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 1 failed, 22 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bundler/transpiler/transpiler.test.js
bun test v1.4.0 (74ceb90)

test/bundler/transpiler/transpiler.test.js:
(pass) Bun.Transpiler > handles errors when parsing macros [7.57ms]
(pass) Bun.Transpiler > normalizes \r\n [6.06ms]
1
(pass) Bun.Transpiler > doesn't hang indefinitely oven-sh#2746 [4.04ms]
(pass) Bun.Transpiler > property access inlining > bails out with spread [7.68ms]
(pass) Bun.Transpiler > property access inlining > bails out with multiple items [3.16ms]
(pass) Bun.Transpiler > property access inlining > works [3.31ms]
(pass) Bun.Transpiler > property access inlining > works nested [2.61ms]
(pass) Bun.Transpiler > property access inlining > bails out on optional-chain index into enum [20.38ms]
(pass) Bun.Transpiler > TypeScript > import Foo = Baz.Bar [2.93ms]
(pass) Bun.Transpiler > TypeScript > ternary should parse correctly when parsing typescript fails [2.39ms]
(pass) Bun.Transpiler > TypeScript > reports Expected ":" for a conditional expression missing its colon [8.50ms]
(pass) Bun.Transpiler > TypeScript > contextual
... (truncated)

release without fix: 15 failed, 22 skipped
bun test v1.4.0-canary.1 (1498d7b)

test/bundler/transpiler/transpiler.test.js:
(pass) Bun.Transpiler > handles errors when parsing macros [0.14ms]
(pass) Bun.Transpiler > normalizes \r\n [0.22ms]
1
(pass) Bun.Transpiler > doesn't hang indefinitely oven-sh#2746 [0.12ms]
(pass) Bun.Transpiler > property access inlining > bails out with spread [0.24ms]
(pass) Bun.Transpiler > property access inlining > bails out with multiple items [0.05ms]
(pass) Bun.Transpiler > property access inlining > works [0.04ms]
(pass) Bun.Transpiler > property access inlining > works nested [0.04ms]
141 |     });
142 |     it("bails out on optional-chain index into enum", () => {
143 |       const pre = "enum Foo { A }\nenum Bar { 'a-b' = 1 }\n";
144 |       const lastLine = out => out.trimEnd().split("\n").at(-1);
145 |       expect(lastLine(ts.parsed(pre + 'export let y = Foo["A"];', false))).toBe("export let y = 0 /* A */;");
146 |       expect(lastLine(ts.parsed(pre + 'export let y = Foo?.["A"];', false))).toBe('export let y = Foo?.["A"];');
                                                                                   ^
error: expect(received).toBe(expected)

Expected: "export let y = F
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 22 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bundler/transpiler/transpiler.test.js
bun test v1.4.0 (74ceb90)

test/bundler/transpiler/transpiler.test.js:
(pass) Bun.Transpiler > handles errors when parsing macros [10.98ms]
(pass) Bun.Transpiler > normalizes \r\n [12.56ms]
1
(pass) Bun.Transpiler > doesn't hang indefinitely oven-sh#2746 [7.86ms]
(pass) Bun.Transpiler > property access inlining > bails out with spread [16.07ms]
(pass) Bun.Transpiler > property access inlining > bails out with multiple items [2.98ms]
(pass) Bun.Transpiler > property access inlining > works [2.79ms]
(pass) Bun.Transpiler > property access inlining > works nested [2.84ms]
(pass) Bun.Transpiler > property access inlining > bails out on optional-chain index into enum [24.25ms]
(pass) Bun.Transpiler > TypeScript > import Foo = Baz.Bar [5.04ms]
(pass) Bun.Transpiler > TypeScript > ternary should parse correctly when parsing typescript fails [4.14ms]
(pass) Bun.Transpiler > TypeScript > reports Expected ":" for a conditional expression missing its colon [13.62ms]
(pass) Bun.Transpiler > TypeScript > contex
... (truncated)

release with fix: 22 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 1117ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[0/4] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m    Blocking�[0m waiting for file lock on build directory
�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp)
�[1m�[92m   Compiling�[0m bun_output v0.0.0 (/workspace/bun/src/output)
�[1m�[92m   Compiling�[0m bun_clap v0.0
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/ast/lib.rs                             |  7 ++-----
 src/bun_core/string/immutable.rs           |  7 -------
 test/bundler/transpiler/transpiler.test.js | 29 +++++++++++++++++++++++++++++
 3 files changed, 31 insertions(+), 12 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                                        reads  edits  tests
src/ast/lib.rs                                  2      2      0
src/bun_core/string/immutable.rs                2      2      0
test/bundler/transpiler/transpiler.test.js      4      3      0
```

</details>

**root cause** · written by the author bot

`Source::range_of_operator_before` computed the wrong location because
it searched for the first occurrence of the operator instead of the last
and then added `loc.start` to an index that was already absolute,
effectively doubling the offset. This caused parser diagnostics such as
"A rest argument cannot have a default initializer" to point at the
wrong column or the wrong operator entirely. The fix switches to a
last-index search and uses the returned offset directly, matching
esbuild's `RangeOfOperatorBefore` semantics.

<!-- robobun:evidence:end -->
…ttp (oven-sh#35978)

Net -488 lines across 21 source files. Each item was verified to have
zero callers/constructors via `rg -w` across `src/` and
`build/debug/codegen/` before deletion.

## `js_printer::Format::Cjs` / `CjsAscii` chain and the
`REWRITE_ESM_TO_CJS` axis (~300 LOC)

`Format` is constructed at exactly 7 sites (transpiler.rs, jsc_hooks.rs,
RuntimeTranspilerStore.rs, AsyncModule.rs, JSTranspiler.rs), all of
which pass `Esm` or `EsmAscii`. The enum has no `repr`/serde/bytemuck so
it cannot arrive from an integer. With `Cjs`/`CjsAscii` gone:

- `fn print_cjs_cold` (bundler/transpiler.rs) becomes unreachable: only
caller was the `Format::Cjs` match arm.
- `pub fn print_common_js` (js_printer/lib.rs) becomes unreachable: only
caller was `print_cjs_cold`.
- `print_common_js` was the only `Printer<_, _, _, true, ...>`
instantiation, so the `REWRITE_ESM_TO_CJS` const-generic axis is dead:
dropped the parameter from the struct and impl, removed
`print_bundled_export` and `print_module_export_symbol` (only called
inside `if REWRITE_ESM_TO_CJS { }` guards), and unwrapped/deleted the
~10 guarded branches.
- `impl PrintArg for u16` has no callers (every `.print(x)` passes `u8`
or `&[u8]`).

## `OutputFile::Value::Move` / `Value::Pending` (~65 LOC)

`Value` is constructed only in `OutputFile::init` (Buffer/Copy/Saved)
and `transpiler.rs:build_static_file` (Copy). `Move` and `Pending` are
only matched, never constructed. With them gone:

- `OutputFile::move_to` becomes unreachable (only called from the `Move`
arm).
- `FileOperation::get_pathname` becomes unreachable (only called from
`move_to`).
- `pub enum Kind` + `Value::kind()` become unreachable (only used in a
`todo_panic!` format string).
- The manual `impl Clone for Value` existed only because `Pending`'s
payload wasn't `Clone`; replaced with `#[derive(Clone)]`.
- `OptionsData::File` is never constructed (only `Buffer`/`Saved` are),
which made `FileOperation::from_file`, `FileOperation.fd`, and
`FileOperation.dir` dead; `FileOperation` is now `{ pathname: Box<[u8]>
}`.

## Other removed items

- `js_parser/parse/parse_entry.rs`: 58-line `else if p.options.bundle &&
parts.is_empty() { if false { ... } }` arm already commented
"permanently disabled"; with no trailing `else` the whole arm is a
no-op.
- `task_tag::ShellIOWriter`: doc comment on
`IOWriter::run_from_main_thread` said "No code path enqueues this tag";
confirmed no producer.
- `LsParseError::ShowUsage`: `ls::parse_opts` only returns `Ok` or
`Err(IllegalOption)`.
- `Stage::Connect` (`http::InternalState`): only `Pending`/`Done`/`Fail`
are ever assigned.
- `git_diff_preprocess_paths::<SENTINEL>`: both call sites pass
`<false>`; dropped the const-generic and its branches.
- Unused `pub use` re-exports: `h2::LIVE_SESSIONS`,
`ssl_config::GlobalRegistry`, `install::CacheDirAndSubpath`,
`dev_server::PackedMap`, `valkey_jsc::ValkeyContext`.
- Stale `print_common_js` mentions scrubbed from renamer.rs / Chunk.rs /
VirtualMachine.rs comments.

## Verification

- `bun bd` builds.
- `bun run rust:check-all`: 10/10 targets pass.
- `bun bd test test/bundler/transpiler/transpiler.test.js`: 182 pass.
- `bun bd test test/cli/install/bun-patch.test.ts`: 29 pass.
- `bun bd test test/js/node/worker_threads/worker_threads.test.ts`: 91
pass.
-
`test/internal/source-lints/dead-symbols-printer-bundler-shell.test.ts`
asserts none of these symbols reappear.

## Not removed (flagged for followup)

- `RedisError::{InvalidArray, InvalidSimpleString, InvalidErrorString,
InvalidNull, InvalidArgument, JSError, JSTerminated}` appear
unconstructed, but the enum derives `strum::EnumString` so they could in
principle arrive via `FromStr`; left alone.
- `rm::PromptBehaviour` is write-only (only checked against `Never`) but
represents planned `-i`/`-I` support; left alone.
- `Ast.runtime_imports` (src/ast/ast_result.rs:26) became write-only
after 8761a43 removed its two `.clone()` readers in transpiler.rs.
Removing it cascades into `bun_ast` and `bun_js_parser` (p.rs:8378/:8393
and the associated comment); deferred to keep this PR's crate footprint
bounded.

## Scanned areas with nothing confidently dead

`src/sql`, `src/runtime/crypto`, `src/threading`, `src/valkey`,
`src/uws`, `src/runtime/server` were scanned and found clean (every pub
item has at least one caller). These were already swept by oven-sh#35002.

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

---

**[review]** gate passed · iteration 1 · 24 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 3 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/internal/source-lints/dead-symbols-printer-bundler-shell.test.ts
bun test v1.4.0 (c5288fe)

test/internal/source-lints/dead-symbols-printer-bundler-shell.test.ts:
26 |     ["src/js_printer/lib.rs", /fn print_module_export_symbol\b/],
27 |     ["src/bundler/transpiler.rs", /fn print_cjs_cold\b/],
28 |     ["src/bundler/transpiler.rs", /Format::CjsAscii => unreachable/],
29 |   ];
30 |   const resurrected = checks.filter(([file, re]) => re.test(src(file))).map(([file, re]) => `${file}: ${re.source}`);
31 |   expect(resurrected).toEqual([]);
                           ^
error: expect(received).toEqual(expected)

- []
+ [
+   "src/js_printer/lib.rs: ^\s*Cjs,$",
+   "src/js_printer/lib.rs: ^\s*CjsAscii,$",
+   "src/js_printer/lib.rs: pub fn print_common_js\b",
+   "src/js_printer/lib.rs: impl PrintArg for u16\b",
+   "src/js_printer/lib.rs: REWRITE_ESM_TO_CJS",
+   "src/js_printer/lib.rs: fn print_bundled_export\b",
+   "src/js_printer/lib.rs: fn print_module_export_symbol\b",
+   "src/bundler/transpiler.rs: fn print_cjs_cold\b",
+  
... (truncated)

release without fix: 3 FAILED
bun test v1.4.0-canary.1 (924ef25)

test/internal/source-lints/dead-symbols-printer-bundler-shell.test.ts:
26 |     ["src/js_printer/lib.rs", /fn print_module_export_symbol\b/],
27 |     ["src/bundler/transpiler.rs", /fn print_cjs_cold\b/],
28 |     ["src/bundler/transpiler.rs", /Format::CjsAscii => unreachable/],
29 |   ];
30 |   const resurrected = checks.filter(([file, re]) => re.test(src(file))).map(([file, re]) => `${file}: ${re.source}`);
31 |   expect(resurrected).toEqual([]);
                           ^
error: expect(received).toEqual(expected)

- []
+ [
+   "src/js_printer/lib.rs: ^\s*Cjs,$",
+   "src/js_printer/lib.rs: ^\s*CjsAscii,$",
+   "src/js_printer/lib.rs: pub fn print_common_js\b",
+   "src/js_printer/lib.rs: impl PrintArg for u16\b",
+   "src/js_printer/lib.rs: REWRITE_ESM_TO_CJS",
+   "src/js_printer/lib.rs: fn print_bundled_export\b",
+   "src/js_printer/lib.rs: fn print_module_export_symbol\b",
+   "src/bundler/transpiler.rs: fn print_cjs_cold\b",
+   "src/bundler/transpiler.rs: Format::CjsAscii => unreachable",
+ ]

- Expected  - 1
+ Received  + 11

      at <anonymous> (/workspace/bun/test/internal/source-lints/dead-symbols-printer-bundler
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/internal/source-lints/dead-symbols-printer-bundler-shell.test.ts
bun test v1.4.0 (c5288fe)

test/internal/source-lints/dead-symbols-printer-bundler-shell.test.ts:
(pass) dead js_printer Format::Cjs chain does not reappear [44.96ms]
(pass) dead OutputFile::Value variants do not reappear [13.62ms]
(pass) dead shell / http / patch items do not reappear [27.42ms]

 3 pass
 0 fail
 3 expect() calls
Ran 3 tests across 1 file. [2.54s]
__F:0:S:0

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 860ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/7] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[2/7] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[2/7] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/bundler/OutputFile.rs                          | 121 +--------
 src/bundler/transpiler.rs                          |  87 +------
 src/event_loop/ConcurrentTask.rs                   |   1 -
 src/http/H2Client.rs                               |   5 +-
 src/http/HTTPThread.rs                             |   4 +-
 src/http/InternalState.rs                          |   1 -
 src/http/ssl_config.rs                             |   2 -
 src/install/PackageManager/patchPackage.rs         |   2 +-
 src/install/lib.rs                                 |   1 -
 src/js_parser/parse/parse_entry.rs                 |  58 -----
 src/js_printer/lib.rs                              | 278 ++-------------------
 src/js_printer/renamer.rs                          |   2 +-
 src/jsc/VirtualMachine.rs                          |   2 +-
 src/patch/lib.rs                                   |  41 +--
 src/runtime/api/output_file_jsc.rs                 |  33 +--
 src/runtime/bake/dev_server/mod.rs                 |   1 -
 src/runtime/dispatch.rs                            |   8 +-
 src/runtime/shell/IOWriter.rs                      |   7 -
 src/runtime/shell/builtin/ls.rs                    |  35 +--
 src/runtime/valkey_jsc/mod.rs                      |   9 -
 src/runtime/valkey_jsc/valkey.rs                   |   2 -
 src/runtime/webcore/fetch.rs                       |   2 +-
 src/sourcemap/Chunk.rs                             |  10 +-
 .../dead-symbols-printer-bundler-shell.test.ts     |  68 +++++
 24 files changed, 140 insertions(+), 640 deletions(-)
```

</details>

**gate history** · 9 passed · 0 rejected · iteration 1

<details><summary>evidence per changed file</summary>

```
file                                        reads  edits  tests
src/bundler/OutputFile.rs                       6      5      0
src/bundler/transpiler.rs                       5      5      0
src/event_loop/ConcurrentTask.rs                1      1      0
src/http/H2Client.rs                            2      2      0
src/http/HTTPThread.rs                          1      1      0
src/http/InternalState.rs                       1      1      0
src/http/ssl_config.rs                          1      1      0
src/install/PackageManager/patchPackage.rs      1      1      0
src/install/lib.rs                              1      1      0
src/js_parser/parse/parse_entry.rs              2      2      0
src/js_printer/lib.rs                           8      6      0
src/js_printer/renamer.rs                       2      3      0
src/jsc/VirtualMachine.rs                       1      1      0
src/patch/lib.rs                                2      3      0
src/runtime/api/output_file_jsc.rs              3      3      0
src/runtime/bake/dev_server/mod.rs              1      1      0
(+ 8 more files)
```

</details>

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

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
…jecting as trailing junk (oven-sh#36021)

## Repro

```js
import zlib from "node:zlib";
const f1 = zlib.zstdCompressSync(Buffer.from("first frame\n"));
const f2 = zlib.zstdCompressSync(Buffer.from("second frame\n"));
const cat = Buffer.concat([f1, f2]);            // valid 2-frame stream (cat a.zst b.zst / pzstd)

await new Response(new Blob([cat]).stream()
  .pipeThrough(new DecompressionStream("zstd"))).text();
// TypeError: Trailing junk found after the end of the compressed stream
//   code: "ERR_TRAILING_JUNK_AFTER_STREAM_END"

Bun.zstdDecompressSync(cat);  // "first frame\nsecond frame\n" (correct)
```

A zstd stream is one or more concatenated frames (RFC 8878 section 3.1);
`zstd -d`, pzstd output (multi-frame by construction),
`Bun.zstdDecompressSync`, and the `fetch()` `Content-Encoding: zstd`
decoder all decode every frame. Only `DecompressionStream("zstd")`
rejects the second frame as trailing junk, so a real pzstd file is
unreadable through it while every other zstd decoder in the process
accepts it. A leading skippable frame (magic `0x184D2A50..5F`) is
rejected the same way.

## Cause

The native zstd `do_work()` calls `ZSTD_decompressStream` once per
write; libzstd stops at every frame boundary (returns 0 with the next
frame unconsumed), so `processCallback` sees `availInAfter > 0` with
output room and, because `DecompressionStream` passes
`rejectGarbageAfterEnd: true`, raises
`ERR_TRAILING_JUNK_AFTER_STREAM_END`. `Gunzip` avoids this because
`NativeZlib::do_work_inflate` already loops on multi-member input.

## Fix

In `NativeZstd::do_work`, after `ZSTD_decompressStream` returns 0 with
input and output room remaining, peek the next four bytes: if they are
the frame magic `0xFD2FB528` or a skippable-frame magic `0x184D2A5?` (or
a prefix of either when fewer than four remain, so a header split across
chunks decodes), call `ZSTD_decompressStream` again. libzstd resets the
DCtx to start-of-frame itself, so no explicit reset is needed. Bytes
that are not a magic or magic prefix are left unconsumed so the existing
`ERR_TRAILING_JUNK_AFTER_STREAM_END` check still fires for genuine
garbage, and `createZstdDecompress` still silently ignores trailing
non-frame data the way Node.js does.

`src/js/node/zlib.ts` is unchanged.

## Verification

New tests in `test/js/web/streams/compression.test.ts` cover a 2-frame
stream written as one chunk, a 2-frame stream split mid-header across
two writes, 64 frames totalling more than one output chunk, a stream
with leading and trailing skippable frames, and trailing non-frame
garbage still rejected with `ERR_TRAILING_JUNK_AFTER_STREAM_END`. The
four multi-frame tests fail on `main` with that error and pass with this
change; the Node-compat `createZstdDecompress` trailing-data tests in
`test/js/node/zlib/zlib.test.js` still pass.

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

---

**[review]** gate passed · iteration 2 · 3 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 6 failed, 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/zlib/zlib.test.js test/js/web/streams/compression.test.ts
bun test v1.4.0 (f5a1ac9)

test/js/web/streams/compression.test.ts:
(pass) CompressionStream and DecompressionStream > brotli > compresses data with brotli [302.30ms]
(pass) CompressionStream and DecompressionStream > brotli > decompresses brotli data [113.72ms]
(pass) CompressionStream and DecompressionStream > brotli > round-trip compression with brotli [341.86ms]
(pass) CompressionStream and DecompressionStream > zstd > compresses data with zstd [35.81ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses zstd data [58.35ms]
(pass) CompressionStream and DecompressionStream > zstd > round-trip compression with zstd [223.26ms]
TypeError: Trailing junk found after the end of the compressed stream
 code: "ERR_TRAILING_JUNK_AFTER_STREAM_END"

      at unknown:1:1
      at processCallback (node:zlib:431:37)
(fail) CompressionStream and DecompressionStream > zstd > decompresses a multi-frame zstd stream [45.46ms]
TypeError: Trailing junk found afte
... (truncated)

release without fix: 2 skipped
bun test v1.4.0-canary.1 (f62fd6a)

test/js/web/streams/compression.test.ts:
(pass) CompressionStream and DecompressionStream > brotli > compresses data with brotli [5.42ms]
(pass) CompressionStream and DecompressionStream > brotli > decompresses brotli data [2.23ms]
(pass) CompressionStream and DecompressionStream > brotli > round-trip compression with brotli [6.12ms]
(pass) CompressionStream and DecompressionStream > zstd > compresses data with zstd [2.48ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses zstd data [1.10ms]
(pass) CompressionStream and DecompressionStream > zstd > round-trip compression with zstd [4.71ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses a multi-frame zstd stream [0.51ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses a multi-frame zstd stream split across writes (next = zstd frame) [1.23ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses a multi-frame zstd stream split across writes (next = skippable frame) [2.40ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses many concatenated zstd frames larger than one output 
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/zlib/zlib.test.js test/js/web/streams/compression.test.ts
bun test v1.4.0 (f5a1ac9)

test/js/web/streams/compression.test.ts:
(pass) CompressionStream and DecompressionStream > brotli > compresses data with brotli [377.58ms]
(pass) CompressionStream and DecompressionStream > brotli > decompresses brotli data [115.46ms]
(pass) CompressionStream and DecompressionStream > brotli > round-trip compression with brotli [324.69ms]
(pass) CompressionStream and DecompressionStream > zstd > compresses data with zstd [44.76ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses zstd data [62.49ms]
(pass) CompressionStream and DecompressionStream > zstd > round-trip compression with zstd [186.59ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses a multi-frame zstd stream [22.91ms]
(pass) CompressionStream and DecompressionStream > zstd > decompresses a multi-frame zstd stream split across writes (next = zstd frame) [64.47ms]
(pass) CompressionStream and DecompressionStream > zstd > decompress
... (truncated)

release with fix: 2 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 766ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/6] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[1/6] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp)
�[1m�[92m   Compiling�[0m bun_output v
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/runtime/node/zlib/NativeZstd.rs     | 56 +++++++++++++++++++++----
 test/js/node/zlib/zlib.test.js          |  6 +++
 test/js/web/streams/compression.test.ts | 73 +++++++++++++++++++++++++++++++++
 3 files changed, 127 insertions(+), 8 deletions(-)
```

</details>

**gate history** · 4 passed · 0 rejected · iteration 2

<details><summary>evidence per changed file</summary>

```
file                                     reads  edits  tests
src/runtime/node/zlib/NativeZstd.rs          6      8      0
test/js/node/zlib/zlib.test.js               2      1      0
test/js/web/streams/compression.test.ts      6      8      0
```

</details>

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

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…h#36072)

Main fails to build on all lanes since bfd1e92 (Buildkite main
#83211, #83215).

## Cause

oven-sh#36067 renamed `AnyResponse::resume_` to `AnyResponse::resume` in
`src/uws_sys/Response.rs`. oven-sh#36006, merged just before it, added six new
callers of the old name. Both passed CI on their own branches; combined
on main:

```
error[E0599]: no method named `resume_` found for enum `AnyResponse` in the current scope
    --> src/runtime/server/RequestContext.rs:2382:22
    --> src/runtime/server/RequestContext.rs:4126:18
    --> src/runtime/server/RequestContext.rs:4182:22
    --> src/runtime/webcore/streams.rs:1408:25
    --> src/runtime/webcore/streams.rs:1785:17
    --> src/runtime/webcore/streams.rs:1873:21
```

## Fix

Rename the six call sites to `resume()`.

## Verification

- `cargo check -p bun_runtime` on main: 6× E0599; with this change:
clean.
- `bun bd` builds.
- `bun bd test test/js/bun/http/serve.test.ts -t 'request body
backpressure'`: 5/5 pass (the tests oven-sh#36006 added that exercise these
call sites).

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

---

**no test proof** · iteration 1 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/bun/http/serve.test.ts

<!-- robobun:evidence:end -->
…6073)

## What

Adds `src/runtime/node/node_fs.rs: 2` to the dead-code escape inventory
so the `dead-code-escapes` source-lint passes again on main.

## Why

oven-sh#36067 (bfd1e92) renamed `_cp_symlink` → `cp_symlink` and
`_cp_open_dest_with_mkdir` → `cp_open_dest_with_mkdir`, moving the
dead-code suppression from the leading underscore (which the inventory
regex does not match) to explicit `#[cfg_attr(..., allow(dead_code))]`
attributes:

```rust
#[cfg_attr(any(windows, target_os = "macos"), allow(dead_code))]
fn cp_symlink(&mut self, ...) { ... }

#[cfg_attr(windows, allow(dead_code))]
fn cp_open_dest_with_mkdir(&mut self, ...) { ... }
```

Both functions are called from the Linux/FreeBSD arms of
`copy_single_file_sync` (lines 8613, 8680, 8706, 8852, 8878) and are
only dead on the platforms named in the predicate, so the escapes are
legitimate per the test's own rules. The inventory file was simply not
regenerated, and the GitHub Actions `source-lints` workflow has been
failing on every main commit since:

```
(fail) #[allow(dead_code)] escapes > src/runtime/node/node_fs.rs (0)
error: src/runtime/node/node_fs.rs has 2 item-level #[allow(dead_code)] escapes, up from 0.
```

Failed runs: 30249533282 (bfd1e92), 30249969141, 30250537591,
30250867335.

## How

Regenerated with `bun
./test/internal/source-lints/dead-code-escapes.test.ts` per the test's
instructions.

## Verification

```
$ bun test test/internal/source-lints/dead-code-escapes.test.ts
...
(pass) #[allow(dead_code)] escapes > src/runtime/node/node_fs.rs (2)
...
 26 pass
 0 fail
```

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

---

**no test proof** · iteration 0 · docs-only change; test-proof not
applicable

<!-- robobun:evidence:end -->
…36101)

### What does this PR do?

The embedded builtin-module source blob (`bun_internal_modules_data`) is
one contiguous ~2.6 MB string with per-module offsets. Modules were
concatenated in registry (sorted path) order, so a `require`'s module
and its transitive dependencies sat on pages scattered across the whole
blob, and a cold start faulted all over it.

This concatenates them in **DFS post-order over the static require
graph** instead, so each module lands contiguous with its dependencies
and loading a builtin reads one contiguous run of pages. The graph is
built from the `internalModuleRegistry, N` lookups already present in
the bundled output; a fixed list of popular entry modules seeds the
traversal so the layout is deterministic. It stays a single blob with
per-module offsets — only the byte order changes, and offsets are still
emitted per module *name* (`<Enum>CodeOffset`), so ids and lookups are
untouched.

**Measured** (Linux x64 release, cold page cache, kernel readahead at
default 128 KB, `.rodata` residency via `mincore` after the process
exits):

| workload | before | after |
|---|---|---|
| `require("node:fs")` | 6.23 MB | 5.71 MB (−8%) |
| `require("node:http")` | 7.27 MB | 6.78 MB (−7%) |

With readahead disabled (true touched set) both are unchanged (~1.6 /
2.4 MB), as expected — the same bytes are read, they're just adjacent
now, so readahead pulls in useful neighbors instead of cold ones.
Modest, but free: zero runtime cost and no format change.

### How did you verify your code works?

- Built release and checked the generated
`InternalModuleRegistryConstants.h`: the physical order is now
dependencies-before-dependents (`InternalPrimordials` first,
`InternalUrl`→`NodeUrl`, `InternalUtilInspect` before `NodeUtil`, the fs
subtree clustered), and every module appears exactly once.
- Ran `bun -e` / `require()` of several builtins on the rebuilt binary;
behavior unchanged (the blob is only reordered).
- Residency numbers above measured with a `mincore` probe from a clean
cwd on a real filesystem (tmpfs paths can't be evicted and would fake
the "before").
## Problem

When `bun` on PATH resolves into the build directory (e.g.
`build/release` is first on PATH, so `process.execPath ==
/path/to/build/release/bun`), `cfg.jsRuntime` gets baked into the
`smoke_test` and `dsymutil` ninja rule commands as the stream.ts
wrapper. But those build edges only declare `bun-profile` as an input,
not the stripped `bun`, so ninja is free to run strip and the wrapper
concurrently (both depend only on the link output). The wrapper then
execs `build/release/bun` while strip is writing it:

```
/bin/sh: 1: /workspace/bun/build/release/bun: Permission denied
```

Generated ninja before this change:
```ninja
rule smoke_test
  command = /workspace/bun/build/release/bun .../stream.ts check --console sh -c '...'
build bun-profile.smoke-test-passed: smoke_test bun-profile
build bun: strip bun-profile
default bun check
```

## Fix

Extract an `emitPostLink()` helper that owns the strip / dsymutil /
`bun` phony / smoke-test sequence for every linking mode (full,
link-only, rust-and-link), and have it add the stripped exe as an
order-only input to the `smoke_test` and `dsymutil` edges. After:

```ninja
build bun-profile.smoke-test-passed: smoke_test bun-profile || bun
```

Ninja now serializes strip before those edges; the wrapper never sees a
half-written file. Order-only (not implicit) because the edges don't
read the stripped binary's content, they only need it to not be
mid-write. Debug builds (no strip) are unchanged.

The sequence was previously open-coded in all three modes; oven-sh#30539's
partial fix missed `emitRustAndLink`. Folding it into one helper means
any future mode gets the ordering for free. The refactor produces
byte-identical `build.ninja` output for every profile.

## Why this is the right fix

Refusing a `jsRuntime` inside `buildDir` at configure time would break
any environment where the only `bun` is the build output (no
`~/.bun/bin/bun`, `build/release` on PATH). Dropping the stream.ts
wrapper would lose the Windows console buffering compensation. Declaring
the actual dependency is the ninja-correct model and costs ~1s of
serialization on release builds.

## Verification

```
$ ninja -C build/release -t query bun
bun:
  input: strip
    bun-profile
  outputs:
    bun-profile.smoke-test-passed
```

New `test/internal/build-post-link-ordering.test.ts` asserts the edge
shape through `emitPostLink` for release (order-only dep present), debug
(absent, `bun` phony instead), and darwin-target configs (dsymutil
ordered too).

Note: the fix is in `scripts/`, not `src/`, so the automated fail-before
check (which stashes `src/ packages/` only) cannot revert it; the
before/after ninja graph above is the proof.

## Related

oven-sh#30539 carries a partial version of this fix (smoke_test only, two of
three call sites) bundled with an unrelated bundler change; this
standalone PR supersedes that portion so it can land independently.

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

---

**no test proof** · iteration 0 · Platform-specific test-only change;
deferring to CI.

<!-- robobun:evidence:end -->
Implements the
[`textStream()`](https://fetch.spec.whatwg.org/#dom-body-textstream)
method on the Body mixin (Request and Response), returning a
`ReadableStream<string>` of the body decoded as UTF-8 text.

## Approach

Rather than materializing a byte `ReadableStream` and piping it through
a `TextDecoderStream`, each body backing decodes directly:

- **In-memory bodies** (string, bytes, Blob-with-bytes) decode once and
enqueue a single string chunk into a closed stream
(`ReadableStream__fromDecodedText`).
- **Native byte sources** (fetch response `ByteStream`, file loader) run
in a text-mode `JSNativeStreamSourceAdapter` that UTF-8-decodes each
pulled span before enqueueing. The streaming-decode state (3 held-back
bytes + BOM-seen) lives inline on the adapter; no extra GC cells.
- **Bodies that already have a materialized byte stream** (user-provided
`ReadableStream`, or `.body` was accessed first) use a new
`SourceKind::TextDecode` whose pull issues a
`ReadRequestKind::TextDecode` read on the source reader; chunk steps
decode and enqueue strings. The decode state is a 4-byte `Uint8Array`
stored in the controller's existing `underlyingObject` slot.

`streamingUTF8Decode` (WebStreamsMisc.cpp) joins held-back bytes from a
previous chunk, strips a single leading BOM per stream, holds back a
trailing incomplete sequence, and decodes via
`WTF::String::fromUTF8ReplacingInvalidSequences`. Held-back bytes are
always `[lead(>=0xC0), cont*(0x80..0xBF)]` so the length is derived from
the first zero byte.

## Verification

```
$ bun bd test test/js/web/fetch/body.test.ts -t textStream
56 pass, 0 fail
```

Covers: string/buffer/null/undefined bodies, user ReadableStream bodies,
multi-byte characters split across chunks, leading BOM stripping,
invalid-sequence replacement, fetch response bodies (native ByteStream
path), body-unusable/locked error handling, error propagation, cancel
propagation, Content-Type charset is ignored.

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

---

**[review]** gate passed · iteration 14 · 20 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 94 failed, 4 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/fetch/body.test.ts test/js/web/fetch/wpt/textstream-wpt.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (6b1404c)

test/js/web/fetch/body.test.ts:
(pass) Request > constructor > undefined [4.97ms]
(pass) Request > constructor > null [3.59ms]
(pass) Request > constructor > string > "" [6.00ms]
(pass) Request > constructor > string > "Hello world" [1.97ms]
(pass) Request > constructor > string > "🫠" [1.55ms]
(pass) Request > constructor > string > "⁉️" [1.27ms]
(pass) Request > constructor > ArrayBuffer > empty buffer [8.73ms]
(pass) Request > constructor > ArrayBuffer > small buffer [3.63ms]
(pass) Request > constructor > ArrayBuffer > large buffer [4.60ms]
(pass) Request > constructor > SharedArrayBuffer > empty buffer [1.85ms]
(pass) Request > constructor > SharedArrayBuffer > small b
... (truncated)

release without fix: 4 skipped
bun test v1.4.0-canary.1 (4045358)

test/js/web/fetch/body.test.ts:
(pass) Request > constructor > undefined [0.07ms]
(pass) Request > constructor > null [0.03ms]
(pass) Request > constructor > string > "" [0.12ms]
(pass) Request > constructor > string > "Hello world" [0.01ms]
(pass) Request > constructor > string > "🫠" [0.01ms]
(pass) Request > constructor > string > "⁉️"
(pass) Request > constructor > ArrayBuffer > empty buffer [0.11ms]
(pass) Request > constructor > ArrayBuffer > small buffer [0.08ms]
(pass) Request > constructor > ArrayBuffer > large buffer [1.72ms]
(pass) Request > constructor > SharedArrayBuffer > empty buffer [0.03ms]
(pass) Request > constructor > SharedArrayBuffer > small buffer [0.03ms]
(pass) Request > constructor > SharedArrayBuffer > large buffer [1.95ms]
(pass) Request > constructor > Buffer > empty buffer [0.02ms]
(pass) Request > constructor > Buffer > small buffer [0.01ms]
(pass) Request > constructor > Buffer > large buffer [1.59ms]
(pass) Request > constructor > Uint8Array > empty buffer [0.01ms]
(pass) Request > constructor > Uint8Array > small buffer [0.03ms]
(pass) Request > constructor > Uint8Array > large buffer [1.4
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 4 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/fetch/body.test.ts test/js/web/fetch/wpt/textstream-wpt.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (6b1404c)

test/js/web/fetch/body.test.ts:
(pass) Request > constructor > undefined [5.01ms]
(pass) Request > constructor > null [3.42ms]
(pass) Request > constructor > string > "" [5.91ms]
(pass) Request > constructor > string > "Hello world" [1.54ms]
(pass) Request > constructor > string > "🫠" [1.77ms]
(pass) Request > constructor > string > "⁉️" [1.19ms]
(pass) Request > constructor > ArrayBuffer > empty buffer [8.63ms]
(pass) Request > constructor > ArrayBuffer > small buffer [3.50ms]
(pass) Request > constructor > ArrayBuffer > large buffer [4.37ms]
(pass) Request > constructor > SharedArrayBuffer > empty buffer [1.79ms]
(pass) Request > constructor > SharedArrayBuffer > small b
... (truncated)

release with fix: 4 skipped
$ bun scripts/build.ts --profile=release
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     6b1404c
  features     (none)

22 deps, 106 codegen, 1169 objects in 674ms

ninja: Entering directory `/workspace/bun/build/release'
[1/59] gen cpp.rs (cppbind)
[2/59] gen generated_host_exports.rs
generated_host_exports.rs: 91 exports (host=3, lazy=10, generic=78, rust=0); 244 extern-C blocks audited
[3/59] gen ZigGeneratedClasses.{cpp,h,rs}
Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts
  - ResolveMessage (13 fields)
  - BuildMessage (10 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts
  - Archive (4 fields, 1 class fields)
Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts
  - ResourceUsage (8 fields)
  - Subprocess (20 fields)
Found 1 classes from /wor
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
packages/bun-types/fetch.d.ts                      |  16 +
 .../bindings/webcore/streams/BunStreamSource.cpp   |  62 +++-
 src/jsc/bindings/webcore/streams/BunStreamSource.h |   3 +
 src/jsc/bindings/webcore/streams/JSReadRequest.cpp |  15 +
 .../streams/JSReadableByteStreamController.cpp     |   2 +
 .../bindings/webcore/streams/JSReadableStream.h    |   9 +
 .../streams/JSReadableStreamDefaultController.cpp  |   4 +
 .../webcore/streams/ReadableStreamOperations.cpp   | 136 +++++++
 src/jsc/bindings/webcore/streams/StreamQueue.h     |   2 +
 src/jsc/bindings/webcore/streams/StreamsForward.h  |  26 ++
 .../bindings/webcore/streams/WebStreamsExports.cpp |  43 +++
 .../bindings/webcore/streams/WebStreamsInternals.h |  20 ++
 .../bindings/webcore/streams/WebStreamsMisc.cpp    |  89 +++++
 src/runtime/server/RequestContext.rs               |  21 ++
 src/runtime/webcore/Body.rs                        | 232 ++++++++----
 src/runtime/webcore/ReadableStream.rs              |  46 ++-
 src/runtime/webcore/response.classes.ts            |   2 +
 test/js/web/fetch/body.test.ts                     | 397 +++++++++++++++++++++
 test/js/web/fetch/wpt/textstream-wpt.test.ts       |  32 ++
 test/js/web/fetch/wpt/textstream.any.js            | 177 +++++++++
 20 files changed, 1258 insertions(+), 76 deletions(-)
```

</details>

**gate history** · 17 passed · 0 rejected · iteration 14

<details><summary>evidence per changed file</summary>

```
file                                                      reads  edits  tests
packages/bun-types/fetch.d.ts                                 2      2      0
src/jsc/bindings/webcore/streams/BunStreamSource.cpp         11     17      0
src/jsc/bindings/webcore/streams/BunStreamSource.h            5      5      0
src/jsc/bindings/webcore/streams/JSReadRequest.cpp            3      5      0
…ings/webcore/streams/JSReadableByteStreamController.cpp      1      2      0
src/jsc/bindings/webcore/streams/JSReadableStream.h           4      4      0
…s/webcore/streams/JSReadableStreamDefaultController.cpp      2      3      0
…c/bindings/webcore/streams/ReadableStreamOperations.cpp     14     22      0
src/jsc/bindings/webcore/streams/StreamQueue.h                2      1      0
src/jsc/bindings/webcore/streams/StreamsForward.h             7     11      0
src/jsc/bindings/webcore/streams/WebStreamsExports.cpp        4      8      0
src/jsc/bindings/webcore/streams/WebStreamsInternals.h        6     11      0
src/jsc/bindings/webcore/streams/WebStreamsMisc.cpp           6     10      0
src/runtime/server/RequestContext.rs                          5      2      0
src/runtime/webcore/Body.rs                                  14     10      0
src/runtime/webcore/ReadableStream.rs                         3      8      0
(+ 4 more files)
```

</details>

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

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…kpressure test (oven-sh#36088)

`serve.test.ts` has been red on the darwin lanes since oven-sh#36072 landed
(main #83238, also the PR's own build #83229 as a retry-flake). The
subtest is `request body backpressure > releases a paused request body
when the handler responds without reading it`, which oven-sh#36072 added to
cover the `detach_response()` resume at `RequestContext.rs:2382`.

```
EPIPE: broken pipe, write
 syscall: "write",
   errno: -32,
    code: "EPIPE"
✗ request body backpressure > releases a paused request body when the handler responds without reading it
```

## Cause

The test sends a 32 MiB `PUT` over a raw `net.Socket` with `Connection:
close`, lets the server's pre-stream pause stall the upload, then has
the handler respond without touching `req.body` and waits for the client
to receive the response.

Once the handler returns, `render_bytes()` writes the response via
`try_end()` and uWS does `shutdown(SHUT_WR)` immediately followed by
`close()` (`HttpResponse.h:860-871`). Because the socket was paused, the
unread body bytes are still sitting in the kernel recv buffer, and
`close()` with unread recv data sends **RST**. On macOS that RST races
two things:

1. the upload pump's `sock.once('drain', writeMore)`, which is still
armed from `pumpUploadUntilPlateau`; when it fires and writes into the
reset peer the socket emits EPIPE, which the test's `sock.once('error',
reject)` turns into a failure, and
2. delivery of the already-written response bytes, which the RST can
drop before the client's `'data'` handler sees them.

On Linux the `'data'` event reliably wins the race, so the test passed
there; on darwin it loses ~70-80% of the time (verified on
`darwin-test-arm64-3` and `darwin-test-x64-2` with the main #83238
binary).

`detach_response()`'s `resp.resume()` is also a no-op on this path: for
a simple text body `try_end()` has already closed the socket by the time
it runs (`us_socket_resume` early-returns on a closed socket). So with
`Connection: close` the test was not actually observing the code it was
written to cover.

## Fix

Switch this one test to `Connection: keep-alive`. The server does not
close after responding, so there is no RST, the response is delivered
deterministically, and `detach_response()`'s resume runs on a live
socket. The test now additionally asserts that the client's upload
progresses past the plateau after the response, which is the direct
observable of the resume (without it the keep-alive socket would stay
paused and `getSent()` would never move).

Also: resolve the response promise on the body content rather than the
header terminator, and drop the `sock.once('error', reject)`; neither
race applies on a keep-alive connection but both were latent flake on
the old path. The `pumpUploadUntilPlateau` helper gains a `connection`
parameter (defaulting to `"close"`, so the other five callers are
untouched) and returns a `getSent()` accessor.

## Verification

With the main #83238 `bun` binary:

| lane | before | after |
| --- | --- | --- |
| darwin 26 aarch64 (`darwin-test-arm64-3`) | 7/10 fail (EPIPE) | 50/50
pass |
| darwin 14 x64 (`darwin-test-x64-2`) | 8/10 fail (EPIPE) | 20/20 pass |
| linux x64 debug+ASAN | 10/10 pass | 10/10 pass |

`USE_SYSTEM_BUN=1 bun test test/js/bun/http/serve.test.ts -t 'releases a
paused'` still fails on `toBeLessThan(TOTAL)` (no oven-sh#36006 backpressure),
so the test still exercises the same `src/` change. This is a test-only
diff; fail-before is against a Bun without oven-sh#36006, not against this PR's
own `src/`.

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

---

**no test proof** · iteration 0 · Platform-specific test-only change;
deferring to CI.

<!-- robobun:evidence:end -->
…ng (oven-sh#36180)

`Body.textStream()` over a native `ByteStream` (a fetch response body)
stalls forever when a multi-byte UTF-8 character is split across three
or more delivered chunks, i.e. whenever two consecutive native pulls
each decode to the empty string.

## Reproduction

```js
const parts = [[0x41], [0xf0], [0x9f], [0xab, 0xa0], [0x42]]; // "A" + "🫠" + "B"
const server = Bun.serve({ port: 0, fetch: () => new Response(new ReadableStream({
  async start(c) { for (const p of parts) { c.enqueue(Uint8Array.from(p)); await new Promise(r => setTimeout(r, 20)); } c.close(); },
})) });
const res = await fetch(server.url);
let out = "";
for await (const ch of res.textStream()) out += ch;  // never resolves; only "A" is delivered
```

The same origin reads correctly via `res.text()`,
`res.body.pipeThrough(new TextDecoderStream())`, and `textStream()` over
a user-provided `ReadableStream` body.

## Cause

`nativeEnqueueTextChunk` holds back an incomplete UTF-8 tail and returns
without enqueueing. In byte mode every pull that resolves with data
enqueues something, which tail-calls `callPullIfNeeded` and arms
`m_pullAgain`; in text mode an all-held-back chunk skips that, so once
the one buffered re-pull (set by the preceding enqueue's
`callPullIfNeeded`) is consumed, the spec pull-fulfilled handler sees
`pullAgain == false` and stops. The outstanding read request is never
fulfilled and `handle.pull()` is never called again.

The `SourceKind::TextDecode` path (`textDecodeReadRequestChunkSteps`,
used when the body is already a materialized byte `ReadableStream`)
already handles the empty-decode case by calling
`readableStreamDefaultControllerCallPullIfNeeded`; the native adapter
path did not.

## Fix

When a non-flush decode produces no output, call
`readableStreamDefaultControllerCallPullIfNeeded(controller)`. Inside a
pull this sets `m_pullAgain` so the loop continues; at other call sites
(`nativeSourceStart` with `m_started == false`, the push-driven
`onDrain`) it is either a no-op or correctly issues the next pull.

## Verification

```
$ bun bd test test/js/web/fetch/body.test.ts
440 pass, 0 fail, 4 skip
```

New `test.each` cases in `body.test.ts` drive a raw `net.Server` that
delivers each body byte as its own HTTP chunk with an event-loop yield
between writes, covering: 4-byte char split as `[lead][cont][cont
cont]`, 4-byte char byte-at-a-time, 3-byte char byte-at-a-time, and a
byte-at-a-time BOM. All four time out on main and pass with the fix.

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

---

**[review]** gate passed · iteration 0 · 2 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 5 failed, 4 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/fetch/body.test.ts
bun test v1.4.0 (adef51e)

test/js/web/fetch/body.test.ts:
(pass) Request > constructor > undefined [4.52ms]
(pass) Request > constructor > null [3.17ms]
(pass) Request > constructor > string > "" [5.94ms]
(pass) Request > constructor > string > "Hello world" [1.47ms]
(pass) Request > constructor > string > "🫠" [1.36ms]
(pass) Request > constructor > string > "⁉️" [1.10ms]
(pass) Request > constructor > ArrayBuffer > empty buffer [8.35ms]
(pass) Request > constructor > ArrayBuffer > small buffer [4.72ms]
(pass) Request > constructor > ArrayBuffer > large buffer [4.21ms]
(pass) Request > constructor > SharedArrayBuffer > empty buffer [1.66ms]
(pass) Request > constructor > SharedArrayBuffer > small buffer [1.81ms]
(pass) Request > constructor > SharedArrayBuffer > large buffer [3.89ms]
(pass) Request > constructor > Buffer > empty buffer [1.58ms]
(pass) Request > constructor > Buffer > small buffer [1.51ms]
(pass) Request > constructor > Buffer > large buffer [3.20ms]
(pass) Request > constructor 
... (truncated)

release without fix: 93 failed, 4 skipped
bun test v1.4.0-canary.1 (1498d7b)

test/js/web/fetch/body.test.ts:
(pass) Request > constructor > undefined [0.12ms]
(pass) Request > constructor > null [0.04ms]
(pass) Request > constructor > string > "" [0.11ms]
(pass) Request > constructor > string > "Hello world" [0.02ms]
(pass) Request > constructor > string > "🫠" [0.02ms]
(pass) Request > constructor > string > "⁉️"
(pass) Request > constructor > ArrayBuffer > empty buffer [0.14ms]
(pass) Request > constructor > ArrayBuffer > small buffer [0.15ms]
(pass) Request > constructor > ArrayBuffer > large buffer [3.00ms]
(pass) Request > constructor > SharedArrayBuffer > empty buffer [0.05ms]
(pass) Request > constructor > SharedArrayBuffer > small buffer [0.04ms]
(pass) Request > constructor > SharedArrayBuffer > large buffer [3.40ms]
(pass) Request > constructor > Buffer > empty buffer [0.06ms]
(pass) Request > constructor > Buffer > small buffer [0.03ms]
(pass) Request > constructor > Buffer > large buffer [2.97ms]
(pass) Request > constructor > Uint8Array > empty buffer [0.02ms]
(pass) Request > constructor > Uint8Array > small buffer [0.04ms]
(pass) Request > constructor > Uint8Array > large buffer [3.0
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 4 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/fetch/body.test.ts
bun test v1.4.0 (adef51e)

test/js/web/fetch/body.test.ts:
(pass) Request > constructor > undefined [4.43ms]
(pass) Request > constructor > null [3.24ms]
(pass) Request > constructor > string > "" [5.86ms]
(pass) Request > constructor > string > "Hello world" [1.51ms]
(pass) Request > constructor > string > "🫠" [1.34ms]
(pass) Request > constructor > string > "⁉️" [1.10ms]
(pass) Request > constructor > ArrayBuffer > empty buffer [8.26ms]
(pass) Request > constructor > ArrayBuffer > small buffer [4.75ms]
(pass) Request > constructor > ArrayBuffer > large buffer [4.25ms]
(pass) Request > constructor > SharedArrayBuffer > empty buffer [1.63ms]
(pass) Request > constructor > SharedArrayBuffer > small buffer [1.87ms]
(pass) Request > constructor > SharedArrayBuffer > large buffer [3.82ms]
(pass) Request > constructor > Buffer > empty buffer [1.50ms]
(pass) Request > constructor > Buffer > small buffer [1.54ms]
(pass) Request > constructor > Buffer > large buffer [3.32ms]
(pass) Request > constructor 
... (truncated)

release with fix: 4 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     adef51e
  features     baseline

22 deps, 108 codegen, 1171 objects in 825ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1234] install /workspace/bun
bun install v1.4.0-canary.1 (1498d7b)

Checked 124 installs across 170 packages (no changes) [22.00ms]
[2/1234] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (1498d7b)

Checked 1 install across 2 packages (no changes) [1.00ms]
[3/1234] gen ErrorCode+*.h
[4/1234] gen bindgenv2
[5/1234] fetch picohttpparser
[picohttpparser] up to date
[6/1234] install /workspace/bun/src/node-fallbacks
bun install v1.4.0-canary.1 (1498d7b)

Checked 129 installs across 147 packages (no changes) [7.00ms]
[7/1234] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[8/1234] fetch tinycc
[tinycc] up to date
[9/1234] fetch zlib
[zlib] up to date
[10/1234] gen .bind.ts → GeneratedBindings.cpp
[11/1234] fetch nodejs (prebuilt)
[nodejs] up to date
[12/1234] subst deps/zlib/zlib.h
[13/1234] fetch zstd
[zstd] up to date
[1
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
.../bindings/webcore/streams/BunStreamSource.cpp   |  9 +++--
 test/js/web/fetch/body.test.ts                     | 42 ++++++++++++++++++++++
 2 files changed, 49 insertions(+), 2 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                                                  reads  edits  tests
src/jsc/bindings/webcore/streams/BunStreamSource.cpp      2      3      0
test/js/web/fetch/body.test.ts                            3      3      0
```

</details>

<!-- robobun:evidence:end -->
Follow-up to oven-sh#36180. Test-only.

Adds regression coverage for the additional faces of the native-adapter
empty-decode stall, all verified to hang on b22e0e6 (the commit
before oven-sh#36180) and pass on d549845:

- **close-after-empty**: a body that ends in (or is only) an incomplete
UTF-8 tail reaches the flush decode and closes (`"\ufffd"`) instead of
stalling on the final pull.
- **BOM-carry then close**: `[EF][BB]` then FIN covers the other
null-returning branch of `streamingUTF8Decode` (the possible-BOM
hold-back).
- **error-after-empty**: a socket drop while the last pull decoded to
nothing surfaces as a rejection instead of an idle hang.
- **`req.textStream()` server-side**: a chunked upload that splits a
code point across chunks completes (same `ByteStream` adapter as the
fetch-response path).

Also refactors the raw-socket chunked origin into a `rawChunkedServer`
helper with `Symbol.asyncDispose` so each case is a three-line `await
using`.

```
$ bun bd test test/js/web/fetch/body.test.ts -t textStream
100 pass, 0 fail
```

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

---

**[stamp-90s]** gate passed · iteration 0 · 1 files touched

<details><summary>passes on PR (with fix)</summary>

```console
Test-only change.

Debug/ASAN (expected pass):
$ bun bd test 'test/js/web/fetch/body.test.ts'
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/js/web/fetch/body.test.ts
bun test v1.4.0 (0cdbb3a)

test/js/web/fetch/body.test.ts:
(pass) Request > constructor > undefined [5.03ms]
(pass) Request > constructor > null [3.19ms]
(pass) Request > constructor > string > "" [6.13ms]
(pass) Request > constructor > string > "Hello world" [1.53ms]
(pass) Request > constructor > string > "🫠" [1.42ms]
(pass) Request > constructor > string > "⁉️" [1.37ms]
(pass) Request > constructor > ArrayBuffer > empty buffer [8.69ms]
(pass) Request > constructor > ArrayBuffer > small buffer [5.06ms]
(pass) Request > constructor > ArrayBuffer > large buffer [4.85ms]
(pass) Request > constructor > SharedArrayBuffer > empty buffer [1.88ms]
(pass) Request > constructor > SharedArrayBuffer > small buffer [1.76ms]
(pass) Request > constructor > SharedArrayBuffer > large buffer [4.13ms]
(pass) Request > constructor > Buffer > empty buffer [1.53ms]
(pass) Request > constructor > Buffer > small buffer [1.52ms]
(pass) Request > constructor > Buffer > large buffer [4.65ms]
(pass) Request > constructor > Uint8Array > empty buffer [1.26ms]
(pass) Request > constructor > Uint8Array > small buffer [1.78ms]
(pass) Request > constructor > Uint8Array > large buffer [3.91ms]
(pass) Request > constructor > Uint8ClampedArray > empty buffer [1.63ms]
(pass) Request > constructor > Uint8ClampedArray > small buffer [1.55ms]
(pass) Request > constructor > Uint8ClampedArray > large buffer [3.41ms]
(pass) Request > constructor > Uint16Array > empty buffer [1.67ms]
(pass) Request > constructor > Uint16Array > small buffer [1.95ms]
(pass) Request > constructor > Uint16Array > large buffer [6.16ms]
(pass) Request > constructor > Uint32Array > empty buffer [19.54ms]
(pass) Request > constructor > Uint32Array > small buffer [2.43ms]
(pass) Request > constructor > Uint32Array > large buffer [10.54ms]
(pass) Request > constructor > Int8Array > empty buffer [1.41ms]
(
... (truncated)
Exit: 0
```

</details>

<details><summary>diff hotspot</summary>

```
test/js/web/fetch/body.test.ts | 96 ++++++++++++++++++++++++++++++++----------
 1 file changed, 73 insertions(+), 23 deletions(-)
```

</details>

**gate history** · 3 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                            reads  edits  tests
test/js/web/fetch/body.test.ts      7     10      0
```

</details>

<!-- robobun:evidence:end -->
…en-sh#36231)

### What

Cap `parallelSafeWidth` at 4 on macOS in `scripts/runner.node.mjs`.
Linux and Windows are unchanged.

### Why

oven-sh#36175 removed the per-platform cap (previously `isWindows ? 2 : 4`) and
switched to `availableParallelism() - 1`. On macOS this oversubscribes:

- **x64**: all eight Intel minis are i7-8700B (6 physical cores, 12 HT
threads), so width jumped **4 → 11**.
- **arm64 tart VMs**: each M2 Ultra host runs two 18-vCPU tart VMs (one
per macOS release), so width jumped **4 → 17** per VM, i.e. 34
coordinators contending for 24 physical cores when both VMs are busy.

Each `bun test --parallel` coordinator also forks its own worker
subprocesses, so the ~800-file batch phase no longer fits inside the
45-minute job timeout:

- build [84092](https://buildkite.com/bun/bun/builds/84092): `813 files
in parallel (11×)` on `darwin-matzo-x64` hit the job timeout mid-batch
- build [84124](https://buildkite.com/bun/bun/builds/84124) (first main
build with oven-sh#36175): `darwin-bagel-x64` shard was at 35 minutes when the
build was canceled
- build [84151](https://buildkite.com/bun/bun/builds/84151) (this PR
with x64-only cap): x64 passed at width 4, but
`darwin-sourdough-arm64-tart-15` ran `800 files in parallel (17×)` and
hit the 45-minute timeout
- build [84142](https://buildkite.com/bun/bun/builds/84142):
`darwin-ciabatta-arm64-tart-26` also hit the 45-minute timeout at width
17

Resulting width per lane:

| lane | cores | before | after |
|---|---|---|---|
| darwin x64 (i7-8700B) | 12 | 11 | **4** |
| darwin arm64 tart (M2 Ultra, 2 VMs/host) | 18 | 17 | **4** |
| darwin arm64 bare (M2) | 8 | 7 | **4** |
| linux/windows EC2 | 4 | 3 | 3 |

This matches the pre-oven-sh#36175 behavior on macOS exactly.

### Verification

Build 84151 confirmed the x64 side: both darwin x64 shards passed in ~15
min at width 4 (log shows `parallel-safe width 4`, `814 files in
parallel (4×)`). `node --check` passes.

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

---

**no test proof** · iteration 1 · build/CI scripts only; test-proof not
applicable

<!-- robobun:evidence:end -->
…bail (oven-sh#36232)

Follow-up to oven-sh#36175, from the first day of runs.

### What went wrong

**A darwin shard died at the Buildkite job timeout inside its batch**
(build 84092, `darwin-14-x64`, `019fa900`): darwin buckets ~800 files
into one `bun test --parallel` batch, and the runner's batch cap was
`max(10 min, 5 s × files)` ≈ 68 min — longer than the 45-minute job. So
when the batch wedged, the interrupt → name-the-hung-file → solo-retry
net never fired; the job was simply killed with no report.

**Panic under `--bail=N`**: the coordinator decided whether the panic
path or `--bail` had set `bailed` by reading it *after* `account_crash`
— which can itself set it via `bail_out()`. When the Nth failure was a
worker panic, the panic banner was skipped and in-flight siblings kept
running.

### Fixes

| | |
|---|---|
| **Stall detection by silence** | `spawnSafe` gains an `idleTimeout`,
re-armed on every stdout/stderr chunk. A wedged batch is silent, so the
batch now aborts gracefully after **4 minutes of no output**, naming the
hung file — a bound that doesn't grow with batch size. |
| **Cap bounded by the job's life** | the wall-clock backstop is `min(5
s × files, job remaining − 5 min)` via `BUILDKITE_TIMEOUT`, so it can
never outlive the job either. |
| **Panic under `--bail`** | snapshot `bailed` before accounting; run
`abort_on_worker_panic` on every panic (its own contract: "runs even if
`--bail` already set `bailed`"). |

Distinct annotation title for the new case: a silence stop reads
`stalled`, a wall-clock one `timeout`.

### Verified

Drove the runner over a bucket with one worker-only silent hang and a 10
s idle window: the guard fired at 13 s, the coordinator named the hung
file, the seven finished files kept their results, and the hanger was
retried alone — 22 s total instead of running to the cap.
`parallel.test.ts` crash/bail/junit cases pass.
…ed (oven-sh#36247)

## What

`test/js/bun/http/bun-serve-html.test.ts` segfaults on `windows-aarch64`
after oven-sh#36175 landed (builds 84162, 84194; one earlier sighting in
83933):

```
panic(main thread): Segmentation fault at address 0x48
Features: ... dev_server(14) ...
```

Symbolicated in oven-sh#36214 as `AsyncFSTask<Access>::run_from_js_thread` with
`self = null`, i.e. a zeroed `ConcurrentTask` was dispatched.

## Cause

`DevServer.watcher_atomics.events[*].concurrent_task` is the intrusive
MPSC node the watcher thread links into `EventLoop.concurrent_tasks`
when it submits a hot-reload event. It was an inline field of
`DevServer`, so `server.stop()` → `drop(Box<DevServer>)` freed it while
it was still linked. The next `tick_concurrent` then read
`.next`/`.task`/`.auto_delete` from freed memory. ASAN on Linux
confirms:

```
heap-use-after-free: ConcurrentTask::get_next (unbounded_queue.rs)
  ← BatchIterator::next ← EventLoop::tick_concurrent_with_count
freed by: Box<DevServer>::drop ← NewServer::deinit_if_we_can
  ← NewServer::stop ← dispose_from_js (using server)
```

On release builds the freed block reads back as zeros, so the copied
`Task` is `{tag: 0, ptr: null}`; tag 0 is `task_tag::Access`, whose
`run_from_js_thread` loads `self.result` at offset `0x48`.

The bug is latent and platform-agnostic. oven-sh#36175 exposed it because the
CI runner now spawns the napi addon prebuild in the background while
serial tests run; that writes under the watched project root, so the
`jsx-runtime` DevServers in this test file now reliably receive a
hot-reload event between the last `await fetch` and `using server`
disposal.

## Fix

`watcher_atomics` is now a `NonNull<WatcherAtomics>` owned via
`bun_core::heap::into_raw`, so the allocation can outlive `DevServer`
and every queued pointer keeps allocation-root provenance.
`watcher_acquire_event`, `watcher_release_and_submit_event` and
`recycle_event_from_dev_server` take `*mut Self` and derive the returned
`*mut HotReloadEvent` (and the linked `concurrent_task` node) from that
root pointer via raw place projections rather than from a `&mut
WatcherAtomics` reborrow.

`Drop for DevServer` reads `next_event` after `Watcher::shutdown` has
serialised out the watcher thread (which guarantees it is stable):

- `DONE`: nothing is queued; clear and `heap::destroy` as before.
- otherwise: a `concurrent_task` is still linked (or its `Task` is
already in the drain FIFO). Null `owner` on every event and leave the
allocation alive.

`HotReloadEvent::run` checks `owner.is_null()` first; when set it
reclaims the allocation via the new `atomics` backref and returns
without touching the dead `DevServer`. The `# Safety` contracts on `run`
and the `BakeHotReloadEvent` dispatch arm are updated to describe the
null-owner case.

## Test

`test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts` creates a
development server, bundles once so `app.js` is watched, synchronously
rewrites `app.js`, spins briefly without yielding so the watcher thread
can enqueue, disposes the server, then yields. Ten iterations. In a
separate file because the React-bundling cases in
`bun-serve-html.test.ts` already exceed the default per-test timeout
under a debug+ASAN build on `main`.

<details><summary>fail-before (debug+ASAN, src/ at main)</summary>

```
==25521==ERROR: AddressSanitizer: heap-use-after-free on address 0x79315e4743e8
READ of size 8 at 0x79315e4743e8 thread T0
    #2 <ConcurrentTask as Node>::get_next                unbounded_queue.rs:82
    #3 BatchIterator<ConcurrentTask>::next               unbounded_queue.rs:135
    #4 EventLoop::tick_concurrent_with_count             event_loop.rs:507
0x79315e4743e8 is located 488 bytes inside of 16512-byte region
freed by thread T0 here:
    #9  Box<DevServer>::drop
    #12 NewServer<false,true>::deinit_if_we_can          mod.rs:1770
    #13 NewServer<false,true>::stop                      mod.rs:1665
    #14 NewServer<false,true>::dispose_from_js           server_body.rs:2584
```

</details>

Passes with the fix in ~2.4s under debug+ASAN (also on a local
`windows-aarch64` debug build, where the original
`bun-serve-html.test.ts` is now 19/19);
`test/bake/deinitialization.test.ts` still green.

Supersedes the producer half of oven-sh#36214 (which adds a sentinel for the
same zeroed-task symptom).

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

---

**[review]** gate passed · iteration 4 · 6 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 1 failed, 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/http/bun-serve-html.test.ts test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts
bun test v1.4.0 (5f6622f)

test/js/bun/http/bun-serve-html.test.ts:
waitForServer /tmp/html-css-js_ObkyZk {
  "/": "/tmp/html-css-js_ObkyZk/index.html",
  "/dashboard": "/tmp/html-css-js_ObkyZk/dashboard.html",
}
[0.12ms] bundle index.html 1.09 KB
[0.05ms] bundle dashboard.html 1.27 KB
(pass) serve html [630.67ms]
waitForServer /tmp/bun-serve-html-txt_5C6B7a {
  "/": "/tmp/bun-serve-html-txt_5C6B7a/index.html",
}
[0.15ms] bundle index.html 0.40 KB
HASH efbnbska
(pass) serve plugins > basic plugin [556.20ms]
waitForServer /tmp/html-css-js-failing-plugin_OPRhwb {
  "/": "/tmp/html-css-js-failing-plugin_OPRhwb/index.html",
}
error: Plugin failed intentionally
    at /tmp/html-css-js-failing-plugin_OPRhwb/styles.css:0
error: Plugin failed intentionally
    at /tmp/html-css-js-failing-plugin_OPRhwb/styles.css:0
(pass) serve plugins > serve html with failing plugin [491.35ms]
waitForServer /tmp/html-css-js-empty-plugins_biqnN6 {
  "/": "/tmp/htm
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (96ff7ec)

test/js/bun/http/bun-serve-html.test.ts:
waitForServer /tmp/html-css-js_ZmgkBG {
  "/": "/tmp/html-css-js_ZmgkBG/index.html",
  "/dashboard": "/tmp/html-css-js_ZmgkBG/dashboard.html",
}
[0.00ms] bundle index.html 1.09 KB
[0.00ms] bundle dashboard.html 1.27 KB
(pass) serve html [25.17ms]
waitForServer /tmp/bun-serve-html-txt_uWNogT {
  "/": "/tmp/bun-serve-html-txt_uWNogT/index.html",
}
[0.00ms] bundle index.html 0.40 KB
HASH efbnbska
(pass) serve plugins > basic plugin [17.25ms]
waitForServer /tmp/html-css-js-failing-plugin_Kd1a8p {
  "/": "/tmp/html-css-js-failing-plugin_Kd1a8p/index.html",
}
error: Plugin failed intentionally
    at /tmp/html-css-js-failing-plugin_Kd1a8p/styles.css:0
error: Plugin failed intentionally
    at /tmp/html-css-js-failing-plugin_Kd1a8p/styles.css:0
(pass) serve plugins > serve html with failing plugin [16.33ms]
waitForServer /tmp/html-css-js-empty-plugins_Ecz7qJ {
  "/": "/tmp/html-css-js-empty-plugins_Ecz7qJ/index.html",
}
[0.00ms] bundle index.html 0.71 KB
(pass) serve plugins > empty plugin array [13.23ms]
Waiting for server
waitForServer /tmp/html-css-js-concurrent-plugins_l7wQg5 {
  "/": "/tmp/
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/http/bun-serve-html.test.ts test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts
bun test v1.4.0 (5f6622f)

test/js/bun/http/bun-serve-html.test.ts:
waitForServer /tmp/html-css-js_CpXhx4 {
  "/": "/tmp/html-css-js_CpXhx4/index.html",
  "/dashboard": "/tmp/html-css-js_CpXhx4/dashboard.html",
}
[0.09ms] bundle index.html 1.09 KB
[0.05ms] bundle dashboard.html 1.27 KB
(pass) serve html [588.64ms]
waitForServer /tmp/bun-serve-html-txt_rjZL4e {
  "/": "/tmp/bun-serve-html-txt_rjZL4e/index.html",
}
[0.15ms] bundle index.html 0.40 KB
HASH efbnbska
(pass) serve plugins > basic plugin [552.11ms]
waitForServer /tmp/html-css-js-failing-plugin_D8NJ2O {
  "/": "/tmp/html-css-js-failing-plugin_D8NJ2O/index.html",
}
error: Plugin failed intentionally
    at /tmp/html-css-js-failing-plugin_D8NJ2O/styles.css:0
error: Plugin failed intentionally
    at /tmp/html-css-js-failing-plugin_D8NJ2O/styles.css:0
(pass) serve plugins > serve html with failing plugin [505.55ms]
waitForServer /tmp/html-css-js-empty-plugins_vK0DVI {
  "/": "/tmp/htm
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 673ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/7] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[2/7] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[2/7] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/runtime/bake/DevServer.rs                      |  63 +++-
 src/runtime/bake/dev_server/lifecycle.rs           |  12 +-
 src/runtime/bake/dev_server/mod.rs                 | 401 +++++++++++----------
 src/runtime/dispatch.rs                            |  10 +-
 .../http/bun-serve-html-hot-reload-drop.test.ts    |  82 +++++
 test/js/bun/http/bun-serve-html.test.ts            |  10 +-
 6 files changed, 374 insertions(+), 204 deletions(-)
```

</details>

**gate history** · 3 passed · 2 rejected · iteration 4

<details><summary>evidence per changed file</summary>

```
file                                                     reads  edits  tests
src/runtime/bake/DevServer.rs                               10     13      0
src/runtime/bake/dev_server/lifecycle.rs                     5      9      0
src/runtime/bake/dev_server/mod.rs                          13     12      0
src/runtime/dispatch.rs                                      3      2      0
test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts      1      5      0
test/js/bun/http/bun-serve-html.test.ts                      6      9      0
```

</details>

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

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
…ven-sh#36331)

## What

A Worker running `Bun.serve()` with a streamed `ReadableStream` body,
terminated mid-stream, SIGABRTs the whole process on assertion-enabled
builds:

```
ASSERTION FAILED: !exception()
ExceptionScope.h(61) : void JSC::ExceptionScope::assertNoException()
```

Stack: `assertNoException` ← `Interpreter::executeCallImpl` ←
`executeBoundCall` ← `JSC::call` ← `AsyncContextFrame::call` ←
`HTTPResponseSink__onClose`, aborting thread "Worker". The same holds
for `HTTPSResponseSink__onClose` over a TLS listener.

## Repro

```js
const { Worker } = require("node:worker_threads");
const src = 'const server = Bun.serve({ port: 0, fetch() { let i = 0;' +
  '  return new Response(new ReadableStream({ async pull(c) {' +
  '    c.enqueue(new Uint8Array(8192).fill(i++)); if (i > 20000) c.close(); await Bun.sleep(0); } })); } });' +
  'require("node:worker_threads").parentPort.postMessage(server.port);';
for (let i = 0; i < 8; i++) {
  const w = new Worker(src, { eval: true });
  const port = await new Promise(r => w.once("message", r));
  const res = await fetch("http://127.0.0.1:" + port + "/");
  const rd = res.body.getReader();
  await rd.read();
  const done = new Promise(r => w.once("exit", r));
  w.terminate();
  await done;
  await rd.cancel().catch(() => {});
}
console.log("survived");
```

Under `bun bd` this aborts on the first iteration 8/8. Release builds
survive (the `ASSERT` is compiled out).

## Cause

`worker.terminate()` sets the sticky `TerminationException` on the
worker VM. Worker shutdown (`web_worker.rs` `close_all_socket_groups`)
then stops every `Bun.serve()`, which aborts in-flight responses:
`RequestContext` → `HTTPServerWritable::abort` → `signal.close(None)` →
`SinkSignal` close thunk → generated `HTTP(S)ResponseSink__onClose`,
which re-enters JS via `AsyncContextFrame::call` → `JSC::profiledCall` →
`executeCallImpl`. `executeCallImpl` opens with
`scope.assertNoException()`, and the already-pending termination
exception trips it.

None of `__onClose`, `__onReady`, or the controller's `detach()` (all
generated by `generate-jssink.ts`, shared by all 6 sink classes) checked
for a pending exception before calling into JS.

## Fix

- `generate-jssink.ts`: guard `detach()`, `__onClose`, and `__onReady`
with `vm.hasPendingTerminationException()` before
`AsyncContextFrame::call`, matching the pattern in `Worker.cpp` /
`NodeTimerObject.cpp` / `JSDOMPromiseDeferred.cpp`. `detach()`'s native
cleanup (nulling `m_sinkPtr`, `Bun__onSinkDestroyed`,
`controllerDetached`) still runs; only the JS onClose is skipped, which
only exists to transition the direct `ReadableStream`'s JS-visible state
and is moot once the VM is shutting down.
- `Sink.rs`: add a `global.has_exception()` early-return in the
`SinkSignal` `close` / `ready` vtable thunks, mirroring the idiom in
`WebSocketServerContext.rs` / `socket/Handlers.rs`. Short-circuits
before the `call_check_slow` scope is constructed. The Rust
`JSSink::detach` is left alone because it must still clear the signal,
unprotect the cell, and run the C++ native cleanup; the C++ `detach()`
guard handles that path.

The `type:"direct"` body cell was also tried but hits a separate
pre-existing assert on main (`VMTraps::deferTerminationSlow`'s
`hasTerminationRequest()` check, rooted at `web_worker.rs` shutdown
clearing the request flag but not the sticky exception before
`close_all_socket_groups`); that is tracked separately.
`BunStreamSource.cpp`'s `readDirectStreamCloseImpl` has the same shape
(pre-call no termination check at the `sinkController.end()` /
`cancel()` calls) but is unreproduced; also left for a separate change.

## Verification

- `bun bd test test/js/web/workers/worker-terminate-lifetime.test.ts -t
"does not trip assertNoException"`: both cells (http `HTTPResponseSink`,
https `HTTPSResponseSink`) fail on main (`ASSERTION FAILED:
!exception()`, exit 134, first iteration every run), pass with fix (~13s
concurrent).
- `test/js/bun/http/serve-direct-readable-stream.test.ts`: 13 pass
(direct-stream onClose path unchanged for the non-terminating case).

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

---

**no test proof** · iteration 1 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/web/workers/worker-terminate-lifetime.test.ts

<!-- robobun:evidence:end -->
…aking it (oven-sh#36335)

## Problem

`test/cli/install/bun-info.test.ts` (and its sibling
`bun-audit.test.ts`) started aborting on the `:debian: 13 x64-asan` PR
lane with a LeakSanitizer report after oven-sh#36175 landed (observed on builds
84674 / 84751 / 84815 / 84881):

```
==19020==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 512 byte(s) in 1 object(s) allocated from:
    ...
    #16 in <bun_http::HTTPClient>::clone_metadata src/http/lib.rs:3977:13
    #17 in handle_on_data_headers<true> src/http/lib.rs:3761:14
    ...
    #26 in <bun_http::http_thread::HttpThread>::process_events
```

## Cause

`AsyncHTTP::send_sync` wrapped the terminal `HTTPResponseMetadata` in
`ManuallyDrop` and returned the inner `picohttp::Response<'static>`:

```rust
let metadata = core::mem::ManuallyDrop::new(metadata);
Ok(metadata.response)
```

This was carried over from the Zig port (the original `sendSync`
returned the bare `Response` and never `deinit`'d the metadata). It
leaks two heap allocations per call: the `Box<[Header]>` leaked via
`heap::release` in `clone_metadata`, and the `StringBuilder`-owned
`owned_buf` that holds status text / header names / header values. Every
sync CLI request goes through this path: `bun info` / `bun pm view`,
`bun audit`, `bun publish` (up to four times with the OTP retry), `bun
upgrade`, `bun create`, and `build --compile`'s target download.

LSan's default scan is conservative, treating stacks and registers of
every thread as roots. The only live reference to the leaked header
slice after the command returns is the `Response` alias stored in
`real.response` by `send_sync_callback`, and that lives on a frame
already below the main thread's SP when `Global::exit` runs the leak
check. Whether LSan still sees it depends on whether a thread happened
to park in epoll / a futex with a stale pointer to the slice in a
callee-saved register. On the x64-asan PR lane it stopped being hidden
after oven-sh#36175; locally it stays hidden unless registers are excluded as
roots. A fix for this leak already exists on the
`farm/3977ed4f/linux-arm64-asan-ci` branch (7f1803a) and in oven-sh#36173;
this PR extracts just the leak fix to unblock the x64-asan lane.

## Fix

Return the owning `HTTPResponseMetadata` from `send_sync`. Accessor
methods (`status_code()`, `status_text()`, `header()`,
`header_if_other_is_absent()`) hand out reborrows tied to `&self` so
borrowck enforces that no slice escapes the metadata's scope; the inner
`Response` is typed `'static` but its slices borrow the sibling
`owned_buf` / header slice that `Drop` frees. Callers switch from
`res.status_code` / `res.headers.get(..)` to the accessor form.
`npm::response_error` now takes `&HTTPResponseMetadata` directly.
`send_sync_callback` writes `real.response = None` instead of copying
the alias back into the caller's `AsyncHTTP`, since that stored copy
would dangle once the returned metadata is dropped and no sync caller
reads `self.response`.

## Test

Added an ASAN-gated case to `bun-info.test.ts` that runs `bun info`
against a local `Bun.serve` registry with `LSAN_OPTIONS=use_registers=0`
so the leak is observed deterministically, and asserts a combined `{
stdout, stderr, exitCode }` result with LSan's default non-zero exit
left intact.

```
# fail-before (src/ reverted to main, debug build)
(fail) bun info does not leak the sync response metadata [5307ms]
  SUMMARY: AddressSanitizer: 206 byte(s) leaked in 2 allocation(s).

# pass-after
bun bd test test/cli/install/bun-info.test.ts
 20 pass  0 fail  (new leak test: 223ms)

bun bd test test/cli/install/bun-audit.test.ts     # 16 pass
bun bd test test/cli/install/bun-create.test.ts    # 19 pass
bun bd test test/cli/install/bun-upgrade.test.ts   #  8 pass
```

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

---

**[review]** gate passed · iteration 1 · 10 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 1 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/bun-info.test.ts
bun test v1.4.0 (8f0ef47)

test/cli/install/bun-info.test.ts:
(pass) bun info > bun info (main command) > should display package info for latest version [359.12ms]
(pass) bun info > bun info (main command) > should handle missing arguments [346.80ms]
(pass) bun info > bun info (main command) > should display package info for specific version [402.47ms]
(pass) bun info > bun pm view (alias) > should display package info for latest version [380.58ms]
(pass) bun info > bun info (main command) > should display specific property [484.38ms]
(pass) bun info > bun pm view (alias) > should display package info for specific version [380.99ms]
(pass) bun info > bun pm view (alias) > should display nested property [324.88ms]
(pass) bun info > bun pm view (alias) > should handle non-existent package [297.70ms]
(pass) bun info > bun pm view (alias) > should display specific property [1379.12ms]
(pass) bun info > bun pm view (alias) > should output JSON format with --json flag [1356.80ms]
(pass) bun info > bun pm v
... (truncated)

release without fix: 1 skipped
bun test v1.4.0-canary.1 (b4544d0)

test/cli/install/bun-info.test.ts:
(pass) bun info > bun info (main command) > should display package info for latest version [69.02ms]
(pass) bun info > bun info (main command) > should handle missing arguments [68.71ms]
(pass) bun info > bun pm view (alias) > should handle non-existent package [62.61ms]
(pass) bun info > bun pm view (alias) > should display package info for latest version [71.24ms]
(pass) bun info > bun pm view (alias) > should display nested property [69.87ms]
(pass) bun info > bun pm view (alias) > should handle . [61.86ms]
(pass) bun info > bun info (main command) > should display package info for specific version [75.65ms]
(pass) bun info > bun info (main command) > should display specific property [77.38ms]
(pass) bun info > bun pm view (alias) > should output JSON format with --json flag [78.60ms]
(pass) bun info > bun pm view (alias) > versions[0] should work [71.64ms]
(pass) bun info > bun pm view (alias) > versions should work [75.43ms]
(pass) bun info > bun pm view (alias) > should handle dist-tags like latest [74.19ms]
(pass) bun info > bun pm view (alias) > should handle version ranges [78.07ms]
(p
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/bun-info.test.ts
bun test v1.4.0 (8f0ef47)

test/cli/install/bun-info.test.ts:
(pass) bun info > bun info (main command) > should display package info for latest version [349.74ms]
(pass) bun info > bun info (main command) > should display package info for specific version [468.60ms]
(pass) bun info > bun info (main command) > should display specific property [469.69ms]
(pass) bun info > bun info (main command) > should handle missing arguments [475.25ms]
(pass) bun info > bun pm view (alias) > should display package info for latest version [506.84ms]
(pass) bun info > bun pm view (alias) > should display package info for specific version [460.48ms]
(pass) bun info > bun pm view (alias) > should display nested property [392.82ms]
(pass) bun info > bun pm view (alias) > should display specific property [507.04ms]
(pass) bun info > bun pm view (alias) > should handle non-existent package [458.13ms]
(pass) bun info > bun pm view (alias) > should output JSON format with --json flag [575.15ms]
(pass) bun info > bun pm vie
... (truncated)

release with fix: 1 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 1113ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/6] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[1/6] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m bun_collections v0.0.0 (/workspace/bun/src/collections)
�[1m�[92m   Compiling�[0m bun_p
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/http/AsyncHTTP.rs                         | 12 +++--
 src/http/lib.rs                               | 22 +++++++++
 src/install/npm.rs                            | 23 +++++-----
 src/runtime/cli/audit_command.rs              |  4 +-
 src/runtime/cli/create_command.rs             | 14 +++---
 src/runtime/cli/pm_view_command.rs            |  2 +-
 src/runtime/cli/publish_command.rs            | 28 +++++-------
 src/runtime/cli/upgrade_command.rs            |  4 +-
 src/standalone_graph/StandaloneModuleGraph.rs |  2 +-
 test/cli/install/bun-info.test.ts             | 65 +++++++++++++++++++++++++--
 10 files changed, 125 insertions(+), 51 deletions(-)
```

</details>

**gate history** · 2 passed · 1 rejected · iteration 1

<details><summary>evidence per changed file</summary>

```
file                                           reads  edits  tests
src/http/AsyncHTTP.rs                              5      6      0
src/http/lib.rs                                    5      4      0
src/install/npm.rs                                 0      0      0
src/runtime/cli/audit_command.rs                   1      0      0
src/runtime/cli/create_command.rs                  2      0      0
src/runtime/cli/pm_view_command.rs                 2      0      0
src/runtime/cli/publish_command.rs                 2      0      0
src/runtime/cli/upgrade_command.rs                 1      0      0
src/standalone_graph/StandaloneModuleGraph.rs      1      0      0
test/cli/install/bun-info.test.ts                  6     11      0
```

</details>

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

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…GUI (oven-sh#36292)

Fixes oven-sh#19916

## Repro

```console
> bun build --compile --windows-hide-console ./app.js --outfile out.exe
> # read OptionalHeader64.Subsystem at e_lfanew + 24 + 68
out.exe: subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI (3)   <-- should be WINDOWS_GUI (2)
```

The flag is accepted and threaded all the way into `inject()` as
`inject_options.hide_console`, then dropped on the floor:

```rust
pub(crate) fn inject(
    bytes: &[u8],
    self_exe: &ZStr,
    inject_options: &InjectOptions,
    target: &CompileTarget,
) -> Fd {
    let _ = inject_options;   // never read
```

The original Zig implementation (oven-sh#15894) called
`bun.windows.editWin32BinarySubsystem(fd, .windows_gui)` here; the Rust
PE writer never gained an equivalent, so the flag has been a no-op since
the port. Same for `Bun.build({ compile: { windows: { hideConsole: true
} } })`.

## Fix

Add `PEFile::set_subsystem(u16)` to `src/exe_format/pe.rs` (writes
`OptionalHeader64.subsystem` and recomputes the PE checksum) and call it
with `IMAGE_SUBSYSTEM_WINDOWS_GUI` from the `CompileTargetOs::Windows`
arm of `inject()` when `hide_console` is set. This is pure byte
manipulation on the already-loaded PE image, so it runs in the same pass
that appends the `.bun` section, before `rescle` touches the file for
icon/metadata.

Because the subsystem write has no WinAPI dependency, the
`!cfg!(windows)` gate on `--windows-hide-console` in the CLI is also
dropped so it works when cross-compiling to a Windows target (the
`Bun.build()` API already had no host-OS check). The other `--windows-*`
flags still go through `rescle`/`BeginUpdateResourceW` and stay
Windows-host-only.

## Verification

New `--windows-hide-console` describe in
`test/bundler/compile-windows-metadata.test.ts` reads the Subsystem
field from the emitted PE header:

```
USE_SYSTEM_BUN=1 bun test test/bundler/compile-windows-metadata.test.ts -t subsystem
  (pass) default build is a console subsystem
  (fail) CLI flag sets GUI subsystem                           Expected: 2  Received: 3
  (fail) Bun.build() hideConsole sets GUI subsystem            Expected: 2  Received: 3
  (fail) GUI subsystem survives the rescle metadata pass       Expected: 2  Received: 3

bun bd test test/bundler/compile-windows-metadata.test.ts -t subsystem
  4 pass, 0 fail
```

The CLI test also launches the resulting GUI-subsystem exe and asserts
it runs (writes a marker file and exits 0). The rescle test pairs
`--windows-hide-console` with `--windows-title` to confirm the subsystem
survives the `EndUpdateResourceW` rewrite.

The `--windows-icon` half of the original report goes through `rescle`
on current main and hard-errors on failure rather than warning; later
commenters on the issue confirm icons work in recent builds. This PR
only addresses `--windows-hide-console`.

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

---

**no test proof** · iteration 1 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/bundler/compile-windows-metadata.test.ts

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

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…h#36290)

Fixes oven-sh#12200
Fixes oven-sh#12882

## Repro

From inside a workspace package, `bun patch <pkg>` prints an absolute
path and suggests running `bun patch --commit
'<abs>/node_modules/<pkg>'` from the same directory. On current canary
that suggested command fails in two different ways depending on
platform:

**Windows** (reported in oven-sh#12882, oven-sh#12200):
```
PS Z:\repo\packages\server> bun patch is-odd
...
  bun patch --commit 'Z:\repo/node_modules/is-odd'

PS Z:\repo\packages\server> bun patch --commit 'Z:\repo/node_modules/is-odd'
ENOENT: No such file or directory: failed to read "packages\server\Z:\repo\node_modules\is-odd\package.json" (open)
```

**Linux/macOS/Windows**, isolated linker (now the default), if the user
types the relative form instead:
```
$ cd packages/server
$ bun patch is-odd                         # editable copy lands at <root>/node_modules/is-odd
$ echo '// x' >> ../../node_modules/is-odd/index.js
$ bun patch --commit node_modules/is-odd
error: failed to parse patchfile: bad_file_mode
error: failed to patch package: is-odd@3.0.1
```

The written `patches/is-odd@3.0.1.patch` is garbage (records the
`packages/server/node_modules/is-odd` symlink as a `mode 120000` file,
plus every cache file as "deleted").

The original headline error from oven-sh#12200, `EPERM: Operation not permitted
(copyfile())` on cross-drive renames, no longer reproduces on current
main; the EXDEV fallback in `renameat_concurrently` handles it. The
recent "still broken in 1.3.x" comments on the issue are hitting the two
failures above.

## Cause

`do_patch_commit` / `prepare_patch` rebase a relative path argument onto
the invoking workspace package's prefix so that a path typed relative to
cwd resolves from the workspace root. Two bugs in that rebasing:

1. The "is this already absolute" guard was
   ```rust
   !Platform::Posix.is_absolute(argument)
       || (cfg!(windows) && !Platform::Windows.is_absolute(argument))
   ```
On Windows, for `C:\...`, `Posix.is_absolute` is `false`, so
`!posix_abs` is `true` and the disjunction short-circuits. A
drive-letter path gets joined onto `packages/<ws>/`. The intent was `&&`
(De Morgan of "absolute in either sense").

2. With the isolated linker, `packages/<ws>/node_modules/<pkg>` is a
symlink into `node_modules/.bun/`. `bun patch <name>` puts the editable
copy at the *root* `node_modules/<pkg>` (a real directory, symlinks
detached), so the rebased path points at the wrong place. `git diff
--no-index` treats a symlink as a single-line file (mode 120000), and
`git_diff_postprocess` cannot strip the prefixes, so the patch is
unparseable.

## Fix

- Replace the guard with `!Platform::AUTO.is_absolute(argument)` in both
`do_patch_commit` and `prepare_patch`. On POSIX this is
`Platform::Posix` (unchanged); on Windows it is `Platform::Windows`,
whose `is_absolute` already accepts `/`-rooted, `\`-rooted and
drive-letter paths.
- In `do_patch_commit`, when the workspace-prefixed path is a symlink or
missing but the argument taken root-relative is a real directory, use
the root-relative path. `prepare_patch` always leaves a real directory,
so a real directory at the root is where the editable copy actually is.
`prepare_patch` itself is unchanged in this respect since it already
detaches symlinks at whichever path it chooses.

## Verification

Two new tests under "inside workspace package, committing with the path
bun suggested" in `test/cli/install/bun-patch.test.ts`, one feeding the
printed absolute path back verbatim and one using `node_modules/is-odd`
relative from the subdir.

Linux x64:
- `USE_SYSTEM_BUN=1`: `relative node_modules/<pkg>` fails with
`bad_file_mode`; `absolute path` already passes (POSIX was unaffected)
- `bun bd test`: both pass; full `bun-patch.test.ts` 31/31 pass

Windows x64:
- `USE_SYSTEM_BUN=1`: both fail (`ENOENT: packages\server\C:\...` and
`bad_file_mode`)
- `bun bd test`: both pass; full `bun-patch.test.ts` 31/31 pass

<details><summary>Windows fail-before</summary>

```
ENOENT: No such file or directory: failed to read "packages\server\C:\Users\azureuser\AppData\Local\Temp\patch-ws-abs_oeKec2\node_modules\is-odd\package.json" (open)
(fail) ... > absolute path

error: failed to parse patchfile: bad_file_mode
error: failed to patch package: is-odd@3.0.1
(fail) ... > relative node_modules/<pkg>
```
</details>

The `Platform::AUTO.is_absolute` change is the same fix as oven-sh#35563; this
PR additionally handles the isolated-linker symlink case that oven-sh#35563
does not cover.

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

---

**no test proof** · iteration 4 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/cli/install/bun-patch.test.ts

<!-- robobun:evidence:end -->
…t stall bun install (oven-sh#36295)

Fixes oven-sh#4938. Fixes oven-sh#33278. Fixes oven-sh#29695. Fixes oven-sh#25619.

Closes oven-sh#33280, Closes oven-sh#32864 and Closes oven-sh#29696 (the per-attempt connect
timer in oven-sh#32949 is orthogonal and left for a separate PR).

### What does this PR do?

On a dual-stack host where IPv6 is advertised but blackholed (Starlink,
broken home routers, some corporate networks, Docker bridges), `bun
install` stalls for ~75-130s per registry manifest fetch.
`registry.npmjs.org` resolves to 12 AAAA + 12 A records; RFC 6724 sorts
the AAAA records first, and `process_results()` in
`src/runtime/dns_jsc/dns.rs` is supposed to interleave address families
(RFC 8305 §4) before handing the list to usockets so the
`CONCURRENT_CONNECTIONS = 4` parallel connect attempts cover both
families.

The interleave loop has never worked:

```rust
let mut want = netc::AF_INET6 as usize;
'outer: for idx in 0..count {
    if results[idx].info.ai_family as usize == want {
        continue;   // never flips want
    }
    for j in (idx + 1)..count { ... }
    break 'outer;   // always breaks after first non-matching idx
}
```

`want` starts at hardcoded `AF_INET6` and only flips on a swap, so any
list that *starts* with IPv6 (the failing shape) passes through
unchanged. With `[12×v6, 12×v4]` the first four parallel connects are
all blackholed IPv6 and the kernel retries SYNs until `tcp_syn_retries`
is exhausted (~75s on macOS, ~127s on Linux), matching the 105.80s one
reporter measured.

### Fix

Replace the post-copy swap with a closed-form interleave during the copy
pass: alternate between the resolver's first family and the other,
preserving resolver order within each family. The slot mapping is a
bijection over `0..count`, so the existing `MaybeUninit`/`assume_init`
invariant is unchanged and the broken swap loop is deleted.

Starting from the resolver's first family (rather than hardcoding v6)
respects the OS's RFC 6724 policy: a v4-first result stays v4-first, and
a user who set `precedence ::ffff:0:0/96 100` in `gai.conf` (the
workaround several reporters used) still gets their preference.

With the interleave in place the first four attempts on a 12+12 result
are `[v6, v4, v6, v4]`, so reachable IPv4 connects immediately even when
every IPv6 address is blackholed.

### How did you verify your code works?

Added `dnsCacheSeed(hostname, addresses)` to `bun:internal-for-testing`.
It builds a synthetic addrinfo linked list, runs it through the real
`process_results()`, and stores the packed result on a `Request` in the
global DNS cache the same way `after_result()` does. Every test in
`test/js/bun/dns/dns-interleave.test.ts` then does a real `fetch()` to
the seeded hostname, so `us_socket_group_connect` →
`Bun__addrinfo_getRequestResult` → `start_connections()` consumes the
exact interleaved list.

The Linux test is an end-to-end repro: 4 blackholed IPv4 listeners
(backlog-0 with the accept queue filled, so SYNs are silently dropped
and `connect()` sits in `EINPROGRESS`) followed by one reachable `::1`.
With the interleave reverted to sequential order:

```
out: { ok: false, err: "TimeoutError", ms: 4022, order: [4, 4, 4, 4, 6] }
```

With the fix, `::1` is in slot 1 of the first batch and the fetch
succeeds in ~1s:

```
out: { ok: true, body: "ok via ::1", ms: ..., order: [4, 6, 4, 4, 4] }
```

`rust:check-all` passes on all 10 targets.

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

---

**no test proof** · iteration 2 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/bun/dns/dns-interleave.test.ts

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

---------

Co-authored-by: Christian Rishøj <christian@rishoj.net>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Deflakes \`test/js/node/http/numeric-header.test.ts\`, which timed out
in the parallel batch on Debian 13 x64 and aarch64 \`test-bun\` lanes
while passing when run alone.

### Cause

The request handler called \`expect()\` before \`res.end()\`:

\`\`\`ts
const server = createServer((req, res) => {
expect(req.headers["1234"]).toBe("Hello from client!"); // throws on
mismatch
  ...
  res.end(...); // never reached on throw
});
\`\`\`

If the assertion throws, \`res.end()\` is never called, so the client
\`fetch\` hangs until the 5s test timeout instead of failing fast. The
test also listened without a host and fetched \`localhost\`, and the
listen promise had no rejection path, so any listen error would also
hang.

### Fix

- Capture header values in the handler and assert them after the
response completes, so a mismatch is a normal assertion failure instead
of a timeout.
- Bind and connect on \`127.0.0.1\` explicitly and send \`Connection:
close\`.
- Use \`await once(server, "listening")\` so listen errors reject.
- Close the server (and any open connections) in a \`finally\` block.

### Verification

- \`bun bd test test/js/node/http/numeric-header.test.ts\`: pass
- 10 parallel debug runs: 10/10 pass
- 20 parallel release runs: 20/20 pass

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

---

**[stamp-90s]** gate passed · iteration 0 · 1 files touched

<details><summary>passes on PR (with fix)</summary>

```console
Test-only change.

Debug/ASAN (expected pass):
$ bun bd test 'test/js/node/http/numeric-header.test.ts'
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/js/node/http/numeric-header.test.ts
bun test v1.4.0 (971676e)

test/js/node/http/numeric-header.test.ts:
(pass) HTTP numeric headers > should handle numeric header names [499.32ms]

 1 pass
 0 fail
 2 expect() calls
Ran 1 test across 1 file. [3.28s]
Exit: 0
```

</details>

<details><summary>diff hotspot</summary>

```
test/js/node/http/numeric-header.test.ts | 64 +++++++++++++++++---------------
 1 file changed, 35 insertions(+), 29 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                                      reads  edits  tests
test/js/node/http/numeric-header.test.ts      2      1      0
```

</details>

<!-- robobun:evidence:end -->
…imeout an absolute handshake deadline (oven-sh#36308)

## Problem

A hostile or MITM'd server that answers every client auth packet with
another **AuthSwitchRequest** (MySQL 0xFE) or **AuthenticationSASL /
MD5Password / CleartextPassword** (Postgres `R`) drives Bun into an
unbounded authentication loop at 100% CPU, pre-auth, with no
application-visible signal. `connectionTimeout` never fires because
`on_data` re-arms the connect-phase timer on every inbound packet, so
any server that dribbles bytes (e.g. one greeting byte per 1.5s) holds
the client indefinitely.

```
client answered 40 AuthSwitchRequests on ONE connection in 7863ms (connectionTimeout: 2 never fired) -> BUG
```

mysql2 / libmysqlclient refuse a second auth-switch; libpq rejects a
second AuthenticationSASL with `duplicate SASL authentication request`.

## Cause

Two independent defects, shared between the adapters:

1. `MySQLConnection::handle_auth` honoured every
`PacketType::AUTH_SWITCH` with no per-handshake state. The Postgres
`Authentication::SASL` / `ClearTextPassword` / `MD5Password` arms
likewise accepted a fresh request in every authentication state.
2. `JSMySQLConnection::on_data` and `PostgresSQLConnection::on_data`
bracketed processing with a `reset_connection_timeout()` (mysql) /
`disable_connection_timeout()` + `reset_connection_timeout()`
(postgres), turning the connect deadline into a per-packet inactivity
timer.

## Fix

MySQL: record that an AuthSwitchRequest has been honoured and reject a
second one with `ERR_MYSQL_UNEXPECTED_PACKET`. `on_data` now leaves the
connect-phase timer running until the auth OK transitions the connection
to `Connected`, at which point it is re-armed as the idle timer.

Postgres: `AuthenticationSASL`, `AuthenticationCleartextPassword` and
`AuthenticationMD5Password` are only accepted while
`authentication_state` is `Pending`; any later arrival is rejected with
`ERR_POSTGRES_UNEXPECTED_MESSAGE`. A new
`AuthenticationState::ClearText` records that a cleartext password was
sent. `on_data` now leaves the connect-phase timer running until
`ReadyForQuery` transitions the connection to `Connected`.

## Verification

New scripted wire-server tests:

- `test/js/sql/sql-mysql-duplicate-auth-switch.test.ts`: a second
AuthSwitchRequest is rejected after exactly one response; the one-switch
happy path still connects; a server that trickles the greeting one byte
per 200ms fails at the 1s `connectionTimeout`.
- `test/js/sql/postgres-duplicate-auth-request.test.ts`: duplicate and
mixed-method auth requests are rejected after exactly one response; the
single-request cleartext and MD5 happy paths still connect; a server
that trickles bytes during auth fails at the 1s `connectionTimeout`.

Existing `wire-frames.test.ts`, `sql-mysql-auth-short-nonce.test.ts`,
`sql-connect-error-reporting.test.ts`,
`postgres-frame-boundary.test.ts`,
`postgres-invalid-message-length.test.ts`, and the scripted cases in
`sql-mysql.auth.test.ts` pass unchanged.

Closes oven-sh#33671 (postgres half, now folded in and rebased).

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

---

**[review]** gate passed · iteration 4 · 7 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 11 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/sql/postgres-duplicate-auth-request.test.ts test/js/sql/sql-mysql-duplicate-auth-switch.test.ts
bun test v1.4.0 (2d1c00e)

test/js/sql/sql-mysql-duplicate-auth-switch.test.ts:
(fail) MySQL: a second AuthSwitchRequest to the same plugin is rejected [5000.63ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: at most two AuthSwitchRequests are honoured per handshake [5000.22ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: caching_sha2 perform_full_authentication is honoured at most once [5000.20ms]
  ^ this test timed out after 5000ms.
(pass) MySQL: a single AuthSwitchRequest to a different plugin then OK still connects [145.61ms]
(pass) MySQL: a single AuthSwitchRequest to the greeting's plugin then OK still connects [82.40ms]
(fail) MySQL: connectionTimeout bounds the whole handshake, not per packet [5000.14ms]
  ^ this test timed out after 5000ms.

test/js/sql/postgres-duplicate-auth-request.test.ts:
(fail) postgres: duplicate AuthenticationSASL is rejected, not answered again [5000.18ms]
  ^ this test timed out af
... (truncated)

release without fix: 11 FAILED
bun test v1.4.0-canary.1 (1498d7b)

test/js/sql/sql-mysql-duplicate-auth-switch.test.ts:
(fail) MySQL: a second AuthSwitchRequest to the same plugin is rejected [5000.60ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: at most two AuthSwitchRequests are honoured per handshake [5000.54ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: caching_sha2 perform_full_authentication is honoured at most once [5000.53ms]
  ^ this test timed out after 5000ms.
(pass) MySQL: a single AuthSwitchRequest to a different plugin then OK still connects [4.80ms]
(pass) MySQL: a single AuthSwitchRequest to the greeting's plugin then OK still connects [1.94ms]
(fail) MySQL: connectionTimeout bounds the whole handshake, not per packet [5000.08ms]
  ^ this test timed out after 5000ms.

test/js/sql/postgres-duplicate-auth-request.test.ts:
(fail) postgres: duplicate AuthenticationSASL is rejected, not answered again [5000.11ms]
  ^ this test timed out after 5000ms.
(fail) postgres: duplicate AuthenticationCleartextPassword is rejected, not answered again [5000.13ms]
  ^ this test timed out after 5000ms.
(fail) postgres: duplicate AuthenticationMD5Password is rejected, not answered
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/sql/postgres-duplicate-auth-request.test.ts test/js/sql/sql-mysql-duplicate-auth-switch.test.ts
bun test v1.4.0 (2d1c00e)

test/js/sql/sql-mysql-duplicate-auth-switch.test.ts:
(pass) MySQL: a second AuthSwitchRequest to the same plugin is rejected [842.62ms]
(pass) MySQL: at most two AuthSwitchRequests are honoured per handshake [129.45ms]
(pass) MySQL: caching_sha2 perform_full_authentication is honoured at most once [230.70ms]
(pass) MySQL: a single AuthSwitchRequest to a different plugin then OK still connects [143.35ms]
(pass) MySQL: a single AuthSwitchRequest to the greeting's plugin then OK still connects [79.30ms]
(pass) MySQL: connectionTimeout bounds the whole handshake, not per packet [1057.49ms]

test/js/sql/postgres-duplicate-auth-request.test.ts:
(pass) postgres: duplicate AuthenticationSASL is rejected, not answered again [120.42ms]
(pass) postgres: duplicate AuthenticationCleartextPassword is rejected, not answered again [62.32ms]
(pass) postgres: duplicate AuthenticationMD5Password is rejected, not answered ag
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     2d1c00e
  features     baseline

22 deps, 108 codegen, 1171 objects in 998ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1234] install /workspace/bun
bun install v1.4.0-canary.1 (1498d7b)

Checked 124 installs across 170 packages (no changes) [21.00ms]
[2/1234] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (1498d7b)

Checked 1 install across 2 packages (no changes) [1.00ms]
[3/1234] install /workspace/bun/src/node-fallbacks
bun install v1.4.0-canary.1 (1498d7b)

Checked 129 installs across 147 packages (no changes) [10.00ms]
[4/1234] gen bindgenv2
[5/1234] gen ErrorCode+*.h
[6/1234] fetch tinycc
[tinycc] up to date
[7/1234] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[8/1234] fetch zlib
[zlib] up to date
[9/1234] fetch picohttpparser
[picohttpparser] up to date
[10/1234] gen .bind.ts → GeneratedBindings.cpp
[11/1234] gen ProcessBindingConstants.lut.h
Generating /workspace/bun/build/release/codegen/ProcessBindingConstants.lut.h from 
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/sql_jsc/mysql/JSMySQLConnection.rs             |   5 +-
 src/sql_jsc/mysql/MySQLConnection.rs               |  26 +-
 src/sql_jsc/postgres/AuthenticationState.rs        |   1 +
 src/sql_jsc/postgres/PostgresSQLConnection.rs      |  34 ++-
 .../js/sql/postgres-duplicate-auth-request.test.ts | 207 +++++++++++++++
 .../js/sql/sql-mysql-duplicate-auth-switch.test.ts | 284 +++++++++++++++++++++
 test/js/sql/wire-frames.ts                         |  16 ++
 7 files changed, 563 insertions(+), 10 deletions(-)
```

</details>

**gate history** · 5 passed · 1 rejected · iteration 4

<details><summary>evidence per changed file</summary>

```
file                                                 reads  edits  tests
src/sql_jsc/mysql/JSMySQLConnection.rs                   4      3      0
src/sql_jsc/mysql/MySQLConnection.rs                    12     14      0
src/sql_jsc/postgres/AuthenticationState.rs              1      1      0
src/sql_jsc/postgres/PostgresSQLConnection.rs            5      7      0
test/js/sql/postgres-duplicate-auth-request.test.ts      1      5      0
test/js/sql/sql-mysql-duplicate-auth-switch.test.ts      3      8      0
test/js/sql/wire-frames.ts                               2      1      0
```

</details>

<!-- robobun:evidence:end -->
…ven-sh#36304)

Fixes oven-sh#23739
Fixes oven-sh#21852

## Problem

In a workspace using a catalog, non-interactive `bun update` never
touched the `catalog`/`catalogs` entries in the root package.json:

```jsonc
// root package.json
{ "workspaces": { "packages": ["packages/*"], "catalog": { "lodash": "4.17.0" } } }
// packages/app/package.json
{ "dependencies": { "lodash": "catalog:" } }
```

```console
$ bun update -r --latest
# "no changes" — catalog.lodash still 4.17.0
```

Worse, running `bun update --latest` from inside a workspace package
rewrote the `catalog:` reference to `^<version>`, silently detaching it
from the catalog. Interactive mode (`bun update -r -i`) already handled
both correctly.

**Root cause:** `edit_update_no_args` only iterates the four dependency
groups of the current package.json; it never looks at
`catalog`/`catalogs`. When it does encounter a `catalog:` value (running
inside a workspace), it treats it like an npm dependency, registers it
in `updating_packages`, and writes the resolved range back over the
`catalog:` literal. Nothing ever edits the root catalog objects.

## Fix

In `PackageJSONEditor.rs`:

* `catalog:`-tagged dependencies are excluded from the value-rewrite
paths (`edit_update_no_args` before/after install, and the `bun update
<pkg>` path in `edit`).
* New `edit_catalogs_before_update` / `edit_catalogs_after_update` walk
the root `catalog`/`catalogs` objects (under `workspaces` or at the top
level, matching `CatalogMap::parse_append`). With `--latest` the entries
are set to a temporary `latest` in the cached root package.json so the
resolver fetches the newest version through the existing `catalog:`
resolution path; after install the resolved version is written back
preserving the `^`/`~`/exact pin. Without `--latest`, ranges move within
range and exact pins stay, matching direct-dependency behavior.

`updatePackageJSONAndInstall.rs` calls these around the install and
handles both run-from-root and run-from-inside-a-workspace (the root
package.json is a different file in the second case and is written
separately), honoring `--dry-run`/`--no-save`. Identity is `(catalog
name, dependency name)`, so the same package in multiple catalogs
updates independently; entries not referenced by any workspace stay
untouched.

`bun add <pkg>` still replaces a `catalog:` reference (adding is an
explicit request to pin a version in that package). `bun update <pkg>`
on a `catalog:` reference keeps the reference and re-resolves within the
catalog range; bumping the catalog entry from a named update is oven-sh#32808 /
oven-sh#32810 territory.

This PR adopts oven-sh#32064 (thank you @CarlosZiegler) on current main with a
small test addition for the `-r` flag from oven-sh#23739.

Also includes a harness fix: bind the verdaccio test registry to
`127.0.0.1` explicitly. A bare port makes verdaccio listen on whatever
`localhost` resolves to (`::1` on hosts that list it first) while the
install client connects to `127.0.0.1`, refusing every request.

## Tests

`test/cli/install/catalogs.test.ts` (new `describe("update")`, verdaccio
registry):

- `--latest` updates default + named catalogs, top-level and
`workspaces.*` locations, with and without `-r`
- run from inside a workspace package updates the root catalog and keeps
`catalog:` refs
- same package in default + named catalogs updates independently;
unreferenced entries unchanged
- plain `bun update` stays in range, does not move exact pins, keeps
refs
- `bun update <pkg> --latest` keeps the catalog reference
- `--dry-run` writes nothing

Fail-before with src/ reverted: 7/8 new tests fail (catalog unchanged,
`catalog:` overwritten with `^2.0.0`). With the fix: 14/14 pass
(including the four pre-existing catalog tests). `bun-update.test.ts`
6/6, `bun-add.test.ts` 54/54, `bun-install-registry.test.ts -t update`
16 pass + 1 todo.

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

---

**[review]** gate passed · iteration 2 · 5 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 8 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/catalogs.test.ts
bun test v1.4.0 (75bcb99)

test/cli/install/catalogs.test.ts:
(pass) basic > both catalog and catalogs in top-level [587.35ms]
(pass) basic > both catalog and catalogs in workspaces [457.07ms]
(pass) basic > detect changes (bun.lockb) [803.98ms]
(pass) basic > detect changes (bun.lock) [881.35ms]
241 |       expect(err).not.toContain("error:");
242 | 
243 |       // catalog entries are updated, preserving the pinning style
244 |       const root = await file(join(packageDir, "package.json")).json();
245 |       const { catalog, catalogs } = isTopLevel ? root : root.workspaces;
246 |       expect(catalog).toEqual({ "no-deps": "^2.0.0" });
                            ^
error: expect(received).toEqual(expected)

  {
-   "no-deps": "^2.0.0",
+   "no-deps": "^1.0.0",
  }

- Expected  - 1
+ Received  + 1

      at <anonymous> (/workspace/bun/test/cli/install/catalogs.test.ts:246:23)
(fail) update > --latest updates catalog versions in top-level [584.67ms]
241 |       expect(err).not.toContain("error:");
24
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (3bfb037)

test/cli/install/catalogs.test.ts:
(pass) basic > both catalog and catalogs in top-level [70.22ms]
(pass) basic > both catalog and catalogs in workspaces [27.96ms]
(pass) basic > detect changes (bun.lockb) [45.77ms]
(pass) basic > detect changes (bun.lock) [43.93ms]
(pass) update > --latest updates catalog versions in top-level [50.49ms]
(pass) update > --latest updates catalog versions in workspaces [41.35ms]
(pass) update > --latest updates catalog versions with -r [43.70ms]
(pass) update > --frozen-lockfile passes after --latest updates catalogs [44.07ms]
(pass) update > --latest run from inside a workspace package updates the root catalog [38.69ms]
(pass) update > --latest updates the same package independently per catalog [34.68ms]
(pass) update > --latest --dry-run does not modify any package.json (from root) [34.78ms]
(pass) update > --latest --dry-run does not modify any package.json (from workspace) [58.05ms]
(pass) update > update without --latest stays in range and keeps catalog references [39.07ms]
(pass) update > update <pkg> --latest keeps the catalog reference [56.67ms]
(pass) errors > fails gracefully when no cat
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/catalogs.test.ts
bun test v1.4.0 (75bcb99)

test/cli/install/catalogs.test.ts:
(pass) basic > both catalog and catalogs in top-level [433.37ms]
(pass) basic > both catalog and catalogs in workspaces [331.82ms]
(pass) basic > detect changes (bun.lockb) [537.51ms]
(pass) basic > detect changes (bun.lock) [552.37ms]
(pass) update > --latest updates catalog versions in top-level [445.45ms]
(pass) update > --latest updates catalog versions in workspaces [399.59ms]
(pass) update > --latest updates catalog versions with -r [404.73ms]
(pass) update > --frozen-lockfile passes after --latest updates catalogs [558.91ms]
(pass) update > --latest run from inside a workspace package updates the root catalog [386.68ms]
(pass) update > --latest updates the same package independently per catalog [411.74ms]
(pass) update > --latest --dry-run does not modify any package.json (from root) [379.27ms]
(pass) update > --latest --dry-run does not modify any package.json (from workspace) [396.85ms]
(pass) update > update without --latest stay
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 695ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/7] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[2/7] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[2/7] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/install/PackageManager.rs                      |  13 +
 src/install/PackageManager/PackageJSONEditor.rs    | 336 ++++++++++++++++++++-
 .../PackageManager/updatePackageJSONAndInstall.rs  | 128 ++++++++
 test/cli/install/catalogs.test.ts                  | 278 +++++++++++++++++
 test/harness.ts                                    |   6 +-
 5 files changed, 756 insertions(+), 5 deletions(-)
```

</details>

**gate history** · 6 passed · 0 rejected · iteration 2

<details><summary>evidence per changed file</summary>

```
file                                                      reads  edits  tests
src/install/PackageManager.rs                                 2      1      0
src/install/PackageManager/PackageJSONEditor.rs               9      8      0
…c/install/PackageManager/updatePackageJSONAndInstall.rs      8      7      0
test/cli/install/catalogs.test.ts                             3      5      0
test/harness.ts                                               2      1      0
```

</details>

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

---------

Co-authored-by: Carlos Ricardo Ziegler <38855507+CarlosZiegler@users.noreply.github.com>
PR oven-sh#3103 (May 2023) added this conversion together with a Zig loop-else
bug that permanently disabled it: the trivial-property validation
loop's only exit is `return null` — no `break` — so the `else` branch,
intended as the empty-object de-opt, ran after every completed loop and
the rewrite code was unreachable from day one. The Rust port mirrored
the shipped behavior and deleted the dead rewrite code.

Reconstruct the rewrite from the pre-rewrite Zig (maybe.zig at
23427db^), with two deliberate changes:
- set esm_export_keyword like the live `exports.<name> = ...`
  conversion in visit_stmt.rs does (the never-run Zig omitted it), and
- emit only one export clause per key, so a duplicate key in the object
  literal ({ foo: 1, foo: 2 }) reassigns the ref (last-wins) instead of
  producing a duplicate `export { $foo as foo }`.

The empty-object case keeps de-opting, now via an explicit
props.is_empty() check. cjs2esm/UnwrappedModuleRequireAssigned's
__toESM assertion is updated: the fixture's `module.exports =
{ react: "react" }` now unwraps fully, so no interop helper remains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Follow-up to the restoration commit, for the rebase onto current main.

Two fixes:

1. new_symbol no longer returns Result (oven-sh#34795 dropped it), so the
   restored code's `.expect("unreachable")` stopped compiling. Drop it,
   matching the live `exports.<name> = ...` path in the same file.

2. De-opt inside unbraced if/while/do bodies. The conversion replaces
   the assignment with an empty expression and splices the decls in as
   sibling statements, so a body with nowhere to splice printed a bare
   `= { a: 1 };` — invalid syntax, and the export was silently dropped:

       if (process.env.NEVER_SET)
          = { a: 1 };

   The `module_scope != current_scope` guard does not catch this because
   if/while/do push no scope, so inside their unbraced body the scope
   check still reads as top-level. Reuse the is_inside_single_stmt_body
   flag oven-sh#35458 added for the sibling `exports.<name> = ...` path, which
   has the same shape. Now de-opts to the __commonJS wrapper.

   The gap predates the port — the 2023 Zig had it too — but could not
   manifest while the conversion was dead code.

   oven-sh#35458's noNestedExport helper does not catch this on its own (the
   broken output contains no `export` clause at all), so the new test
   also asserts there is no orphan `= ` and that the bundle runs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@crishoj
crishoj force-pushed the claude/restore-cjs-object-named-exports branch from 0ba59f0 to 962c31b Compare July 29, 2026 12:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants