import { Client } from "magicbell-js/user-client"; import { setDebug } from "../lib/debug"; import { generateID } from "../lib/id"; import { memo } from "../lib/memo"; import { NotificationStore } from "../stores/notification-store"; import { RealtimeStore } from "../stores/realtime-store"; export type MagicBellContext = { client: Client; socket: RealtimeStore; notifications: NotificationStore; sessionId: string; }; export type MagicBellProviderProps = { token: string; baseUrl?: string; socketUrl?: string; children?: any; }; export function getSessionId() { if (typeof sessionStorage === "undefined") { return generateID(64); } // sessionStorage gets cleared when the page session ends. A page // session lasts for as long as the browser is open and survives // over page reloads and restores. Opening a page in a new tab or // window will cause a new session to be initiated. This gives us // a stable ID per tab, and different ID's across tabs. const stored = sessionStorage.getItem("magicbell--realtime-token"); if (stored) return stored; const id = generateID(64); sessionStorage.setItem("magicbell--realtime-token", id); return id; } export function createMagicBellContext(props: MagicBellProviderProps): MagicBellContext { const cacheKey = [props.token, props.baseUrl || "", props.socketUrl || ""]; const client = memo(["client", ...cacheKey], () => new Client({ token: props.token, baseUrl: props.baseUrl })); const socket = memo(["socket", ...cacheKey], () => new RealtimeStore({ client: client, socketUrl: props.socketUrl })); const notifications = memo(["notifications", ...cacheKey], () => new NotificationStore({ client: client, socket: socket })); const ctx: MagicBellContext = { client, socket, notifications, sessionId: getSessionId() }; setDebug("ctx", ctx); return ctx; }