From 25a5fee24e42f4d5bb6f5edfe9bc2065f8efef4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Filipe=20Caba=C3=A7o?= Date: Wed, 11 Dec 2024 14:50:55 +0000 Subject: [PATCH] fix: ws conditional import (#444) only import types and ws dependency if NATIVE_WEBSOCKET_AVAILABLE not available --- src/RealtimeClient.ts | 34 ++++++++++++++------------- vitest.config.ts => vitest.config.mts | 0 2 files changed, 18 insertions(+), 16 deletions(-) rename vitest.config.ts => vitest.config.mts (100%) diff --git a/src/RealtimeClient.ts b/src/RealtimeClient.ts index 871dff9..2ddb8cf 100755 --- a/src/RealtimeClient.ts +++ b/src/RealtimeClient.ts @@ -1,5 +1,3 @@ -import type { WebSocket as WSWebSocket } from 'ws' - import { CHANNEL_EVENTS, CONNECTION_STATE, @@ -62,8 +60,13 @@ export interface WebSocketLikeConstructor { options?: { headers: Object | undefined } ): WebSocketLike } +const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined' -export type WebSocketLike = WebSocket | WSWebSocket | WSWebSocketDummy +const WSWebSocket = NATIVE_WEBSOCKET_AVAILABLE + ? WebSocket + : require('ws').WebSocket + +export type WebSocketLike = WebSocket | typeof WSWebSocket | WSWebSocketDummy export interface WebSocketLikeError { error: any @@ -71,7 +74,6 @@ export interface WebSocketLikeError { type: string } -const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined' const WORKER_SCRIPT = ` addEventListener("message", (e) => { if (e.data.event === "start") { @@ -204,20 +206,20 @@ export default class RealtimeClient { this.conn = new WebSocket(this.endpointURL()) this.setupConnection() return - } - - this.conn = new WSWebSocketDummy(this.endpointURL(), undefined, { - close: () => { - this.conn = null - }, - }) + } else { + this.conn = new WSWebSocketDummy(this.endpointURL(), undefined, { + close: () => { + this.conn = null + }, + }) - import('ws').then(({ default: WS }) => { - this.conn = new WS(this.endpointURL(), undefined, { - headers: this.headers, + import('ws').then(({ default: WS }) => { + this.conn = new WS(this.endpointURL(), undefined, { + headers: this.headers, + }) + this.setupConnection() }) - this.setupConnection() - }) + } } /** diff --git a/vitest.config.ts b/vitest.config.mts similarity index 100% rename from vitest.config.ts rename to vitest.config.mts