From 5398aa0ca34601834809cbedc17ac4fe322e1e6d Mon Sep 17 00:00:00 2001 From: coso Date: Mon, 30 Mar 2026 14:55:03 +0800 Subject: [PATCH] fix: support global event source in dev bridge --- src/lib/dev-bridge/http-client.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/lib/dev-bridge/http-client.ts b/src/lib/dev-bridge/http-client.ts index 4fcbc60b3..761fd2a45 100644 --- a/src/lib/dev-bridge/http-client.ts +++ b/src/lib/dev-bridge/http-client.ts @@ -35,6 +35,18 @@ interface DevBridgeEventHub { const bridgeEventHubs = new Map(); +function resolveEventSourceConstructor(): typeof EventSource | null { + if (typeof window !== "undefined" && typeof window.EventSource === "function") { + return window.EventSource; + } + + if (typeof globalThis.EventSource === "function") { + return globalThis.EventSource; + } + + return null; +} + function toErrorMessage(error: unknown): string { if (error instanceof Error) { return error.message || error.name || "Unknown error"; @@ -110,7 +122,7 @@ export function hasDevBridgeEventListenerCapability(): boolean { return ( isDevBridgeAvailable() && typeof window !== "undefined" && - typeof window.EventSource === "function" + resolveEventSourceConstructor() !== null ); } @@ -149,7 +161,12 @@ export async function listenViaHttpEvent( let hub = bridgeEventHubs.get(normalizedEvent); if (!hub) { - const source = new window.EventSource( + const EventSourceConstructor = resolveEventSourceConstructor(); + if (!EventSourceConstructor) { + throw new Error(`[DevBridge] 浏览器模式事件桥不可用: ${event}`); + } + + const source = new EventSourceConstructor( `${BRIDGE_EVENTS_URL}?event=${encodeURIComponent(normalizedEvent)}`, ); const listeners = new Set>();