From 82824e5f6d409e7d90b5d63e58dea160c9facfe4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 22:00:23 -0500 Subject: [PATCH] fix(bun): add ws error handler for Node/Deno parity; hoist TextDecoder Signed-off-by: Diego Resendez --- src/bun.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/bun.ts b/src/bun.ts index 4da5579..9169db7 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -16,6 +16,7 @@ interface BunWebSocketHandler { open?(ws: BunServerWebSocket): void; message(ws: BunServerWebSocket, message: string | Uint8Array): void; close?(ws: BunServerWebSocket, code: number, reason: string): void; + error?(ws: BunServerWebSocket, error?: unknown): void; } interface BunServer { port: number; @@ -32,6 +33,8 @@ interface BunServeOptions { type BunServeShortOptions = { port?: number; hostname?: string }; declare const Bun: { serve(options: BunServeOptions): BunServer }; +const decoder = new TextDecoder(); + /** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ interface BunConnData { wsReq: WsRequest; @@ -119,13 +122,18 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { message(ws, message) { const { inbound } = ws.data as BunConnData; // decode binary to UTF-8 to match Node's Buffer.toString() (cross-adapter parity) - inbound.push(typeof message === 'string' ? message : new TextDecoder().decode(message)); + inbound.push(typeof message === 'string' ? message : decoder.decode(message)); }, close(ws) { const { inbound, ac } = ws.data as BunConnData; inbound.close(); ac.abort(); }, + error(ws) { + const { inbound, ac } = ws.data as BunConnData; + inbound.fail(new Error('websocket error')); + ac.abort(); + }, }, }); }