import { useAuthStore } from './store'; /** * Cross-tab auth synchronisation via the `storage` event. * * When a user logs out (or in) in tab A, other tabs need to pick up the * new state without the user clicking around. The storage event fires on * every other tab when localStorage changes — bumping a version key in * tab A causes tabs B, C, ... to re-run the auth probe and converge. * * Pattern is one-way: this tab writes the version key on its own auth * transitions; storage events trigger `initialize()` to re-read state from * Directus. The actual auth state lives in cookies (server-issued), not in * localStorage — the version key is just a "something changed, re-check" * signal. * * Idempotent: safe to call multiple times (HMR-friendly). */ const VERSION_KEY = 'trm-auth-version'; let started = false; export function startCrossTabSync(): void { if (started) return; started = true; let lastStatus: string | null = null; useAuthStore.subscribe((state) => { if (state.status === lastStatus) return; lastStatus = state.status; try { localStorage.setItem(VERSION_KEY, String(Date.now())); } catch { // localStorage may be unavailable (private browsing, quota). Sync // silently no-ops; auth still works in this tab, just not cross-tab. } }); window.addEventListener('storage', (ev) => { if (ev.key !== VERSION_KEY) return; void useAuthStore.getState().initialize(); }); }