Skip to content

Commit

Permalink
fix: ws conditional import (#444)
Browse files Browse the repository at this point in the history
only import types and ws dependency if NATIVE_WEBSOCKET_AVAILABLE not available
  • Loading branch information
filipecabaco authored Dec 11, 2024
1 parent 9ef7649 commit 25a5fee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions src/RealtimeClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import type { WebSocket as WSWebSocket } from 'ws'

import {
CHANNEL_EVENTS,
CONNECTION_STATE,
Expand Down Expand Up @@ -62,16 +60,20 @@ 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
message: string
type: string
}

const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined'
const WORKER_SCRIPT = `
addEventListener("message", (e) => {
if (e.data.event === "start") {
Expand Down Expand Up @@ -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()
})
}
}

/**
Expand Down
File renamed without changes.

0 comments on commit 25a5fee

Please sign in to comment.