import { writable } from 'svelte/store'; export interface AuthUser { id: string; email: string; } export type AuthState = | { status: 'unknown' } | { status: 'authenticated'; user: AuthUser } | { status: 'unauthenticated' }; function createAuthStore() { const { subscribe, set } = writable({ status: 'unknown' }); /** Calls GET /api/v1/auth/me and updates the store. Never throws. */ async function refresh(): Promise { try { const res = await fetch('/api/v1/auth/me', { credentials: 'include' }); if (res.ok) { const user = (await res.json()) as AuthUser; const next: AuthState = { status: 'authenticated', user }; set(next); return next; } } catch { // Network failure: fall through to unauthenticated. The login page's own // fetch will surface a retry message if the user tries to act. } const next: AuthState = { status: 'unauthenticated' }; set(next); return next; } async function logout(): Promise { try { await fetch('/api/v1/auth/logout', { method: 'POST', credentials: 'include' }); } finally { set({ status: 'unauthenticated' }); } } return { subscribe, refresh, logout }; } export const auth = createAuthStore();