import { ensure } from "ensured"; import type { Client } from "magicbell-js/user-client"; import WebSocket from "reconnecting-websocket"; import { Collection } from "tinycoll"; import { getSessionId } from "../context/context"; import { getApiKeyFromToken } from "../lib/jwt"; import { log } from "../lib/log"; import { isOK } from "../lib/response"; type Options = { client: Client; socketUrl?: string; }; type Event = { id: string; name: string; data: { id: string; [key: string]: unknown; }; }; function getWebSocket(): typeof WebSocket { if (typeof WebSocket === "function") return WebSocket; // @ts-ignore - wrong typings - https://github.com/pladaria/reconnecting-websocket/issues/196 if ("default" in WebSocket && typeof WebSocket.default === "function") { // @ts-ignore return WebSocket.default; } throw Error("WebSocket is not defined"); } export class RealtimeStore extends Collection { #socketUrl = "wss://ws.magicbell.com"; #origin; #client: Client; #socket: WebSocket | null = null; #token: string | null = null; constructor(options: Options) { super("realtime"); if (options.socketUrl) { this.#socketUrl = options.socketUrl; } this.#client = options.client; const WS = getWebSocket(); // @ts-ignore this.#socket = new WS(() => this.#getUrl(), [], { startClosed: typeof window === "undefined" || typeof document === "undefined" }); this.#socket.addEventListener("message", event => { if (event.origin !== this.#origin) return; try { const data = JSON.parse(event.data); this.insert(data); log.debug("socket: received message", data); } catch (e) { log.error("socket: failed to parse message", { data: event.data, error: e }); } }); this.#socket.addEventListener("open", () => { log.info("socket: open"); }); this.#socket.addEventListener("close", () => { log.info("socket: close"); }); this.#socket.addEventListener("error", err => { log.error("socket: error", err); }); } async #getUrl() { const jwtToken = this.#client.config.token; ensure(jwtToken, "MagicBell JWT token missing from client config"); const apiKey = getApiKeyFromToken(jwtToken); ensure(apiKey, "Failed to extract API key from JWT token"); const token = await this.#getToken(); const url = new URL(this.#socketUrl); url.searchParams.set("api_key", apiKey); url.searchParams.set("token", token); this.#origin = url.origin; return url.toString(); } async #getToken() { if (this.#token) return this.#token; const { data, metadata: res } = await this.#client.channels.saveInboxToken({ token: getSessionId() }); ensure(isOK(res), `Failed to save Inbox token: ${res.status} ${res.statusText}`); ensure(data?.token, "Unexpected server response, missing token"); this.#token = data.token; return this.#token; } listen(filter: Parameters["find"]>[0], cb: (event: Event) => void) { this.find(filter).observe(change => { if (change.type !== "added") return; cb(change.doc); }); } }