Skip to content

feat(io): Add append option to Bun.write, BunFile.write and FileSink (BunFile.writer) - #25751

Closed
mattermoran wants to merge 9 commits into
oven-sh:mainfrom
mattermoran:feat/bun-write-append
Closed

mattermoran wants to merge 9 commits into
oven-sh:mainfrom
mattermoran:feat/bun-write-append

Conversation

@mattermoran

@mattermoran mattermoran commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor

Closes #10473
Closes #16768

Add support for appending with .write() without truncating the file by adding an append option.

Essentially it just replaces the truncate flag with append. The fast write path is skipped when appending and file to file copies use read write fallback instead of optimized syscalls.

  • Added append?: boolean option to Bun.write() and BunFile.write()
  • Added append?: boolean option to FileSink (Bun.file().writer())
  • Added support for ReadableStream as a source for .write()
  • Aligned supported source types between Bun.write and BunFile.write
  • Added all the necessary tests

@mattermoran
mattermoran requested a review from alii as a code owner December 30, 2025 00:42
@coderabbitai

coderabbitai Bot commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds an append option across public typings and internal write/copy paths; threads the flag through file open/create logic to choose APPEND vs TRUNC modes, disables fast-paths when appending, updates FileSink/writer behavior, and adds tests for append semantics.

Changes

Cohort / File(s) Summary
Type definitions
packages/bun-types/bun.d.ts
Add append?: boolean to Bun.write overloads, BunFile.write, and writer options; expand input unions to include ReadableStream, Request, Response, and BunFile.
Blob write core (Zig)
src/bun.js/webcore/Blob.zig, src/bun.js/webcore/blob/write_file.zig, src/bun.js/webcore/blob/copy_file.zig
Add append: bool fields/params to WriteFile/WriteFileWindows/CopyFile; introduce getOpenFlags/openDestinationFlags; thread append through create/open/write/copy flows; gate/disable clonefile/fast-paths when appending and enable read-write fallback.
FileSink / streams (Zig)
src/bun.js/webcore/FileSink.zig, src/bun.js/webcore/streams.zig
Replace truncate with append in FileSink.Options; compute open flags from append; parse append from JS and propagate through all FileSink construction paths.
S3 write adjustments (Zig)
src/bun.js/webcore/S3Client.zig, src/bun.js/webcore/S3File.zig
Explicitly pass append = false into Blob.writeFileInternal for S3-backed writes to preserve overwrite semantics.
Public API wiring (Zig)
src/bun.js/webcore/Blob.zig (WriteFileOptions, pipeReadableStreamToBlob)
Add append to WriteFileOptions and to pipeReadableStreamToBlob signature; propagate append through public write APIs.
Tests
test/js/bun/io/bun-write-append.test.ts
Add tests covering append: true and append: false across Bun.write, Bun.file().write, streams, Response, and typed arrays; validate creation, append vs truncate behavior, and final content/size.
Misc wiring
various Zig call sites ...
Threaded append flag through multiple call sites and tasks (WriteFileWaitFromLockedValueTask, writer paths, pipe/piping flows) to ensure consistent behavior.

Possibly related PRs

Suggested reviewers

  • alii
  • pfgithub
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and concisely describes the main feature added: an append option to Bun.write, BunFile.write, and FileSink.
Description check ✅ Passed The PR description covers the objectives with specific details about what was changed, though it could reference the template sections more explicitly.
Linked Issues check ✅ Passed The PR implementation directly addresses both linked issues by adding append: boolean flag to Bun.write, BunFile.write, and FileSink.
Out of Scope Changes check ✅ Passed All changes are within scope: append support across write APIs, FileSink bug fix, ReadableStream source support alignment, and comprehensive tests.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/bun.js/webcore/Blob.zig (1)

1050-1072: CRITICAL: File-to-file copy path doesn't support append mode.

When both source and destination are file-backed blobs, the code uses an optimized file copy path (lines 1051-1072). However, this path doesn't check the append flag from options, meaning Bun.write(destFile, srcFile, { append: true }) will silently overwrite the destination instead of appending to it.

Either:

  1. Skip this optimization when append is true and fall through to the bytes-based write path, or
  2. Return an error indicating that file-to-file append is not supported
🔎 Proposed fix to skip optimization for append mode
     }
     // If this is file <> file, we can just copy the file
-    else if (destination_type == .file and source_type == .file) {
+    else if (destination_type == .file and source_type == .file and (options.append orelse false) == false) {
         if (comptime Environment.isWindows) {
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 538be13 and 91b2734.

📒 Files selected for processing (4)
  • packages/bun-types/bun.d.ts
  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/blob/write_file.zig
  • test/js/bun/io/bun-write-append.test.ts
🧰 Additional context used
📓 Path-based instructions (5)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Use bun:test with files that end in *.test.{ts,js,jsx,tsx,mjs,cjs}
Do not write flaky tests. Never wait for time to pass in tests; always wait for the condition to be met instead of using an arbitrary amount of time
Never use hardcoded port numbers in tests. Always use port: 0 to get a random port
Prefer concurrent tests over sequential tests using test.concurrent or describe.concurrent when multiple tests spawn processes or write files, unless it's very difficult to make them concurrent
When spawning Bun processes in tests, use bunExe and bunEnv from harness to ensure the same build of Bun is used and debug logging is silenced
Use -e flag for single-file tests when spawning Bun processes
Use tempDir() from harness to create temporary directories with files for multi-file tests instead of creating files manually
Prefer async/await over callbacks in tests
When callbacks must be used and it's just a single callback, use Promise.withResolvers to create a promise that can be resolved or rejected from a callback
Do not set a timeout on tests. Bun already has timeouts
Use Buffer.alloc(count, fill).toString() instead of 'A'.repeat(count) to create repetitive strings in tests, as ''.repeat is very slow in debug JavaScriptCore builds
Use describe blocks for grouping related tests
Always use await using or using to ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc
Always check exit codes and test error scenarios in error tests
Use describe.each() for parameterized tests
Use toMatchSnapshot() for snapshot testing
Use beforeAll(), afterEach(), beforeEach() for setup/teardown in tests
Track resources (servers, clients) in arrays for cleanup in afterEach()

Files:

  • test/js/bun/io/bun-write-append.test.ts
**/*.test.ts?(x)

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.ts?(x): Never use bun test directly - always use bun bd test to run tests with debug build changes
For single-file tests, prefer -e flag over tempDir
For multi-file tests, prefer tempDir and Bun.spawn over single-file tests
Use normalizeBunSnapshot to normalize snapshot output of tests
Never write tests that check for 'panic', 'uncaught exception', or similar strings in test output
Use tempDir from harness to create temporary directories - do not use tmpdirSync or fs.mkdtempSync
When spawning processes in tests, expect stdout before expecting exit code for more useful error messages on test failure
Do not write flaky tests - do not use setTimeout in tests; instead await the condition to be met
Verify tests fail with USE_SYSTEM_BUN=1 bun test <file> and pass with bun bd test <file> - tests are invalid if they pass with USE_SYSTEM_BUN=1
Test files must end with .test.ts or .test.tsx
Avoid shell commands like find or grep in tests - use Bun's Glob and built-in tools instead

Files:

  • test/js/bun/io/bun-write-append.test.ts
test/**/*.test.ts?(x)

📄 CodeRabbit inference engine (CLAUDE.md)

Always use port: 0 in tests - do not hardcode ports or use custom random port number functions

Files:

  • test/js/bun/io/bun-write-append.test.ts
src/**/*.zig

📄 CodeRabbit inference engine (src/CLAUDE.md)

src/**/*.zig: Private fields in Zig are fully supported using the # prefix: struct { #foo: u32 };
Use decl literals in Zig for declaration initialization: const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer @import at the bottom of the file (auto formatter will move them automatically)

Files:

  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/blob/write_file.zig
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

In Zig code, be careful with allocators and use defer for cleanup

Files:

  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/blob/write_file.zig
🧠 Learnings (20)
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
  • packages/bun-types/bun.d.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : For multi-file tests, prefer `tempDir` and `Bun.spawn` over single-file tests

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` with files that end in `*.test.{ts,js,jsx,tsx,mjs,cjs}`

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-19T02:44:46.354Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/context-propagation.test.ts:1-1
Timestamp: 2025-10-19T02:44:46.354Z
Learning: In the Bun repository, standalone packages under packages/ (e.g., bun-vscode, bun-inspector-protocol, bun-plugin-yaml, bun-plugin-svelte, bun-debug-adapter-protocol, bun-otel) co-locate their tests with package source code using *.test.ts files. This follows standard npm/monorepo patterns. The test/ directory hierarchy (test/js/bun/, test/cli/, test/js/node/) is reserved for testing Bun's core runtime APIs and built-in functionality, not standalone packages.

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Verify tests fail with `USE_SYSTEM_BUN=1 bun test <file>` and pass with `bun bd test <file>` - tests are invalid if they pass with USE_SYSTEM_BUN=1

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/js/node/test/{parallel,sequential}/*.js : For test/js/node/test/{parallel,sequential}/*.js files without a .test extension, use `bun bd <file>` instead of `bun bd test <file>` since these expect exit code 0 and don't use bun's test runner

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : When spawning Bun processes in tests, use `bunExe` and `bunEnv` from `harness` to ensure the same build of Bun is used and debug logging is silenced

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `-e` flag for single-file tests when spawning Bun processes

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Never use `bun test` directly - always use `bun bd test` to run tests with debug build changes

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Always use `await using` or `using` to ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `tempDir()` from harness to create temporary directories with files for multi-file tests instead of creating files manually

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.

Applied to files:

  • packages/bun-types/bun.d.ts
  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().

Applied to files:

  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations

Applied to files:

  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive already maintains internal state to prevent issues from multiple ref/unref calls, so additional idempotence guards are not needed when calling poll_ref.ref() and poll_ref.unref().

Applied to files:

  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive uses a simple state machine (active/inactive/done) rather than reference counting, with internal status field preventing issues from multiple ref/unref calls, making additional idempotence guards unnecessary.

Applied to files:

  • src/bun.js/webcore/blob/write_file.zig
🔇 Additional comments (3)
test/js/bun/io/bun-write-append.test.ts (1)

1-51: Append behavior tests are clear, isolated, and follow harness conventions

These four tests exercise both Bun.write and Bun.file().write with append: true for existing and non‑existent files, use tempDir + using correctly, and assert both content and length. No issues spotted.

src/bun.js/webcore/Blob.zig (2)

1206-1210: LGTM: WriteFileOptions extended with append field.

The addition of the append field to WriteFileOptions is correctly implemented with an appropriate default value of null, and it's properly threaded through to the underlying WriteFile and WriteFileWindows constructors.


4609-4617: Verify that all callers of FileOpener implement getOpenFlags() correctly.

The new getOpenFlagsForContext helper dynamically determines open flags by checking if the context has:

  1. A getOpenFlags() method (preferred), or
  2. An open_flags field (fallback)

For append functionality to work correctly, contexts using FileOpener must implement getOpenFlags() to return the appropriate flags (including O_APPEND when needed).

Please verify that:

  1. WriteFile implements getOpenFlags(this: *const WriteFile) c_int
  2. WriteFileWindows implements a similar method
  3. These methods correctly check the append field and return O_APPEND instead of O_TRUNC when append == true

Comment thread src/bun.js/webcore/Blob.zig Resolved
Comment thread src/bun.js/webcore/blob/write_file.zig Resolved

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this

We need to handle the separate code path for when both src and dest are a file, like Bun.write(Bun.file(a), Bun.file(b), { append: true }). Instead we should make it use the read write fallback codepath for that case I think? Ideally we would simply append the contents and that is possible to do, I think for linux in most cases but it's tricky and will need to be tested. I don't think it's doable on macOS or Windows.

Comment thread src/bun.js/webcore/Blob.zig Resolved
Comment thread src/bun.js/webcore/Blob.zig Resolved
Comment thread src/bun.js/webcore/Blob.zig Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/bun.js/webcore/Blob.zig (1)

1051-1071: File-to-file copy silently ignores append option.

The PR description states that file-to-file copies are not supported in append mode, but this code path doesn't validate or throw an error when options.append is true. Users attempting Bun.write(fileA, fileB, { append: true }) will have their append option silently ignored.

Consider adding validation before the copy:

🔎 Proposed fix
     // If this is file <> file, we can just copy the file
     else if (destination_type == .file and source_type == .file) {
+        if (options.append orelse false) {
+            return globalThis.throwInvalidArguments("Cannot use append option with file-to-file copy. Read the source file first, then write with append.", .{});
+        }
         if (comptime Environment.isWindows) {
♻️ Duplicate comments (2)
src/bun.js/webcore/Blob.zig (2)

1548-1553: Use getBooleanLoose instead of getTruthy as previously suggested.

A previous reviewer (Jarred-Sumner) suggested using getBooleanLoose here for parsing the boolean option.

🔎 Proposed fix
-            if (try options_object.getTruthy(globalThis, "append")) |append_value| {
-                if (!append_value.isBoolean()) {
-                    return globalThis.throwInvalidArgumentType("write", "options.append", "boolean");
-                }
-                append = append_value.toBoolean();
-            }
+            if (try options_object.getBooleanLoose(globalThis, "append")) |append_value| {
+                append = append_value;
+            }

2312-2317: Use getBooleanLoose instead of getTruthy as previously suggested.

A previous reviewer (Jarred-Sumner) suggested using getBooleanLoose here for parsing the boolean option.

🔎 Proposed fix
-            if (try options_object.getTruthy(globalThis, "append")) |append_value| {
-                if (!append_value.isBoolean()) {
-                    return globalThis.throwInvalidArgumentType("write", "options.append", "boolean");
-                }
-                append = append_value.toBoolean();
-            }
+            if (try options_object.getBooleanLoose(globalThis, "append")) |append_value| {
+                append = append_value;
+            }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 91b2734 and a60a9d6.

📒 Files selected for processing (1)
  • src/bun.js/webcore/Blob.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig

📄 CodeRabbit inference engine (src/CLAUDE.md)

src/**/*.zig: Private fields in Zig are fully supported using the # prefix: struct { #foo: u32 };
Use decl literals in Zig for declaration initialization: const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer @import at the bottom of the file (auto formatter will move them automatically)

Files:

  • src/bun.js/webcore/Blob.zig
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

In Zig code, be careful with allocators and use defer for cleanup

Files:

  • src/bun.js/webcore/Blob.zig
🧠 Learnings (8)
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-16T17:32:03.074Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/install/PackageManager/PackageManagerOptions.zig:187-193
Timestamp: 2025-10-16T17:32:03.074Z
Learning: In Bun's codebase (particularly in files like src/install/PackageManager/PackageManagerOptions.zig), mixing bun.EnvVar.*.get() and bun.EnvVar.*.platformGet() for environment variable lookups is intentional and safe. The code is protected by compile-time platform checks (Environment.isWindows, etc.), and compilation will fail if the wrong function is used on the wrong platform. This pattern should not be flagged as a consistency issue.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes

Applied to files:

  • src/bun.js/webcore/Blob.zig
🔇 Additional comments (3)
src/bun.js/webcore/Blob.zig (3)

4609-4617: Clean helper for dynamic open flag selection.

The getOpenFlagsForContext helper nicely encapsulates the logic for determining open flags by checking for a getOpenFlags method first, then falling back to open_flags field, and finally defaulting to RDONLY. This enables WriteFile to dynamically compute flags based on the append setting.


1256-1265: Fast path correctly bypassed for append operations.

The logic to skip the fast path when options.append is true is correct since the fast path uses O_CREAT | O_WRONLY without O_APPEND. Append operations require the async path that properly handles the O_APPEND flag.


1024-1039: Append option correctly propagated to WriteFile constructors.

The options.append orelse false is properly passed to both WriteFileWindows.create and WriteFile.create, enabling the underlying write logic to set appropriate flags.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/bun.js/webcore/Blob.zig (2)

1050-1071: File-to-file copy silently ignores append option.

When both source and destination are files, the code uses CopyFile which doesn't receive or handle the append parameter. The PR summary states "file-to-file copies are not supported in append mode", but currently the append flag is silently ignored rather than rejected.

Consider adding an explicit check to throw an error when append mode is requested for file-to-file copies:

🔎 Proposed fix
     // If this is file <> file, we can just copy the file
     else if (destination_type == .file and source_type == .file) {
+        if (options.append) {
+            return globalThis.throwInvalidArguments("Append mode is not supported for file-to-file copies", .{});
+        }
         if (comptime Environment.isWindows) {
             return Blob.copy_file.CopyFileWindows.init(

850-862: Empty source incorrectly truncates file in append mode.

When options.append is true but the source is empty (triggering this function), the file is still truncated to 0 bytes. Appending empty data should leave the file unchanged.

🔎 Proposed fix
 fn writeFileWithEmptySourceToDestination(ctx: *jsc.JSGlobalObject, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!jsc.JSValue {
     // SAFETY: null-checked by caller
     const destination_store = destination_blob.store.?;
     defer destination_blob.detach();

     switch (destination_store.data) {
         .file => |file| {
+            // In append mode with empty source, the file should remain unchanged
+            if (options.append) {
+                return jsc.JSPromise.resolvedPromiseValue(ctx, jsc.JSValue.jsNumber(0));
+            }
             // TODO: make this async
             const node_fs = ctx.bunVM().nodeFS();
             var result = node_fs.truncate(.{
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a60a9d6 and 628c050.

📒 Files selected for processing (1)
  • src/bun.js/webcore/Blob.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig

📄 CodeRabbit inference engine (src/CLAUDE.md)

src/**/*.zig: Private fields in Zig are fully supported using the # prefix: struct { #foo: u32 };
Use decl literals in Zig for declaration initialization: const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer @import at the bottom of the file (auto formatter will move them automatically)

Files:

  • src/bun.js/webcore/Blob.zig
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

In Zig code, be careful with allocators and use defer for cleanup

Files:

  • src/bun.js/webcore/Blob.zig
🧠 Learnings (8)
📓 Common learnings
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `-e` flag for single-file tests when spawning Bun processes
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` with files that end in `*.test.{ts,js,jsx,tsx,mjs,cjs}`
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes

Applied to files:

  • src/bun.js/webcore/Blob.zig
🔇 Additional comments (6)
src/bun.js/webcore/Blob.zig (6)

1206-1210: LGTM!

The append: bool field is appropriately added to WriteFileOptions. All call sites explicitly provide this value.


1255-1266: LGTM!

The fast path correctly skips when append is true, ensuring append operations go through the async write path that properly handles append semantics with the appropriate open flags.


1537-1559: LGTM!

The append option parsing in writeFile is well-implemented:

  • Defaults to false for backward compatibility
  • Uses getBooleanLoose per reviewer suggestion
  • Properly threads the value through to writeFileInternal

2275-2322: LGTM!

The append option handling in doWrite (for BunFile.write) mirrors the implementation in writeFile (for Bun.write), ensuring consistent behavior across both APIs.


1022-1040: LGTM!

The append flag is correctly passed to both Windows and non-Windows write file implementations.


3603-3665: LGTM!

The getOpenFlagsForContext helper provides a clean abstraction for computing open flags:

  1. First checks for a getOpenFlags() instance method (allowing dynamic flag computation based on options like append)
  2. Falls back to a static open_flags constant
  3. Defaults to RDONLY if neither exists

This enables write implementations to dynamically include O_APPEND when needed.

@mattermoran
mattermoran force-pushed the feat/bun-write-append branch from d123fc4 to cc203b1 Compare December 30, 2025 22:38
@mattermoran

mattermoran commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor Author

@Jarred-Sumner good suggestion about read write loop. seems to be working just fine.

while doing that I ended up adding append to FileSink as well so now there's also Bun.file().writer({append: true}).

noticed a weird thing though: FileSink has the truncate option with default set to true but it was never actually set when called and it wasn't even used when setting the open flags. getting a writer for existing file would start writing from beginning without truncating so the file would end up corrupted.
I suppose it's a bug so now it always truncates when not append: true.

Also fixed an inconsistency with source types between Bun.write and BunFile.write. Now they support same types. While on it ended up adding support for ReadableStream as a source. It was being incorrectly stringified.

As for os optimized appends I will take investigate that separately.

p.s the size caching issue is more noticeable now with appends because grabbing a file, appending and checking the content will keep returning the old one but #25702 addresses that

@mattermoran mattermoran changed the title feat(io): Add append option to Bun.write and BunFile.write feat(io): Add append option to Bun.write, BunFile.write and BunFile.writer Dec 30, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/bun.js/webcore/Blob.zig (2)

2420-2450: S3 path silently ignores append parameter.

The pipeReadableStreamToBlob function accepts an append parameter but when the destination is S3, it ignores the flag entirely. S3 object storage doesn't support append semantics natively.

Consider throwing an error when append: true is used with S3 destinations to avoid silent data loss where users expect append behavior but get overwrite behavior instead.

🔎 Proposed fix
 pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *jsc.JSGlobalObject, readable_stream: jsc.WebCore.ReadableStream, extra_options: ?JSValue, append: bool) bun.JSError!jsc.JSValue {
     var store = this.store orelse {
         return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Blob is detached", .{}));
     };

     if (this.isS3()) {
+        if (append) {
+            return globalThis.throwInvalidArguments("Append mode is not supported for S3 files", .{});
+        }
         const s3 = &this.store.?.data.s3;

2651-2712: S3 path in getWriter ignores append option.

Similar to pipeReadableStreamToBlob, the S3 path in getWriter doesn't check the append flag. When users call file.writer({ append: true }) on an S3 file, the option is silently ignored.

🔎 Proposed fix
     if (this.isS3()) {
+        if (append) {
+            return globalThis.throwInvalidArguments("Append mode is not supported for S3 files", .{});
+        }
         const s3 = &this.store.?.data.s3;
         const path = s3.path();
packages/bun-types/bun.d.ts (1)

724-749: Bun.write append typings look correct; consider tightening docs around overwrite vs append semantics

  • Extending the main write(destination: BunFile | S3File | PathLike, …) overload to accept ReadableStream | Request and threading append?: boolean through all the relevant overload option objects is type‑safe and matches the described behavior (default false preserves existing truncate semantics).
  • The notes on the file‑to‑file overloads (“When append: true, the optimized copy is not used”) are helpful and correctly scoped.

One minor docs nit: the JSDoc for the Response overloads and the copy overloads still state that the destination “will be overwritten / truncated” without mentioning the append escape hatch. Consider adding a short clarification that those overwrite/truncate statements apply when append is omitted/false so the comments stay strictly accurate now that append is supported.

Also applies to: 763-784, 796-817, 830-831, 874-875, 840-861, 883-905

♻️ Duplicate comments (1)
src/bun.js/webcore/blob/write_file.zig (1)

25-35: Append flag integration in WriteFile and open‑flag computation look good

Adding append: bool = false to WriteFile, threading it through createWithCtx / create, and using getOpenFlags() to switch between O.APPEND and O.TRUNC while preserving NONBLOCK|CREAT|WRONLY maintains backwards‑compatible defaults and cleanly encodes append semantics for POSIX writes. No new issues spotted in this path.

Also applies to: 78-99, 100-123

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 628c050 and cc203b1.

📒 Files selected for processing (9)
  • packages/bun-types/bun.d.ts
  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/FileSink.zig
  • src/bun.js/webcore/S3Client.zig
  • src/bun.js/webcore/S3File.zig
  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/blob/write_file.zig
  • src/bun.js/webcore/streams.zig
  • test/js/bun/io/bun-write-append.test.ts
🧰 Additional context used
📓 Path-based instructions (5)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Use bun:test with files that end in *.test.{ts,js,jsx,tsx,mjs,cjs}
Do not write flaky tests. Never wait for time to pass in tests; always wait for the condition to be met instead of using an arbitrary amount of time
Never use hardcoded port numbers in tests. Always use port: 0 to get a random port
Prefer concurrent tests over sequential tests using test.concurrent or describe.concurrent when multiple tests spawn processes or write files, unless it's very difficult to make them concurrent
When spawning Bun processes in tests, use bunExe and bunEnv from harness to ensure the same build of Bun is used and debug logging is silenced
Use -e flag for single-file tests when spawning Bun processes
Use tempDir() from harness to create temporary directories with files for multi-file tests instead of creating files manually
Prefer async/await over callbacks in tests
When callbacks must be used and it's just a single callback, use Promise.withResolvers to create a promise that can be resolved or rejected from a callback
Do not set a timeout on tests. Bun already has timeouts
Use Buffer.alloc(count, fill).toString() instead of 'A'.repeat(count) to create repetitive strings in tests, as ''.repeat is very slow in debug JavaScriptCore builds
Use describe blocks for grouping related tests
Always use await using or using to ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc
Always check exit codes and test error scenarios in error tests
Use describe.each() for parameterized tests
Use toMatchSnapshot() for snapshot testing
Use beforeAll(), afterEach(), beforeEach() for setup/teardown in tests
Track resources (servers, clients) in arrays for cleanup in afterEach()

Files:

  • test/js/bun/io/bun-write-append.test.ts
**/*.test.ts?(x)

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.ts?(x): Never use bun test directly - always use bun bd test to run tests with debug build changes
For single-file tests, prefer -e flag over tempDir
For multi-file tests, prefer tempDir and Bun.spawn over single-file tests
Use normalizeBunSnapshot to normalize snapshot output of tests
Never write tests that check for 'panic', 'uncaught exception', or similar strings in test output
Use tempDir from harness to create temporary directories - do not use tmpdirSync or fs.mkdtempSync
When spawning processes in tests, expect stdout before expecting exit code for more useful error messages on test failure
Do not write flaky tests - do not use setTimeout in tests; instead await the condition to be met
Verify tests fail with USE_SYSTEM_BUN=1 bun test <file> and pass with bun bd test <file> - tests are invalid if they pass with USE_SYSTEM_BUN=1
Test files must end with .test.ts or .test.tsx
Avoid shell commands like find or grep in tests - use Bun's Glob and built-in tools instead

Files:

  • test/js/bun/io/bun-write-append.test.ts
test/**/*.test.ts?(x)

📄 CodeRabbit inference engine (CLAUDE.md)

Always use port: 0 in tests - do not hardcode ports or use custom random port number functions

Files:

  • test/js/bun/io/bun-write-append.test.ts
src/**/*.zig

📄 CodeRabbit inference engine (src/CLAUDE.md)

src/**/*.zig: Private fields in Zig are fully supported using the # prefix: struct { #foo: u32 };
Use decl literals in Zig for declaration initialization: const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer @import at the bottom of the file (auto formatter will move them automatically)

Files:

  • src/bun.js/webcore/S3File.zig
  • src/bun.js/webcore/streams.zig
  • src/bun.js/webcore/blob/write_file.zig
  • src/bun.js/webcore/S3Client.zig
  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/FileSink.zig
  • src/bun.js/webcore/blob/copy_file.zig
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

In Zig code, be careful with allocators and use defer for cleanup

Files:

  • src/bun.js/webcore/S3File.zig
  • src/bun.js/webcore/streams.zig
  • src/bun.js/webcore/blob/write_file.zig
  • src/bun.js/webcore/S3Client.zig
  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/FileSink.zig
  • src/bun.js/webcore/blob/copy_file.zig
🧠 Learnings (26)
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` with files that end in `*.test.{ts,js,jsx,tsx,mjs,cjs}`

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : For multi-file tests, prefer `tempDir` and `Bun.spawn` over single-file tests

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-19T02:44:46.354Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/context-propagation.test.ts:1-1
Timestamp: 2025-10-19T02:44:46.354Z
Learning: In the Bun repository, standalone packages under packages/ (e.g., bun-vscode, bun-inspector-protocol, bun-plugin-yaml, bun-plugin-svelte, bun-debug-adapter-protocol, bun-otel) co-locate their tests with package source code using *.test.ts files. This follows standard npm/monorepo patterns. The test/ directory hierarchy (test/js/bun/, test/cli/, test/js/node/) is reserved for testing Bun's core runtime APIs and built-in functionality, not standalone packages.

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/js/node/test/{parallel,sequential}/*.js : For test/js/node/test/{parallel,sequential}/*.js files without a .test extension, use `bun bd <file>` instead of `bun bd test <file>` since these expect exit code 0 and don't use bun's test runner

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Verify tests fail with `USE_SYSTEM_BUN=1 bun test <file>` and pass with `bun bd test <file>` - tests are invalid if they pass with USE_SYSTEM_BUN=1

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `-e` flag for single-file tests when spawning Bun processes

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : When spawning Bun processes in tests, use `bunExe` and `bunEnv` from `harness` to ensure the same build of Bun is used and debug logging is silenced

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
  • packages/bun-types/bun.d.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Use `normalizeBunSnapshot` to normalize snapshot output of tests

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Always use `await using` or `using` to ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-06T00:58:23.965Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24417
File: test/js/bun/spawn/spawn.test.ts:903-918
Timestamp: 2025-11-06T00:58:23.965Z
Learning: In Bun test files, `await using` with spawn() is appropriate for long-running processes that need guaranteed cleanup on scope exit or when explicitly testing disposal behavior. For short-lived processes that exit naturally (e.g., console.log scripts), the pattern `const proc = spawn(...); await proc.exited;` is standard and more common, as evidenced by 24 instances vs 4 `await using` instances in test/js/bun/spawn/spawn.test.ts.

Applied to files:

  • test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().

Applied to files:

  • src/bun.js/webcore/streams.zig
  • src/bun.js/webcore/FileSink.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations

Applied to files:

  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive already maintains internal state to prevent issues from multiple ref/unref calls, so additional idempotence guards are not needed when calling poll_ref.ref() and poll_ref.unref().

Applied to files:

  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive uses a simple state machine (active/inactive/done) rather than reference counting, with internal status field preventing issues from multiple ref/unref calls, making additional idempotence guards unnecessary.

Applied to files:

  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-19T19:55:22.427Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 22568
File: src/valkey/js_valkey_functions.zig:853-854
Timestamp: 2025-09-19T19:55:22.427Z
Learning: In Bun's JSPromise API, `resolvedPromiseValue(globalThis: *JSGlobalObject, value: JSValue) JSValue` returns a JSValue directly (not a JSPromise that needs `.toJS()` called on it). This is different from `resolvedPromise()` which returns a *JSPromise that would need `.toJS()`.

Applied to files:

  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-11-24T18:37:47.899Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/AGENTS.md:0-0
Timestamp: 2025-11-24T18:37:47.899Z
Learning: Applies to src/bun.js/bindings/v8/**/<UNKNOWN> : <UNKNOWN>

Applied to files:

  • src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.

Applied to files:

  • src/bun.js/webcore/FileSink.zig
  • packages/bun-types/bun.d.ts
📚 Learning: 2025-09-02T18:25:27.976Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 22227
File: src/allocators/allocation_scope.zig:284-314
Timestamp: 2025-09-02T18:25:27.976Z
Learning: In bun's custom Zig implementation, the `#` prefix for private fields is valid syntax and should not be flagged as invalid. The syntax `#fieldname` creates private fields that cannot be accessed from outside the defining struct, and usage like `self.#fieldname` is correct within the same struct. This applies to fields like `#parent`, `#state`, `#allocator`, `#trace`, etc. throughout the codebase.

Applied to files:

  • src/bun.js/webcore/FileSink.zig
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664

Applied to files:

  • packages/bun-types/bun.d.ts
🔇 Additional comments (32)
src/bun.js/webcore/S3File.zig (1)

126-169: LGTM: S3 writes correctly disable append.

Both write paths (path-backed and blob-backed) explicitly set append = false, which correctly reflects that S3 writes don't support append semantics.

src/bun.js/webcore/S3Client.zig (1)

211-232: LGTM: S3Client write correctly disables append.

Consistent with S3File changes, append is explicitly disabled for S3 write operations.

test/js/bun/io/bun-write-append.test.ts (3)

5-15: LGTM: Well-structured append test.

Test correctly verifies that append: true appends to existing content and checks both content and size.


124-136: LGTM: Important truncation test.

This test verifies that append: false properly truncates existing content, ensuring the default truncate behavior is preserved.


138-148: LGTM: Critical edge case test.

This test ensures that empty writes with append: true don't truncate the file, which is important for preserving file content when no new data is written.

src/bun.js/webcore/FileSink.zig (1)

49-60: LGTM: Append flag correctly replaces truncate with inverted logic.

The field change from truncate: bool = true to append: bool = false maintains backward compatibility while adding append support. The flags() function correctly maps:

  • append = false → O.TRUNC (default: overwrite)
  • append = true → O.APPEND (new: append)
src/bun.js/webcore/streams.zig (2)

123-128: LGTM: Append flag parsing is safe and correct.

Default value is false, and the flag is only set to true if explicitly provided as a boolean in JS options.


115-182: LGTM: Append flag consistently propagated through all FileSink construction paths.

The append flag is correctly threaded through all three FileSink construction scenarios:

  1. Path-based (line 143)
  2. FD-based (line 163)
  3. Default/fallback (line 179)

This ensures append behavior works regardless of how the FileSink is constructed.

src/bun.js/webcore/Blob.zig (11)

855-858: LGTM!

The early return for append mode with empty source is correct—appending nothing should leave the file unchanged and return 0 bytes written.


1029-1086: LGTM!

The append option is consistently propagated through all write paths (WriteFileWindows, WriteFile, CopyFileWindows, CopyFile, and pipeReadableStreamToBlob).


1213-1217: LGTM!

The append: bool field is correctly added to WriteFileOptions. All call sites explicitly initialize this field.


1263-1272: LGTM!

Correctly skipping the fast path for append operations—the fast path doesn't support append semantics since it opens files without O_APPEND.


1415-1425: LGTM!

The append flag is correctly propagated to WriteFileWaitFromLockedValueTask for deferred body handling.


1492-1498: LGTM!

ReadableStream handling correctly propagates the append flag to pipeReadableStreamToBlob.


1554-1574: LGTM!

Good implementation following the pattern suggested in past reviews: initializing append to false and using getBooleanLoose to parse the option.


2292-2337: LGTM!

The doWrite method correctly handles the append option with the same pattern as writeFile, maintaining API consistency between Bun.write() and BunFile.write().


2640-2646: LGTM!

The getWriter method correctly parses the append option, enabling append mode for file writers.


4629-4637: LGTM!

Good abstraction for determining open flags. The function correctly checks for a getOpenFlags method first (allowing dynamic flags based on append mode), falls back to a static open_flags field, then defaults to read-only. This cleanly supports the append feature without duplicating flag logic.


4673-4691: LGTM!

The getOpenFlagsForContext(this) calls correctly use the new abstraction in both Windows and non-Windows file opening paths, enabling append mode support.

packages/bun-types/bun.d.ts (1)

1324-1335: BunFile.writer/write append surface matches Bun.write and looks consistent

The new append?: boolean option on BunFile.writer() and BunFile.write() is wired consistently with the top‑level Bun.write overloads (same default and JSDoc contract), and the expanded data union (including ReadableStream, Request, Response, BunFile) aligns with the runtime behavior described elsewhere. No type‑level issues spotted here.

Also applies to: 1376-1399

src/bun.js/webcore/blob/write_file.zig (2)

360-361: Windows append semantics and flag plumbing are consistent with POSIX path

On the Windows side, the new append: bool field is correctly:

  • Captured in createWithCtx/create and stored on the struct.
  • Reflected in open() via flags choosing uv.O.APPEND vs uv.O.TRUNC on top of the existing base flags.
  • Left intentionally unused for .fd pathlikes, so existing descriptors (stdin/stdout/stderr or user‑provided FDs) keep whatever mode they were opened with.

This matches the POSIX behavior and keeps default truncate semantics when append is false/omitted.

Also applies to: 367-387, 424-438, 641-660


688-689: Append option correctly propagated through WriteFileWaitFromLockedValueTask to Blob.writeFileWithSourceDestination

Extending WriteFileWaitFromLockedValueTask with an append: bool = false and forwarding it into Blob.writeFileWithSourceDestination via .{ .mkdirp_if_not_exists = this.mkdirp_if_not_exists, .append = this.append } ensures the promise‑based/Body.Value path honors append semantics consistently with the direct write APIs. Lifetimes (file_blob.detach, promise deinit, and handler destruction) remain unchanged and look safe.

Also applies to: 694-722

src/bun.js/webcore/blob/copy_file.zig (10)

21-21: LGTM!

The append field is correctly added with a sensible default of false, preserving backward compatibility.


133-136: LGTM!

The helper cleanly encapsulates the conditional flag selection for destination file opening.


420-420: LGTM!

Correctly disabling the clonefile fast path when append is true, as clonefile creates a full copy rather than appending content.


601-603: LGTM!

Correctly guards against truncation when in append mode, preserving the appended content.


625-625: LGTM!

Consistent with the CopyFile struct's field addition.


856-892: LGTM!

The append parameter is correctly threaded through, with appropriate open flags (O.APPEND vs O.TRUNC) selected based on the mode.


898-917: LGTM!

Correctly passes this.append for the destination and false for the source, since only the destination file needs append semantics.


930-935: LGTM!

Correctly bypasses uv_fs_copyfile for append mode, as the libuv API doesn't support appending. The read-write loop fallback is the appropriate mechanism.


27-51: LGTM!

The append parameter is correctly threaded through the create function and used to initialize the struct.


827-854: LGTM!

The append parameter is correctly threaded through the init function, consistent with the CopyFile.create pattern.

Comment thread src/bun.js/webcore/blob/copy_file.zig Resolved
Comment thread src/bun.js/webcore/blob/copy_file.zig Resolved
Comment thread test/js/bun/io/bun-write-append.test.ts Resolved
@mattermoran mattermoran changed the title feat(io): Add append option to Bun.write, BunFile.write and BunFile.writer feat(io): Add append option to Bun.write, BunFile.write and FileSink (BunFile.writer) Dec 30, 2025
Comment thread src/bun.js/webcore/blob/copy_file.zig Resolved
Comment thread src/bun.js/webcore/Blob.zig Outdated
switch (bun.sys.open(
path,
bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK,
bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK | (if (append) bun.O.APPEND else bun.O.TRUNC),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This didn't previously use O_TRUNC so we should continue to not use O_TRUNC

Suggested change
bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK | (if (append) bun.O.APPEND else bun.O.TRUNC),
bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK | (if (append) bun.O.APPEND else 0),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

updated though I find the non truncating behavior of the FileSink confusing as I mentioned in my message

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

actually now that I think about it I think it's a bug. normal .write does not pass the trunc flag for performance but it still truncates the file after the write but for filesink it just starts writing over the file. I can handle that in a separate PR after this one

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added 2 PRs fixing the truncation issue either using O_TRUNC flag in #25966 or ftruncate in #25967

Comment thread src/bun.js/webcore/Blob.zig Resolved
@mattermoran

Copy link
Copy Markdown
Contributor Author

removed the truncation where there wasn't before

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/bun.js/webcore/blob/copy_file.zig (1)

625-631: Windows append path risks truncating existing files in onComplete

The Windows changes correctly:

  • Add an append: bool field to CopyFileWindows and thread it through init.
  • Pass append into preparePathlike so destinations are opened with WRONLY | CREAT | APPEND when appending.
  • Route append: true through prepareReadWriteLoop() instead of uv_fs_copyfile, disabling the optimized copy in append mode.

However, onComplete() still unconditionally uses this.size to decide whether to truncate:

pub fn onComplete(this: *CopyFileWindows, written_actual: usize) void {
    var written = written_actual;
    if (written != @as(@TypeOf(written), @intCast(this.size)) and this.size != Blob.max_size) {
        this.truncate();
        written = @intCast(this.size);
    }
    ...
}

In append mode, this.size represents the expected number of bytes copied, not the final file size (which includes pre‑existing data). If this condition ever trips for an append operation (for example due to a short write when size was set from metadata), truncate() will shrink the entire destination file to this.size, discarding existing content that should have been preserved by append.

To keep append safe while leaving existing behavior unchanged for overwrite mode, truncate() should be skipped when append is true:

Suggested fix: guard truncation behind !this.append
 pub fn onComplete(this: *CopyFileWindows, written_actual: usize) void {
     var written = written_actual;
-    if (written != @as(@TypeOf(written), @intCast(this.size)) and this.size != Blob.max_size) {
-        this.truncate();
-        written = @intCast(this.size);
-    }
+    if (!this.append and written != @as(@TypeOf(written), @intCast(this.size)) and this.size != Blob.max_size) {
+        this.truncate();
+        written = @intCast(this.size);
+    }
     const globalThis = this.event_loop.global;
     const promise = this.promise.swap();
     ...
 }

This keeps non‑append semantics intact while ensuring append operations never retroactively truncate existing files.

Also applies to: 829-848, 858-895, 896-930, 932-937, 1103-1108

packages/bun-types/bun.d.ts (1)

763-785: Docs for Response/BunFile copy overloads should mention append semantics

The Response and BunFile copy overloads now correctly accept append?: boolean in options, and you’ve added a note that append: true disables the optimized copy path, which matches the Zig implementation.

The remaining prose in these JSDoc blocks still says the destination “will be overwritten” and “destination will be truncated” without mentioning the append case, which is now inaccurate when append: true.

Consider updating the text to something like:

  • “If append is not set or false, the file is overwritten…”
  • “When append: true, data is appended and the existing contents are not truncated; optimized copy paths are disabled.”

That keeps the behavior clear for both modes and avoids confusion when reading the docs.

Also applies to: 796-817, 819-905

♻️ Duplicate comments (1)
src/bun.js/webcore/blob/copy_file.zig (1)

130-137: Re‑introducing O.TRUNC for destinations — confirm intended semantics/perf trade‑off

openDestinationFlags() now uses O.TRUNC when append is false, so doOpenFile() truncates the destination immediately on open in the non‑append case:

fn openDestinationFlags(this: *const CopyFile) i32 {
    const mode: i32 = if (this.append) O.APPEND else O.TRUNC;
    return O.CLOEXEC | O.CREAT | O.WRONLY | mode;
}

Previously there was feedback (from Jarred) that O_TRUNC was intentionally avoided here for performance reasons (overwrite in place + ftruncate later). This helper changes that behavior again.

If the new eager‑truncate semantics are intentional, consider documenting that decision; otherwise, it may be worth dropping O.TRUNC and relying on the existing truncation logic after copy, to avoid the extra zeroing cost.

Also applies to: 162-201

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between df598a9 and 2a0c3fe.

📒 Files selected for processing (3)
  • packages/bun-types/bun.d.ts
  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/blob/copy_file.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig

📄 CodeRabbit inference engine (src/CLAUDE.md)

src/**/*.zig: Private fields in Zig are fully supported using the # prefix: struct { #foo: u32 };
Use decl literals in Zig for declaration initialization: const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer @import at the bottom of the file (auto formatter will move them automatically)

Files:

  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/Blob.zig
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

In Zig code, be careful with allocators and use defer for cleanup

Files:

  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/Blob.zig
🧠 Learnings (13)
📚 Learning: 2025-11-03T20:40:59.655Z
Learnt from: pfgithub
Repo: oven-sh/bun PR: 24273
File: src/bun.js/bindings/JSValue.zig:545-586
Timestamp: 2025-11-03T20:40:59.655Z
Learning: In Bun's Zig codebase, JSErrors (returned as `bun.JSError!T`) must always be properly handled. Using `catch continue` or `catch { break; }` to silently suppress JSErrors is a bug. Errors should either be explicitly handled or propagated with `try`. This applies to snapshot serializer error handling where Jest's behavior is to throw when serializers throw.

Applied to files:

  • src/bun.js/webcore/blob/copy_file.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.

Applied to files:

  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes

Applied to files:

  • src/bun.js/webcore/Blob.zig
  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-20T19:51:32.288Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24880
File: packages/bun-vscode/package.json:382-385
Timestamp: 2025-11-20T19:51:32.288Z
Learning: In the Bun repository, dependencies may be explicitly added to package.json files (even when not directly imported in code) to force version upgrades on transitive dependencies, particularly as part of Aikido security scanner remediation to ensure vulnerable transitive dependencies resolve to patched versions.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-19T04:55:33.099Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: test/js/bun/http/node-telemetry.test.ts:27-203
Timestamp: 2025-10-19T04:55:33.099Z
Learning: In test/js/bun/http/node-telemetry.test.ts and the Bun.telemetry._node_binding API, after the architecture refactor, the _node_binding interface only contains two methods: handleIncomingRequest(req, res) and handleWriteHead(res, statusCode). The handleRequestFinish hook and other lifecycle hooks were removed during simplification. Both current methods are fully tested.

Applied to files:

  • packages/bun-types/bun.d.ts
🧬 Code graph analysis (1)
packages/bun-types/bun.d.ts (2)
src/codegen/bindgenv2/internal/interfaces.ts (1)
  • Blob (21-40)
src/codegen/bindgenv2/lib.ts (1)
  • Blob (10-10)
🔇 Additional comments (16)
src/bun.js/webcore/blob/copy_file.zig (4)

20-47: Append flag is correctly threaded through CopyFile.create

The new append: bool field and create(..., append: bool) parameter are wired consistently into the CopyFile initializer, so downstream logic can reliably distinguish append vs truncate behavior. No issues here.


420-467: Gating clonefile on !append is correct and avoids incompatible fast‑path

The added !this.append check in the macOS clonefile fast path ensures append operations never go through clonefile, which only supports whole‑file clones. That avoids subtle “append but actually overwrite” behavior and correctly forces append operations down the regular open/copy path.


522-538: Linux append fallback looks correct; double‑check offset usage for append cases

The Linux append branch now:

  • Unconditionally falls back to copyFileUsingReadWriteLoop when this.append is true.
  • Correctly updates read_len from total_written.
  • Calls this.doClose() on both .err and .result paths, fixing the earlier FD leak.

One thing to verify: this path ignores this.offset and just passes this.source_fd into the read/write loop. If CopyFile.create is ever called with a non‑zero offset in append mode (e.g. Bun.write(dest, Bun.file(src).slice(begin), { append: true })), we’ll currently append from the start of the source file rather than from offset.

If such combinations are valid, we probably need to either:

  • Seek source_fd to this.offset before entering the loop, or
  • Extend copyFileUsingReadWriteLoop to accept an initial offset.

If append + offset is supposed to be unsupported, consider asserting this.offset == 0 when this.append is true.


580-607: macOS append fallback and truncation gating align with expected semantics

On macOS, the new append branch:

  • Routes appends through copyFileUsingReadWriteLoop (no clonefile/fcopyfile fast paths).
  • Ensures this.doClose() runs on both success and error.
  • Gently changes the post‑copy truncation to only run when !this.append:
if (!this.append and stat.size != 0 and @as(SizeType, @intCast(stat.size)) > this.max_length) {
    _ = darwin.ftruncate(..., @intCast(this.max_length));
}

This prevents accidental shrinking of an existing file when appending, while preserving previous truncate‑on‑short‑copy behavior for non‑append writes. Looks good.

packages/bun-types/bun.d.ts (2)

724-749: Top‑level Bun.write overload matches new runtime capabilities

The widened input union (adding ReadableStream and Request) and the new append?: boolean option are consistent with the runtime changes (stream sources and append semantics), and the JSDoc clearly explains overwrite vs append behavior and default createPath. This overload looks accurate and ready for external consumers.


1324-1332: BunFile.writer and BunFile.write append options and input unions align with Bun.write

The updates to:

  • BunFile.writer(options?: { highWaterMark?: number; append?: boolean })
  • BunFile.write(data: Blob | NodeJS.TypedArray | ArrayBufferLike | string | BlobPart[] | ReadableStream | Request | Response | BunFile, options?: { highWaterMark?: number; append?: boolean })

bring the instance APIs in line with the top‑level Bun.write overloads (same source types, same append semantics). The JSDoc for append is clear and consistent with the new behavior. No issues from a typings standpoint.

Also applies to: 1373-1396

src/bun.js/webcore/Blob.zig (10)

855-858: LGTM! Correct early return for append with empty source.

Appending an empty source should leave the file unchanged, and returning immediately with a resolved promise (0 bytes written) is the correct behavior. This avoids the truncation logic below that applies to non-append writes.


1262-1273: LGTM! Fast path correctly skipped for append operations.

The logic properly checks options.append == false before allowing the fast synchronous write path. This is intentional per the PR design, as append operations require proper file positioning that the fast path doesn't handle.


1492-1498: LGTM! ReadableStream support correctly implemented.

The new ReadableStream source handling is well-implemented:

  • Properly checks if the stream has already been used (disturbed)
  • Correctly cleans up resources (detaches destination_blob) on error
  • Threads the append flag through to pipeReadableStreamToBlob

This aligns with the PR objective of adding ReadableStream support for .write().


1554-1575: LGTM! Option extraction follows established patterns.

The append option is correctly extracted from the options object:

  • Defaults to false (preserve existing behavior)
  • Uses getBooleanLoose for proper coercion (as per past feedback)
  • Properly passed through to writeFileInternal

2292-2337: LGTM! Consistent option handling in BunFile.write().

The append option extraction in doWrite (for BunFile.write()) mirrors the pattern used in writeFile (for Bun.write()), ensuring consistent behavior across both APIs.


2464-2465: LGTM! Open flags correctly use O_APPEND when appending.

The conditional addition of bun.O.APPEND based on the append flag is correct. Note that O_TRUNC is intentionally not used here (as confirmed by past review feedback), as truncation logic is handled separately in FileSink when appropriate.


2640-2646: LGTM! Append option properly added to FileSink writer.

The append option extraction for getWriter (which backs Bun.file().writer()) is correctly implemented and consistent with the other write APIs. This fulfills the PR objective of extending FileSink to support append.


4629-4637: LGTM! Excellent abstraction for context-specific open flags.

The getOpenFlagsForContext function is a well-designed abstraction that allows different contexts to specify their own open flags (including O_APPEND or O_TRUNC based on append mode). The compile-time reflection using @hasDecl makes this generic function work cleanly with multiple context types while maintaining type safety.

This centralizes flag determination logic and makes FileOpener more maintainable.


4676-4691: LGTM! Consistent use of getOpenFlagsForContext abstraction.

Both file open paths (Windows/libuv and POSIX) correctly use getOpenFlagsForContext(this) to obtain the appropriate flags from the context. This allows WriteFile, CopyFile, and other contexts to specify their own flags (including O_APPEND when append mode is enabled) while maintaining consistent baseline flags (O_NONBLOCK | O_CLOEXEC).


1216-1216: Overall: Well-implemented append functionality across all write paths.

The append option has been cleanly integrated throughout the Blob/File write infrastructure:

✅ Consistent API design: The option is uniformly extracted and validated across Bun.write(), BunFile.write(), and BunFile.writer()

✅ Correct semantics:

  • Empty source + append = no-op (file unchanged)
  • Fast path correctly skipped for append operations
  • Open flags properly use O_APPEND when needed

✅ Good abstractions: The getOpenFlagsForContext helper cleanly separates flag determination logic

✅ Feature additions: ReadableStream support integrates well with the append functionality

The implementation aligns with the PR objectives and handles edge cases appropriately.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @src/bun.js/webcore/Blob.zig:
- Line 1220: The new append: bool field in the Blob type lacks documentation;
add a short doc comment above the append field explaining its purpose and
behavior (e.g., when append == true the blob write should append to existing
data, when false the write should truncate/overwrite), note any default
semantics and how it interacts with existing write/truncate logic (e.g., whether
truncation occurs only on false or on open modes), and keep the comment concise
and placed immediately above the append field declaration to clarify expected
runtime behavior.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1c39917 and 7501636.

📒 Files selected for processing (4)
  • packages/bun-types/bun.d.ts
  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/S3Client.zig
  • src/bun.js/webcore/S3File.zig
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

In Zig code, be careful with allocators and use defer for cleanup

Files:

  • src/bun.js/webcore/S3Client.zig
  • src/bun.js/webcore/S3File.zig
  • src/bun.js/webcore/Blob.zig
src/**/*.zig

📄 CodeRabbit inference engine (src/CLAUDE.md)

src/**/*.zig: Use the # prefix for private fields in Zig structs, e.g., struct { #foo: u32 };
Use Decl literals in Zig, e.g., const decl: Decl = .{ .binding = 0, .value = 0 };
Place @import statements at the bottom of the file in Zig (auto formatter will handle positioning)
Never use @import() inline inside functions in Zig; always place imports at the bottom of the file or containing struct

Files:

  • src/bun.js/webcore/S3Client.zig
  • src/bun.js/webcore/S3File.zig
  • src/bun.js/webcore/Blob.zig
🧠 Learnings (15)
📚 Learning: 2026-01-05T16:32:07.551Z
Learnt from: alii
Repo: oven-sh/bun PR: 25474
File: src/bun.js/event_loop/Sigusr1Handler.zig:0-0
Timestamp: 2026-01-05T16:32:07.551Z
Learning: In Zig codebases (e.g., Bun), treat std.posix.sigaction as returning void and do not perform runtime error handling for its failure. The Zig standard library views sigaction failures as programmer errors (unreachable) because they only occur with invalid signals like SIGKILL/SIGSTOP. Apply this pattern across Zig files that call sigaction (e.g., crash_handler.zig, main.zig, filter_run.zig, process.zig) and ensure failures are not handled as recoverable errors; prefer reaching an explicit unreachable/compile-time assumption when such failures are detected.

Applied to files:

  • src/bun.js/webcore/S3Client.zig
  • src/bun.js/webcore/S3File.zig
  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes

Applied to files:

  • packages/bun-types/bun.d.ts
  • src/bun.js/webcore/Blob.zig
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun bd test <...test file>` to run tests with compiled code changes. Do not use `bun test` as it will not include your changes.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-20T19:51:32.288Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24880
File: packages/bun-vscode/package.json:382-385
Timestamp: 2025-11-20T19:51:32.288Z
Learning: In the Bun repository, dependencies may be explicitly added to package.json files (even when not directly imported in code) to force version upgrades on transitive dependencies, particularly as part of Aikido security scanner remediation to ensure vulnerable transitive dependencies resolve to patched versions.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` for files ending in `*.test.{ts,js,jsx,tsx,mjs,cjs}`. For test files without .test extension in test/js/node/test/{parallel,sequential}/*.js, use `bun bd <file>` instead of `bun bd test <file>` since they expect exit code 0.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:47.899Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/AGENTS.md:0-0
Timestamp: 2025-11-24T18:37:47.899Z
Learning: Applies to src/bun.js/bindings/v8/**/<UNKNOWN> : <UNKNOWN>

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.

Applied to files:

  • src/bun.js/webcore/Blob.zig
🔇 Additional comments (15)
src/bun.js/webcore/Blob.zig (6)

855-858: LGTM - Correct handling of append with empty source.

The early return for append mode with an empty source is correct—appending nothing should be a no-op that leaves the file unchanged. The comment clearly explains the intent.


1498-1504: LGTM - ReadableStream support properly implemented.

The new ReadableStream handling correctly checks if the stream is disturbed before piping, properly detaches the destination blob on error, and passes the append flag through to pipeReadableStreamToBlob.


1560-1572: LGTM - Option parsing is correct and maintains backward compatibility.

The append option defaults to false, preserving existing behavior. Using getBooleanLoose for parsing allows flexible coercion of truthy values.


2472-2472: File opening flags are correct for append mode.

The conditional addition of bun.O.APPEND when append is true correctly implements append semantics at the OS level. When append is false, the file is opened with WRONLY | CREAT | NONBLOCK without O_TRUNC, which is deliberate per past review feedback for performance reasons.


2648-2654: LGTM - getWriter correctly reads and defaults the append option.

The append option parsing follows the same pattern as other write methods, defaulting to false for backward compatibility.


4639-4647: Good refactoring to consolidate file opening flag logic.

The new getOpenFlagsForContext helper provides a clean way for different contexts to specify their open flags while ensuring common flags like NONBLOCK and CLOEXEC are always added. The append behavior is appropriately delegated to context-specific implementations through getOpenFlags() or open_flags.

src/bun.js/webcore/S3File.zig (1)

160-160: LGTM - Explicitly disabling append for S3 operations is correct.

S3 doesn't support atomic append operations, so explicitly passing append: false is appropriate. The explicit false makes the intent clear and documents that append is not supported for S3 writes.

Also applies to: 166-166

src/bun.js/webcore/S3Client.zig (1)

232-232: LGTM - Consistent with S3File, correctly disabling append for S3.

Like S3File.zig, this correctly passes append: false since S3 doesn't support atomic append operations.

packages/bun-types/bun.d.ts (7)

724-749: LGTM! Expanded input types and append option properly added.

The input type expansion to include ReadableStream | Request aligns with the PR objectives. The append option is well-documented with clear behavior description and correct default value.


763-784: LGTM! Append option correctly added for Response input.

The append option is properly documented and consistent with other overloads.


796-817: LGTM! Append option properly documented.

Consistent implementation across Response input overloads.


830-861: LGTM! Good documentation of performance implications.

The note at lines 830-831 about optimized copy paths being disabled when append: true is valuable information for users. The append option is properly documented.


874-904: LGTM! Consistent documentation for file copy operations.

The performance note about optimized copy paths and the append option are both properly documented, consistent with the BunFile destination overload.


1324-1331: LGTM! FileSink writer now supports append mode.

The append option is properly added to BunFile.writer() with clear documentation, enabling append support for FileSink as mentioned in the PR objectives.


1373-1396: LGTM! BunFile.write() types aligned with Bun.write().

The expanded input types (including ReadableStream, Request, Response, and BunFile) properly align the supported source types between Bun.write() and BunFile.write() as stated in the PR objectives. The append option is well-documented and consistent with other APIs.

Comment thread src/bun.js/webcore/Blob.zig Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bun-types/bun.d.ts (1)

778-845: Docs for append semantics look good; consider cross-referencing append in the generic overload docs.
The Response-specific overloads clearly state truncate vs append behavior (Lines 782-784, 817-819). That clarity is missing from the “generic input” overload (Lines 767-775) where users are most likely to look first. Consider adding a brief “append=false truncates” sentence to the generic overload JSDoc as well (or referencing these overloads).

🤖 Fix all issues with AI agents
In @packages/bun-types/bun.d.ts:
- Around line 1379-1386: The JSDoc for BunFile.writer's options is ambiguous
about append=false; update the comment on the writer(options?: { append?:
boolean }) signature (the writer method that returns FileSink) to explicitly
state that when append is false or omitted the file is truncated (overwritten)
rather than preserved, and keep @default false to match Bun.write docs and the
PR behavior.
- Around line 1428-1451: Introduce shared type aliases for the duplicated input
union and options and use them in both Bun.write and BunFile.write signatures:
create a type alias (e.g., WriteInput = Blob | NodeJS.TypedArray |
ArrayBufferLike | string | BlobPart[] | ReadableStream | Request | Response |
BunFile) and an options alias (e.g., WriteAppendOptions = { highWaterMark?:
number; append?: boolean }) and replace the inline union and options object in
the write(...) overloads with these aliases so both Bun.write and BunFile.write
reference the single source of truth.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7501636 and 7e18d38.

📒 Files selected for processing (3)
  • packages/bun-types/bun.d.ts
  • src/bun.js/webcore/Blob.zig
  • src/bun.js/webcore/blob/copy_file.zig
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

In Zig code, be careful with allocators and use defer for cleanup

Files:

  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/Blob.zig
src/**/*.zig

📄 CodeRabbit inference engine (src/CLAUDE.md)

src/**/*.zig: Use the # prefix for private fields in Zig structs, e.g., struct { #foo: u32 };
Use Decl literals in Zig, e.g., const decl: Decl = .{ .binding = 0, .value = 0 };
Place @import statements at the bottom of the file in Zig (auto formatter will handle positioning)
Never use @import() inline inside functions in Zig; always place imports at the bottom of the file or containing struct

Files:

  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/Blob.zig
🧠 Learnings (15)
📚 Learning: 2025-11-03T20:40:59.655Z
Learnt from: pfgithub
Repo: oven-sh/bun PR: 24273
File: src/bun.js/bindings/JSValue.zig:545-586
Timestamp: 2025-11-03T20:40:59.655Z
Learning: In Bun's Zig codebase, JSErrors (returned as `bun.JSError!T`) must always be properly handled. Using `catch continue` or `catch { break; }` to silently suppress JSErrors is a bug. Errors should either be explicitly handled or propagated with `try`. This applies to snapshot serializer error handling where Jest's behavior is to throw when serializers throw.

Applied to files:

  • src/bun.js/webcore/blob/copy_file.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.

Applied to files:

  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/Blob.zig
📚 Learning: 2026-01-05T16:32:07.551Z
Learnt from: alii
Repo: oven-sh/bun PR: 25474
File: src/bun.js/event_loop/Sigusr1Handler.zig:0-0
Timestamp: 2026-01-05T16:32:07.551Z
Learning: In Zig codebases (e.g., Bun), treat std.posix.sigaction as returning void and do not perform runtime error handling for its failure. The Zig standard library views sigaction failures as programmer errors (unreachable) because they only occur with invalid signals like SIGKILL/SIGSTOP. Apply this pattern across Zig files that call sigaction (e.g., crash_handler.zig, main.zig, filter_run.zig, process.zig) and ensure failures are not handled as recoverable errors; prefer reaching an explicit unreachable/compile-time assumption when such failures are detected.

Applied to files:

  • src/bun.js/webcore/blob/copy_file.zig
  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.

Applied to files:

  • src/bun.js/webcore/Blob.zig
  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.

Applied to files:

  • src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun bd test <...test file>` to run tests with compiled code changes. Do not use `bun test` as it will not include your changes.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2025-11-20T19:51:32.288Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24880
File: packages/bun-vscode/package.json:382-385
Timestamp: 2025-11-20T19:51:32.288Z
Learning: In the Bun repository, dependencies may be explicitly added to package.json files (even when not directly imported in code) to force version upgrades on transitive dependencies, particularly as part of Aikido security scanner remediation to ensure vulnerable transitive dependencies resolve to patched versions.

Applied to files:

  • packages/bun-types/bun.d.ts
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` for files ending in `*.test.{ts,js,jsx,tsx,mjs,cjs}`. For test files without .test extension in test/js/node/test/{parallel,sequential}/*.js, use `bun bd <file>` instead of `bun bd test <file>` since they expect exit code 0.

Applied to files:

  • packages/bun-types/bun.d.ts
🧬 Code graph analysis (1)
packages/bun-types/bun.d.ts (1)
src/codegen/bindgenv2/internal/interfaces.ts (1)
  • Blob (21-40)
🔇 Additional comments (31)
src/bun.js/webcore/blob/copy_file.zig (12)

22-22: LGTM!

The append field is properly added with a sensible default of false, and correctly propagated through the create function to the struct initializer.

Also applies to: 37-37, 49-49


154-157: LGTM!

The openDestinationFlags method correctly computes the destination open flags, choosing O.APPEND for append mode and O.TRUNC for normal writes.


189-189: LGTM!

Correctly uses the dynamic openDestinationFlags() method instead of hardcoded flags.


442-442: LGTM!

Correctly skips the clonefile fast path when appending, since clonefile creates a new copy and cannot append to an existing file.


554-570: LGTM!

The Linux append path correctly falls back to the read-write loop, which will work with the O_APPEND flag set on the destination file descriptor.


612-628: LGTM!

The macOS append path correctly mirrors the Linux implementation, falling back to the read-write loop for append operations.


635-635: LGTM!

Correctly skips truncation when appending, preserving the existing file content that was just appended to.


663-663: LGTM!

The append field is properly added to CopyFileWindows and correctly propagated through the init function.

Also applies to: 870-870, 884-884


896-907: LGTM!

The preparePathlike function correctly uses the append parameter to determine open flags for writing, adding O.APPEND when needed.


938-938: LGTM!

Correctly passes this.append for the destination and false for the source, since append only applies to write operations.

Also applies to: 951-951


970-975: LGTM!

Correctly bypasses uv_fs_copyfile when appending, since that syscall cannot append to files.


1143-1147: LGTM!

Correctly skips truncation in onComplete when appending, preventing data loss.

src/bun.js/webcore/Blob.zig (17)

855-858: LGTM!

Correct optimization: appending an empty source should be a no-op, so returning early with 0 bytes written is appropriate.


1029-1029: LGTM!

The append flag is correctly propagated to both Windows and non-Windows write file implementations.

Also applies to: 1044-1044


1063-1063: LGTM!

The append flag is correctly propagated to the file copy implementations for file-to-file operations.

Also applies to: 1077-1077


1088-1088: LGTM!

The append flag is correctly passed when piping from S3 to a file destination.


1218-1223: LGTM!

The WriteFileOptions struct correctly includes the append field, and since it's a private struct, having it as a required field is appropriate.


1268-1278: LGTM!

Correctly skips the fast write path when appending, since the fast path doesn't support O_APPEND semantics.


1427-1427: LGTM!

The append flag is correctly propagated to WriteFileWaitFromLockedValueTask for both Response and Request locked bodies.

Also applies to: 1490-1490


1500-1506: LGTM!

Correctly handles ReadableStream as a source and pipes it to the blob with the append flag. This addresses the PR objective of adding ReadableStream support.


1563-1563: LGTM!

The writeFile function correctly parses the append option from the options object and propagates it to writeFileInternal.

Also applies to: 1585-1587, 1596-1596


2315-2315: LGTM!

The doWrite function correctly parses the append option and passes it to writeFileInternal.

Also applies to: 2348-2350, 2356-2360


2443-2443: LGTM!

The pipeReadableStreamToBlob function signature correctly includes the append parameter.


2488-2489: LGTM!

Correctly adds O.APPEND to the open flags when appending on Windows.


2564-2564: LGTM!

The append flag is correctly passed to the FileSink stream start configuration.


2664-2670: LGTM!

The getWriter function correctly parses the append option from the options object.


2748-2748: LGTM!

Both Windows and non-Windows paths in getWriter correctly use the append flag when opening/configuring the file writer.

Also applies to: 2824-2824


4655-4663: LGTM!

The getOpenFlagsForContext function provides a flexible mechanism for types to specify dynamic open flags (e.g., based on append), with sensible fallbacks.


4702-4702: LGTM!

Both Windows and non-Windows paths in getFdByOpening correctly use the dynamic getOpenFlagsForContext function.

Also applies to: 4717-4717

packages/bun-types/bun.d.ts (2)

846-960: Good: explicit “optimized copy disabled when appending”; verify behavior for append+copy edge cases.
The note about skipping optimized copy paths when append: true is helpful (Lines 857-862, 915-920). One thing to sanity-check in tests/behavior (if not already): append: true with input === destination (same file) and with non-empty destination—ensure it either errors or produces deterministic results.


751-776: Add explicit Bun.write() overloads for S3File with Response, or restrict S3File to Blob-like inputs only in the generic overload.
The first write() overload includes S3File as a destination with Request and ReadableStream in the input union (line 753), but there's no corresponding Response overload for S3File. Since BunFile has dedicated Response overloads and tests don't validate Bun.write(s3file, Request), clarify whether Request/ReadableStream are supported for S3File destinations or restrict them to filesystem/BunFile operations only. If S3File should support Response bodies, add a matching overload; if not, narrow the first overload's input union to exclude Request/ReadableStream when the destination is S3File.

Comment on lines +1379 to +1386
writer(options?: {
highWaterMark?: number;
/**
* If `true`, append to the end of the file.
* @default false
*/
append?: boolean;
}): FileSink;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

BunFile.writer({ append }) docs are ambiguous about the non-append default (truncate vs overwrite-in-place).
Right now it only says “append to the end” and @default false (Lines 1382-1385), but doesn’t state what false does. Given the PR fixes truncation behavior when not appending, please spell out “If false/omitted, the file is truncated (overwritten)” to align with Bun.write docs.

Proposed doc tweak
     writer(options?: {
       highWaterMark?: number;
       /**
        * If `true`, append to the end of the file.
+       *
+       * If `false` or omitted, the file will be truncated (overwritten).
        * @default false
        */
       append?: boolean;
     }): FileSink;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
writer(options?: {
highWaterMark?: number;
/**
* If `true`, append to the end of the file.
* @default false
*/
append?: boolean;
}): FileSink;
writer(options?: {
highWaterMark?: number;
/**
* If `true`, append to the end of the file.
*
* If `false` or omitted, the file will be truncated (overwritten).
* @default false
*/
append?: boolean;
}): FileSink;
🤖 Prompt for AI Agents
In @packages/bun-types/bun.d.ts around lines 1379 - 1386, The JSDoc for
BunFile.writer's options is ambiguous about append=false; update the comment on
the writer(options?: { append?: boolean }) signature (the writer method that
returns FileSink) to explicitly state that when append is false or omitted the
file is truncated (overwritten) rather than preserved, and keep @default false
to match Bun.write docs and the PR behavior.

Comment on lines 1428 to 1451
write(
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer | Request | Response | BunFile,
options?: { highWaterMark?: number },
data:
| Blob
| NodeJS.TypedArray
| ArrayBufferLike
| string
| BlobPart[]
| ReadableStream
| Request
| Response
| BunFile,

options?: {
highWaterMark?: number;
/**
* If `true`, append to the end of the file instead of overwriting it.
*
* If `false` or omitted, the file will be truncated (overwritten).
*
* @default false
*/
append?: boolean;
},
): Promise<number>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Avoid type drift: factor shared “write input” / “append options” aliases used by Bun.write + BunFile.write.
The input union and the append option block are now duplicated across multiple overloads (Lines 1429-1450 and earlier). This is likely to drift over time (e.g., adding a new accepted type to one but not the others). Consider introducing internal aliases (e.g., type WriteAppendOptions = { highWaterMark?: number; append?: boolean }) and reusing them.

Possible direction (illustrative)
   type BlobPart = string | Blob | BufferSource;
+  type WriteAppendOptions = {
+    highWaterMark?: number;
+    /**
+     * If `true`, append to the end of the file instead of overwriting it.
+     *
+     * If `false` or omitted, the file will be truncated (overwritten).
+     *
+     * @default false
+     */
+    append?: boolean;
+  };

   interface BunFile extends Blob {
     writer(options?: {
       highWaterMark?: number;
       /**
        * If `true`, append to the end of the file.
        *
        * If `false` or omitted, the file will be truncated (overwritten).
        * @default false
        */
       append?: boolean;
     }): FileSink;

     write(
       data:
         | Blob
         | NodeJS.TypedArray
         | ArrayBufferLike
         | string
         | BlobPart[]
         | ReadableStream
         | Request
         | Response
         | BunFile,
-      options?: {
-        highWaterMark?: number;
-        /**
-         * If `true`, append to the end of the file instead of overwriting it.
-         *
-         * If `false` or omitted, the file will be truncated (overwritten).
-         *
-         * @default false
-         */
-        append?: boolean;
-      },
+      options?: WriteAppendOptions,
     ): Promise<number>;
   }
🤖 Prompt for AI Agents
In @packages/bun-types/bun.d.ts around lines 1428 - 1451, Introduce shared type
aliases for the duplicated input union and options and use them in both
Bun.write and BunFile.write signatures: create a type alias (e.g., WriteInput =
Blob | NodeJS.TypedArray | ArrayBufferLike | string | BlobPart[] |
ReadableStream | Request | Response | BunFile) and an options alias (e.g.,
WriteAppendOptions = { highWaterMark?: number; append?: boolean }) and replace
the inline union and options object in the write(...) overloads with these
aliases so both Bun.write and BunFile.write reference the single source of
truth.

@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator

Closing as stale: this PR predates the Rust rewrite. Every src/ file it modifies has since been removed or relocated on main (Zig sources deleted; src/bun.js/ reorganized into src/jsc/), so it can no longer merge.

If the underlying change is still wanted, it will need to be redone against the current Rust/C++ tree. Apologies for the churn, and thank you for the contribution.

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.

Support appending files with Bun.write Introduce BunFile.append or Bun.append

3 participants