|
1 | | -import type { WebSocket as WSWebSocket } from 'ws' |
2 | | - |
3 | 1 | import { |
4 | 2 | CHANNEL_EVENTS, |
5 | 3 | CONNECTION_STATE, |
@@ -62,16 +60,20 @@ export interface WebSocketLikeConstructor { |
62 | 60 | options?: { headers: Object | undefined } |
63 | 61 | ): WebSocketLike |
64 | 62 | } |
| 63 | +const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined' |
65 | 64 |
|
66 | | -export type WebSocketLike = WebSocket | WSWebSocket | WSWebSocketDummy |
| 65 | +const WSWebSocket = NATIVE_WEBSOCKET_AVAILABLE |
| 66 | + ? WebSocket |
| 67 | + : require('ws').WebSocket |
| 68 | + |
| 69 | +export type WebSocketLike = WebSocket | typeof WSWebSocket | WSWebSocketDummy |
67 | 70 |
|
68 | 71 | export interface WebSocketLikeError { |
69 | 72 | error: any |
70 | 73 | message: string |
71 | 74 | type: string |
72 | 75 | } |
73 | 76 |
|
74 | | -const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined' |
75 | 77 | const WORKER_SCRIPT = ` |
76 | 78 | addEventListener("message", (e) => { |
77 | 79 | if (e.data.event === "start") { |
@@ -204,20 +206,20 @@ export default class RealtimeClient { |
204 | 206 | this.conn = new WebSocket(this.endpointURL()) |
205 | 207 | this.setupConnection() |
206 | 208 | return |
207 | | - } |
208 | | - |
209 | | - this.conn = new WSWebSocketDummy(this.endpointURL(), undefined, { |
210 | | - close: () => { |
211 | | - this.conn = null |
212 | | - }, |
213 | | - }) |
| 209 | + } else { |
| 210 | + this.conn = new WSWebSocketDummy(this.endpointURL(), undefined, { |
| 211 | + close: () => { |
| 212 | + this.conn = null |
| 213 | + }, |
| 214 | + }) |
214 | 215 |
|
215 | | - import('ws').then(({ default: WS }) => { |
216 | | - this.conn = new WS(this.endpointURL(), undefined, { |
217 | | - headers: this.headers, |
| 216 | + import('ws').then(({ default: WS }) => { |
| 217 | + this.conn = new WS(this.endpointURL(), undefined, { |
| 218 | + headers: this.headers, |
| 219 | + }) |
| 220 | + this.setupConnection() |
218 | 221 | }) |
219 | | - this.setupConnection() |
220 | | - }) |
| 222 | + } |
221 | 223 | } |
222 | 224 |
|
223 | 225 | /** |
|
0 commit comments