UNPKG

better-auth

Version:

The most comprehensive authentication framework for TypeScript.

46 lines (45 loc) 1.44 kB
//#region src/client/broadcast-channel.ts const kBroadcastChannel = Symbol.for("better-auth:broadcast-channel"); const now = () => Math.floor(Date.now() / 1e3); var WindowBroadcastChannel = class { listeners = /* @__PURE__ */ new Set(); name; constructor(name = "better-auth.message") { this.name = name; } subscribe(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; } post(message) { if (typeof window === "undefined") return; try { localStorage.setItem(this.name, JSON.stringify({ ...message, timestamp: now() })); } catch {} } setup() { if (typeof window === "undefined" || typeof window.addEventListener === "undefined") return () => {}; const handler = (event) => { if (event.key !== this.name) return; const message = JSON.parse(event.newValue ?? "{}"); if (message?.event !== "session" || !message?.data) return; this.listeners.forEach((listener) => listener(message)); }; window.addEventListener("storage", handler); return () => { window.removeEventListener("storage", handler); }; } }; function getGlobalBroadcastChannel(name = "better-auth.message") { if (!globalThis[kBroadcastChannel]) globalThis[kBroadcastChannel] = new WindowBroadcastChannel(name); return globalThis[kBroadcastChannel]; } //#endregion export { getGlobalBroadcastChannel, kBroadcastChannel }; //# sourceMappingURL=broadcast-channel.mjs.map