Bun

Bun v1.2.5


Jarred Sumner · 2025 年 3 月 11 日

此版本修正了 75 個錯誤(解決了 162 個 👍),並新增了 69 個通過 Node.js 測試。它包含了前端開發伺服器的改進、CSS 模組支援、Node-API 的完整重寫、來自 node:crypto 的更快速的 SignVerifyHashHmac,以及針對 node:net 和 Bun 打包器的錯誤修正。

安裝 Bun

curl
npm
powershell
scoop
brew
docker
curl
curl -fsSL https://bun.dev.org.tw/install | bash
npm
npm install -g bun
powershell
powershell -c "irm bun.sh/install.ps1|iex"
scoop
scoop install bun
brew
brew tap oven-sh/bun
brew install bun
docker
docker pull oven/bun
docker run --rm --init --ulimit memlock=-1:-1 oven/bun

升級 Bun

bun upgrade

Node.js 相容性

更佳的 Node-API 相容性

在 Bun v1.2.5 中,我們幾乎完整重寫了 Bun 的 Node-API 實作。Node-API 是一個 C 介面,讓您可以用高度最佳化的原生程式碼編寫模組,並將其嵌入任何相容的 JavaScript 執行階段環境中。這可以加速效能關鍵的程式碼,並且允許在 C、C++、Rust 或 Zig 等語言中重複使用現有的原生函式庫。我們現在比以前更佳地相容於 Node.js 的實作,確保在 Node 中運作的 Node-API 模組也能在 Bun 中運作。

為了致力於 Node-API 相容性,我們專注於在 Bun 中執行 Node 的測試。這與我們自 Bun v1.2 以來測試核心 JavaScript 模組相容性的方式相同。我們也在自己的 Node-API 測試套件中新增了新的測試,以涵蓋邊緣案例。Bun v1.2.5 通過了 98% 的 Node 的 js-native-api 測試套件,該套件涵蓋了與核心 JavaScript 類型和執行互動的 API(例如,napi_create_double 將 C double 轉換為 JavaScript number)。

為此工作修正的錯誤完整列表相當長,但其中一些主要的錯誤是

  • 每個 Node-API 模組現在都有自己的 napi_env。先前,它們都共用同一個,如果您載入兩個都嘗試在 napi_env 中儲存資料的模組,就會發生錯誤。
  • 幾乎所有函式都比以前具有更好的錯誤處理,例如在傳遞 null 指標而不是假設指標有效並導致崩潰時,正確地傳回錯誤代碼。在我們能力所及的範圍內,務必確保有問題的原生模組拋出可以捕獲的錯誤,而不是導致整個程序崩潰。
  • 由 Node-API 建立的物件上的屬性現在具有正確的旗標,修正了諸如 #15429 的問題。
  • 我們偵測模組正在使用的 Node-API 版本,這意味著某些 API(例如終結器)的行為會有所不同。

更精確的 node:timers

Bun 的 node:timers 實作已修正為更緊密地符合 Node.js 行為。此更新解決了數個相容性問題和邊緣案例,讓您更容易執行基於 Node 的程式碼,而無需修改。

// Unref'd setImmediate no longer keeps the event loop alive
const immediate = setImmediate(() => console.log("This won't prevent exit"));
immediate.unref();

// Timers now handle edge cases for millisecond values
setTimeout(() => console.log("Still works with edge cases"), NaN); // Fires immediately with warning

// clearTimeout now accepts stringified timer IDs
const timeoutId = setTimeout(() => {}, 1000);
clearTimeout(String(timeoutId)); // Works correctly

Bun.CSRF

我們新增了 Bun.CSRF.generateBun.CSRF.verify,以協助您保護應用程式免受跨網站請求偽造 (CSRF) 攻擊。

感謝 @cirospaciari 的貢獻!

node:net 中更佳的 connect() 驗證

Node.js 相容性層中的 net.connect() 方法現在實作了改良的驗證。模組現在可以正確驗證 localAddresslocalPort 選項,並在提供無效值時拋出適當的錯誤類型。

// This will throw with ERR_INVALID_IP_ADDRESS
net.connect({
  host: "localhost",
  port: 8080,
  localAddress: "invalid-ip",
});

// This will throw with ERR_INVALID_ARG_TYPE
net.connect({
  host: "localhost",
  port: 8080,
  localPort: "not-a-number",
});

改良的 console.log() 中的 String 呈現

Bun 現在以類似於 Node.js 的方式在主控台中顯示 String 物件,將它們顯示為 [String: "value"]。這在偵錯使用 String 物件包裝函式的程式碼時,提供了更好的清晰度。

console.log(new String("Hello"));
// Previous: "Hello"
// Now: [String: "Hello"]

感謝 @Pranav2612000 的貢獻!

EventEmitter 中的 captureRejections 驗證

EventEmittercaptureRejections 選項的驗證已獲得改進,以便在提供無效值時提供更佳的錯誤訊息。

// This will now throw a more descriptive error
const emitter = new EventEmitter({ captureRejections: "yes" });
// TypeError: The "options.captureRejections" property must be of type boolean.

// Correct usage
const emitter = new EventEmitter({ captureRejections: true });

node:crypto 中更快速的 SignVerify

node:crypto 模組的 SignVerify 類別已在 C++ 中重新實作,利用 BoringSSL 以獲得更佳的效能和安全性。

node:crypto 中更快速的 createHashcreateHmac

Bun 現在以 C++ 原生實作 Node.js crypto 模組的 HmacHash 類別。這提高了密碼編譯操作的效能和與 Node.js 的相容性。

// Hash example
import { createHash } from "node:crypto";

const hash = createHash("sha256");
hash.update("hello world");
console.log(hash.digest("hex"));
// 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'

// Hmac example
import { createHmac } from "node:crypto";

const hmac = createHmac("sha256", "secret-key");
hmac.update("hello world");
console.log(hmac.digest("hex"));
// 'f13607378197fdb246f5dbc78e86e2fea13347b273087b330e8be27484cecae1'

感謝 @dylan-conway 的貢獻!

node:net 中的 AbortSignal 支援

您現在可以將 AbortSignal 傳遞至 net.createServer,以便在訊號中止時中止伺服器。

// Create a server with an AbortSignal
const server = net.createServer();
const controller = new AbortController();

// Pass the signal in the listen options
server.listen({ port: 0, signal: controller.signal });

// Later, abort the controller to close the server
controller.abort();

// You can also use a pre-aborted signal
const preAbortedServer = net.createServer();
preAbortedServer.listen({
  port: 0,
  signal: AbortSignal.abort(),
}); // Server will close immediately

node:perf_hooks 中已修正的行為

node:perf_hooks 模組中的 monitorEventLoopDelay()createHistogram() 方法現在在呼叫時會正確地拋出錯誤,而不是靜默地不做任何事。這些函式尚未在 Bun 中實作,它們現在正確地向開發人員指出這一點。

const { performance } = require("node:perf_hooks");

// Before: These would silently do nothing
// Now: They properly throw an error when called
try {
  performance.monitorEventLoopDelay();
} catch (e) {
  console.error("Error:", e.message); // Error: Not implemented
}

node:child_process 中已修正的傳送空白 IPC 訊息

修正了在子程序通訊期間接收到空白 IPC 訊息時,Bun 執行階段環境會拋出判斷提示錯誤的問題。這提高了使用 child_process.fork() 時的可靠性,方法是正確地處理邊緣案例。

// Before: Empty messages could cause an assertion error
const child = fork("./worker.js");
child.send(""); // Could cause assertion failure

// Now: Empty messages are properly handled
const child = fork("./worker.js");
child.send(""); // Works correctly

感謝 @DonIsaac 的修正!

已修正監聽前的 server.unref()

修正了在監聽之前在 net.Server 上呼叫 unref() 不會持久保存 unref 狀態的錯誤,這可能會導致伺服器意外地保持事件迴圈開啟。

// Previously, this pattern didn't work correctly
const server = net.createServer();
server.unref(); // This wouldn't persist after listen()
server.listen();

// Now unref() correctly persists even when called before listen()

感謝 @nektro 的貢獻!

已修正事件迴圈中 setImmediate 的行為

修正了事件迴圈中的效能問題,該問題會在同時存在 setInterval 計時器和 setImmediate 工作時導致不必要的閒置。事件迴圈現在可以正確地優先處理立即工作而不會閒置,從而為依賴立即回呼的程式碼帶來更佳的效能。

// Immediate tasks now run efficiently even with interval timers present
setInterval(() => {
  // Some background task
}, 1000);

function processNextItem() {
  // Process item from queue
  if (moreItemsExist) {
    setImmediate(processNextItem);
  }
}

processNextItem();

感謝 @190n 的修正!

node:child_process 的繼承 stdin

修正了具有繼承 stdin 的子程序不正確地傳回 process.stdin 而不是 null 的問題。此變更使 Bun 的行為與 Node.js 一致,並解決了與 npx 等工具的相容性問題,這些工具在 stdin 繼承時會預期 null

// Before: Would incorrectly return process.stdin
const child = spawn("some-command", [], { stdio: "inherit" });
console.log(child.stdin); // Previously: process.stdin (caused errors)

// After: Correctly returns null
const child = spawn("some-command", [], { stdio: "inherit" });
console.log(child.stdin); // Now: null (matches Node.js behavior)

感謝 @pfgithub 的修正!

已修正 net.connect() 中的無限迴圈

此版本解決了僅使用 null 或 undefined 引數呼叫 Socket.connect() 會進入無限迴圈的問題。現在,此方法可以正確地驗證輸入並拋出有意義的錯誤訊息。

const net = require("net");

// This would previously cause an infinite loop
// Now throws: 'The "options", "port", or "path" argument must be specified'
try {
  net.connect();
} catch (error) {
  console.error(error.message);
}

已修正 node:net 中的 resetAndDestroy()

此更新改進了 net 模組中的 socket 處理,以便在 socket 關閉或重設時獲得更一致的錯誤行為。

// Create a socket and use the new resetAndDestroy method
const socket = new net.Socket();
socket.resetAndDestroy();

// Error handling is now more consistent with proper error codes
socket.on("error", (err) => {
  console.log(err.code); // ERR_SOCKET_CLOSED
});

已修正 node:net 中的 socket 超時

修正了 Node.js 相容模式下 socket 超時的行為。實作現在可以正確地驗證超時值和回呼函式,確保與 Node.js 的行為一致。

// Setting socket timeout now validates input values
const socket = new net.Socket();

// Valid timeout values work as expected
socket.setTimeout(1000, () => console.log("Socket timed out"));

// Invalid values throw appropriate errors
socket.setTimeout("100"); // Throws ERR_INVALID_ARG_TYPE
socket.setTimeout(-1); // Throws ERR_OUT_OF_RANGE
socket.setTimeout(Infinity); // Throws ERR_OUT_OF_RANGE

// Large values are capped with a warning
socket.setTimeout(Number.MAX_SAFE_INTEGER);
// TimeoutOverflowWarning: Value does not fit into a 32-bit signed integer.
// Timer duration was truncated to 2147483647.

已修正 node:net 中的 write() 引數驗證

Bun 現在可以正確地驗證傳遞至 socket.write() 的引數,並在提供無效類型時拋出適當的錯誤。這與 Node.js 行為一致,以獲得更佳的相容性。

// Will throw TypeError with code ERR_STREAM_NULL_VALUES
socket.write(null);

// Will throw TypeError with code ERR_INVALID_ARG_TYPE
socket.write(true);
socket.write(1);
socket.write([]);
socket.write({});
// Only string, Buffer, TypedArray, or DataView are allowed

已修正 node:net 中的 allowHalfOpen

修正了 net.SocketallowHalfOpen 的實作,以便在可讀端結束時正確地強制關閉可寫端,與 Node.js 行為對齊。

const { Socket } = require("net");

// Create a socket that will auto-close when the readable side ends
const socket = new Socket({ allowHalfOpen: false });

// With this fix, the socket correctly registers a listener for the 'end' event
// to enforce the half-open connection policy

Bun 的前端開發伺服器

打包器和開發伺服器中的 Svelte 支援

我們透過新的官方外掛程式套件:bun-plugin-svelte 新增了對 Svelte 的內建支援。您現在可以在開發伺服器中使用 Svelte 元件(使用 HMR)和打包器。

// Import the plugin
import { SveltePlugin } from "bun-plugin-svelte";

// Use in Bun.build
Bun.build({
  entrypoints: ["src/index.ts"],
  outdir: "dist",
  target: "browser", // Also supports "bun" or "node" for server-side components
  plugins: [
    SveltePlugin({
      development: true, // Enable dev features, set to false for production
    }),
  ],
});

此外掛程式在 Svelte 元件中提供了開箱即用的 TypeScript 支援

<!-- App.svelte -->
<script lang="ts">
let name: string = "Bun";
</script>

<main>
  <h1>Hello {name}!</h1>
</main>

CSS 模組支援

我們在打包器中新增了 CSS 模組支援,讓您可以匯入 CSS,並自動產生本地範圍的類別名稱。副檔名為 .module.css 的檔案會自動被視為 CSS 模組。

// style.module.css
.button {
  background: blue;
  color: white;
}

.button:hover {
  background: darkblue;
}

// In your JavaScript file
import styles from './style.module.css';

// Use the generated class names
const button = document.createElement('button');
button.className = styles.button;
button.textContent = 'Click me';

支援的功能包括使用 composes 的類別名稱組成(在同一個檔案內、來自其他 CSS 模組檔案,或來自全域範圍)。實作會為本地範圍的類別和 ID 產生全域唯一的名稱。

改良的 HMR 支援

此版本為開發伺服器中的熱模組替換 (HMR) 帶來了顯著的改進,使其對於 JavaScript 開發人員而言更強大且功能更豐富。

// Self-accepting module using new import.meta.hot API
import.meta.hot.accept();

// Accept changes from dependencies
import * as foo from "./foo";
export let state = getState(foo);

// Handle updates from specific module
import.meta.hot.accept("./foo", (newFoo) => {
  state.foo = newFoo;
});

HMR 系統已完全重寫,以支援同步 ESM 匯入和現代 import.meta.hot.accept API 模式。這使 Bun 的 HMR 實作更接近其他現代開發工具,同時新增了獨特的最佳化。

HMR 程式碼現在會在生產環境中自動 DCE (無效程式碼消除),這表示在許多情況下,您可以在最上層使用 import.meta.hot API 呼叫,而無需將它們包裝在條件檢查中。

非字串 describe 標籤

Bun 的測試執行器現在接受數字、函式和類別(匿名和具名)作為 describe 區塊的第一個引數,這修正了 Jest 相容性問題。

// Using a number as describe label
describe(1, () => {
  test("works with number labels", () => {
    // ...
  });
});

// Using a class as describe label
class UserService {}
describe(UserService, () => {
  test("automatically uses the class name", () => {
    // ...
  });
});

// Using a function as describe label
function validateInput() {}
describe(validateInput, () => {
  test("automatically uses the function name", () => {
    // ...
  });
});

感謝 @reillyjodonnell 的貢獻!

錯誤修正

監聽前使用 server.close() 的錯誤

修正了 Node.js net.Server API 中回呼函式的處理方式。實作現在可以正確地將 onListen 回呼函式註冊為一次性事件監聽器,而不是直接呼叫它,從而提高與 Node.js 行為的相容性。

// Before, callback could be called incorrectly
const server = net.createServer();
server.listen(3000, () => {
  console.log("Server listening");
});

// Now follows Node.js behavior and handles edge cases properly
server.close(); // Can be called before the server is listening

已修正具有工作區覆寫的 bun.lock

我們修正了當載入包含具有不同名稱的工作區套件覆寫的 bun.lock 檔案時,bun install 會失敗的問題。現在,無論名稱差異如何,您都可以使用工作區套件成功覆寫 npm 套件。

// In package.json
{
  "name": "foo",
  "workspaces": ["packages/*"],
  "dependencies": {
    "one-dep": "1.0.0"
  },
  "overrides": {
    "no-deps": "workspace:packages/pkg1"
  }
}

// In packages/pkg1/package.json
{
  "name": "pkg1",
  "version": "2.2.2"
}

// After bun install, no-deps will point to the workspace package
// node_modules/no-deps/package.json will contain:
{
  "name": "pkg1",
  "version": "2.2.2"
}

感謝 @dylan-conway 的修正!

RegExp 中的 Unicode 錯誤

修正了影響 webpack 的回歸問題,該問題與正則表達式中的 Unicode 屬性逸出有關,尤其會影響基於腳本的屬性查找,例如 \p{Script=Hangul}。這解決了某些 Unicode 模式比對會失敗的相容性問題。

// Now working correctly
const pattern = /^\p{Script=Hangul}$/u;
console.log(pattern.test("한글")); // true

// Also fixed basic character class checks
console.log(/^(?:H|Hangul)$/.test("Hangul")); // true

已修正 Strict-Transport-Security 標頭

Bun 現在在使用 Bun.servenode:http 時,可以正確地支援在 HTTP 回應中傳送 Strict-Transport-Security 標頭。先前,當透過 HTTP 連線提供服務時,標頭會自動移除,但許多部署都依賴透過 NGINX 等工具代理 HTTP 流量,這些工具會處理 HTTPS 終止。

// With Bun.serve
Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello World", {
      headers: {
        "Strict-Transport-Security": "max-age=31536000",
      },
    });
  },
});

// With node:http
import http from "node:http";

http
  .createServer((req, res) => {
    res.writeHead(200, {
      "Strict-Transport-Security": "max-age=31536000",
    });
    res.end("Hello World");
  })
  .listen(3000);

已修正 package.json 中長套件名稱導致的崩潰

修正了當解析具有非常長的套件名稱的 package.json 時可能會導致崩潰的問題。這提高了處理具有異常長套件名稱的專案時的穩定性。

// Previously, this would crash when the package name was very long
const longNamePackage = {
  name: "extremely-long-package-name-that-would-cause-issues-with-fixed-buffer",
  version: "1.0.0",
};

// Now it parses correctly without crashing

感謝 @hudon 的修正!

test.failing 支援

Bun 現在支援 test.failing(),讓您可以標記您預期會失敗的測試。這些測試會反轉 - 如果它們拋出錯誤則通過,如果它們沒有拋出錯誤則失敗。這對於記錄需要修正的錯誤或用於測試驅動開發非常有用。

describe("add(a, b)", () => {
  test.failing("should return sum but not implemented yet", () => {
    // This test will pass overall because the expectation fails
    expect(add(1, 2)).toBe(3);
  });

  test.failing("this test will actually fail", () => {
    // This will cause the test to fail because it passes unexpectedly
    expect(true).toBe(true);
  });
});

感謝 @DonIsaac 的貢獻!

在匯入的檔案中使用 Jest 全域變數

Jest 全域變數(例如 expecttestdescribe)現在在測試套件的所有檔案中都可正確使用,而不僅僅是進入點檔案。這讓您可以定義 Jest 擴充功能、自訂比對器和在個別檔案中的測試輔助程式,而不會遇到參考錯誤。

// entry.test.js
import "./test-helpers.js";

test("can use helpers from imported file", () => {
  expect(1).toBeOne();
});

// test-helpers.js
expect.extend({
  toBeOne(actual) {
    return {
      pass: actual === 1,
      message: () => `expected ${actual} to be 1`,
    };
  },
});

感謝 @Electroid 的貢獻!

已修正 VSCode 擴充功能中執行具有特殊字元的測試

VS Code 擴充功能現在可以正確地處理名稱中具有特殊字元的測試。名稱包含大括號、括弧或其他特殊字元的測試現在可以直接透過 CodeLens「執行測試」或「監看測試」動作執行,而不會失敗或被略過。

// Test names with special characters now work correctly
test("can run with special chars :)", () => {
  // This test will now run properly when clicked in VS Code
});

test("parse {", () => {
  // Previously would fail the runner
});

test("something (something)", () => {
  // Previously would be skipped
});

感謝 @MarkSheinkman 的貢獻!

已修正關閉 WebSocket 時的錯誤處理

修正了當內部 WebSocket 執行個體不可用時,WebSocket 的 close()terminate() 方法會拋出錯誤的錯誤。這解決了特別是透過 CTRL+C 終止具有 Turbopack 的 Next.js 開發工作階段時的問題。

// Now checks if internal WebSocket exists before calling methods
webSocket.close(1000, "Normal closure");
webSocket.terminate();

改良的 socket 錯誤訊息

Socket 錯誤訊息現在包含更詳細的資訊,例如 syscalladdressport 屬性。此增強功能使偵錯與網路相關的問題變得更容易,並提供與 Node.js 的更佳相容性。

// When a network server fails to listen
const server = net.createServer();
server.listen(1234, "192.168.1.100");
server.on("error", (err) => {
  console.log(err.syscall); // "listen"
  console.log(err.address); // "192.168.1.100"
  console.log(err.port); // 1234
});

已修正搭配 Bun.serve() 路由的 WebSocket 升級

我們修正了在使用明確路由處理常式時 WebSocket 升級的問題。先前,WebSocket 連線僅在 catch-all 路由中才能正常運作,但現在它們可以在特定的路由路徑中正確運作。

// Define a server with explicit routes and WebSocket support
const server = Bun.serve({
  port: 3000,

  // WebSocket handler works with specific routes now
  websocket: {
    message(ws, message) {
      ws.send(`Echo: ${message}`);
    },
  },

  // Route-specific handlers properly handle WebSocket upgrades
  routes: {
    "/chat": (req, server) => {
      // This now works correctly
      if (server.upgrade(req)) {
        return; // Request was upgraded
      }
      return new Response("WebSocket connection required", { status: 400 });
    },
  },
});

其他變更

Alpine Linux 的更小二進位檔大小

由於最佳化的編譯設定和更新的 WebKit 相依性,以 Alpine Linux (musl libc) 為目標的 Bun 建置現在明顯更小。

bun publish 中的 NPM_CONFIG_TOKEN 支援

bun publish 現在遵循 NPM_CONFIG_TOKEN 環境變數,使其更容易在 GitHub Actions 等 CI 環境中設定自動發佈工作流程,而無需額外設定。

// In your CI workflow
process.env.NPM_CONFIG_TOKEN = "npm-token-from-secrets";
await $`bun publish`;

感謝 @KilianB

bun init <folder> 支援

您現在可以在初始化新的 Bun 專案時指定目標資料夾。如果目錄不存在,Bun 將會建立該目錄,並在其中初始化專案。

// Create a new project in a specific directory
bun init myproject -y

// The folder structure is created automatically
// myproject/
//   ├── .gitignore
//   ├── README.md
//   ├── bun.lock
//   ├── index.ts
//   ├── node_modules
//   ├── package.json
//   └── tsconfig.json

Bun.sql 中的動態欄位支援

您現在可以使用動態欄位選擇、更新操作和 "WHERE IN" 子句,讓 Bun.sql 中的資料庫操作更具彈性和直覺性。

// Dynamic column selection with rest parameters
await sql`INSERT INTO users ${sql(user, "name", "email")}`;

// Dynamic updates with selected columns
await sql`UPDATE users SET ${sql(user, "name", "email")} WHERE id = ${user.id}`;

// Use all object keys for updates
await sql`UPDATE users SET ${sql(user)} WHERE id = ${user.id}`;

// Simple "WHERE IN" with array of values
await sql`SELECT * FROM users WHERE id IN ${sql([1, 2, 3])}`;

// "WHERE IN" with array of objects
const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" },
];
await sql`SELECT * FROM users WHERE id IN ${sql(users, "id")}`;

感謝 @cirospaciari 的貢獻!

修復開發伺服器中的記憶體洩漏

此版本修復了 Bun 開發伺服器中的記憶體洩漏問題,透過在伺服器關閉時正確地釋放資源。這些變更改善了在長時間運行 Bun 開發伺服器時的記憶體管理和穩定性。

// Memory leaks are now properly handled when stopping the dev server
const devServer = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello World");
  },
});

// Later when you want to shut down
devServer.stop();
// Resources are now properly cleaned up

server.reload() 速度提升 30%

降低計時器中的記憶體使用量

更快的 TextDecoder 初始化速度

@types/bun 的改進

此版本包含 Bun 中 TypeScript 類型定義的重大改進,解決了各種問題,並為多個 API 新增了更好的類型支援。

// Better *.svg module declarations for frontend dev server
declare module "*.svg" {
  var contents: `${string}.svg`;
  export = contents;
}

// Improved ShellError class types with full method definitions
const output = await $`echo '{"hello": 123}'`;
console.log(output.json()); // { hello: 123 }

感謝 @alii 的貢獻!

改進 ReadableStream 的錯誤訊息

Bun 現在在使用 type: "direct" 的 ReadableStream 時提供更具描述性的錯誤訊息。您現在將看到關於錯誤原因的具體資訊,而不是通用的 "Expected Sink" 錯誤,例如嘗試在串流關閉後使用控制器時。

// Before: Generic "Expected Sink" error
// Now: Detailed error message
const stream = new ReadableStream({
  type: "direct",
  async pull(controller) {
    controller.write("data");
    // If you try to use the controller after pull() returns:
    // Error: This HTTPResponseSink has already been closed.
    // A "direct" ReadableStream terminates its underlying socket once `async pull()` returns.
  },
});

感謝 @paperclover 的貢獻!

HMR 事件改進

熱模組重載 API 已透過完全實現的事件系統得到增強,允許開發人員監聽各種 HMR 生命周期事件。這使得在 Bun 的開發伺服器中可以更精確地控制熱模組替換過程。

// Listen for an event before hot updates are applied
import.meta.hot.on("bun:beforeUpdate", () => {
  console.log("Preparing for hot update...");
});

// Clean up when no longer needed
import.meta.hot.off("bun:beforeUpdate", listener);

事件包括 bun:beforeUpdatebun:afterUpdatebun:errorbun:ws:connect 等。為了相容性,也支援 Vite 風格的事件名稱(帶有 vite: 前綴)。

感謝 @paperclover

修復 node:net 中的 ipv6Only

修復了 net.Server.listen()ipv6Only 選項的實作,以在指定時正確停用雙堆疊支援。這確保當您設定 ipv6Only: true 時,伺服器將僅監聽 IPv6 位址,而不接受 IPv4 連線。

const server = net.createServer();
server.listen(
  {
    host: "::",
    port: 0,
    ipv6Only: true,
  },
  () => {
    console.log("Server is now listening only on IPv6");
  },
);

修復 Bun.sql 中的 SQL 參數處理

修復了 PostgreSQL 驅動程式中的一個錯誤,該錯誤導致語句狀態過早設定為已準備,從而導致參數驗證問題。此修復正確處理了查詢和提供的數值之間參數計數不符的情況。

// Before: Could encounter errors when parameter counts didn't match
const sql = new SQL("postgres://user:pass@localhost:5432/db");
await sql.query("SELECT * FROM users WHERE id = $1"); // Missing parameter

// After: Provides clearer error messages about parameter mismatches
// Error: PostgresError: bind message supplies 0 parameters, but prepared statement requires 1

修復帶有空主體的 new File()

File 建構函式現在可以正確處理使用空主體但指定名稱建立檔案的情況。先前,這會導致意外行為。

// Now works correctly
const file = new File([], "empty.txt", { type: "text/plain;charset=utf-8" });
console.log(file.name); // "empty.txt"
console.log(file.size); // 0
console.log(file.type); // "text/plain;charset=utf-8"

感謝 @cirospaciari 修復!

修復捆綁器中未縮減的識別符號衝突

修復了一個捆綁錯誤,該錯誤導致在解析期間區塊作用域變數未正確提升,從而在捆綁具有相同變數名稱的多個模組時導致識別符號衝突。

// Before: These two files would conflict when bundled
// foo.js
{
  var d = 0;
}
export const foo = () => {};

// bar.js
function d() {}
export function bar() {
  d.length;
}

// After: The bundler now correctly handles this case
// without causing identifier conflicts

感謝 @jbarrieault 修復!

感謝 25 位貢獻者!

@190n @alii @aryzing @brycefranzen @cirospaciari @cngJo @daniellionel01 @DonIsaac @dylan-conway @Electroid @heimskr @hudon @Jarred-Sumner @jbarrieault @KilianB @malonehedges @MarkSheinkman @mayfieldiv @Nanome203 @nektro @paperclover @pfgithub @Pranav2612000 @reillyjodonnell @zackradisic