| 48 | } |
| 49 | |
| 50 | export class ServerEventBus { |
| 51 | #eventTarget: EventTarget |
| 52 | #clients = new Set<WebSocket>() |
| 53 | #sseClients = new Set<http.ServerResponse>() |
| 54 | #server: http.Server | null = null |
| 55 | #wssServer: WebSocketServer | null = null |
| 56 | #port: number |
| 57 | #host: string |
| 58 | #debug: boolean |
| 59 | #externalServer: HttpServerLike | null = null |
| 60 | #externalRequestHandler: |
| 61 | | ((req: http.IncomingMessage, res: http.ServerResponse) => void) |
| 62 | | null = null |
| 63 | #externalUpgradeHandler: |
| 64 | | ((req: http.IncomingMessage, socket: Duplex, head: Buffer) => void) |
| 65 | | null = null |
| 66 | #dispatcher = (e: Event) => { |
| 67 | const event = (e as CustomEvent).detail |
| 68 | this.debugLog('Dispatching event from dispatcher, forwarding', event) |
| 69 | this.emit(event) |
| 70 | } |
| 71 | #connectFunction = () => { |
| 72 | this.debugLog( |
| 73 | 'Connection request made to event-bus, replying back with success', |
| 74 | ) |
| 75 | this.#eventTarget.dispatchEvent(new CustomEvent('tanstack-connect-success')) |
| 76 | } |
| 77 | constructor({ |
| 78 | port = 4206, |
| 79 | host = 'localhost', |
| 80 | debug = false, |
| 81 | httpServer, |
| 82 | }: ServerEventBusConfig = {}) { |
| 83 | this.#port = port |
| 84 | this.#host = host |
| 85 | this.#eventTarget = |
| 86 | globalThis.__TANSTACK_EVENT_TARGET__ ?? new EventTarget() |
| 87 | // we want to set the global event target only once so that we can emit/listen to events on the server |
| 88 | if (!globalThis.__TANSTACK_EVENT_TARGET__) { |
| 89 | globalThis.__TANSTACK_EVENT_TARGET__ = this.#eventTarget |
| 90 | } |
| 91 | this.#server = globalThis.__TANSTACK_DEVTOOLS_SERVER__ ?? null |
| 92 | this.#wssServer = globalThis.__TANSTACK_DEVTOOLS_WSS_SERVER__ ?? null |
| 93 | this.#externalServer = httpServer ?? null |
| 94 | this.#debug = debug |
| 95 | this.debugLog('Initializing server event bus') |
| 96 | } |
| 97 | |
| 98 | private debugLog(...args: Array<any>) { |
| 99 | if (this.#debug) { |
| 100 | console.log('🌴 [tanstack-devtools:server-bus] ', ...args) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | private emitToServer(event: TanStackDevtoolsEvent<string>) { |
| 105 | this.debugLog('Emitting event to specific server listeners', event) |
| 106 | this.#eventTarget.dispatchEvent( |
| 107 | new CustomEvent(event.type, { detail: event }), |