// auth.svelte.ts — Auth store (Svelte 5 runes) // Cookie-based auth with SuperOAuth PKCE import { apiFetch } from '$lib/api'; export interface User { id: number; nickname: string; avatar_url?: string; [key: string]: unknown; } let user = $state(null); let loading = $state(true); async function refresh() { try { const data = await apiFetch('/auth/me'); user = data as User; } catch { user = null; } } async function init() { await refresh(); loading = false; // Listen for expired session if (typeof window !== 'undefined') { window.addEventListener('auth:expired', () => { user = null; }); } } async function logout() { try { await apiFetch('/auth/logout', { method: 'POST' }); } catch { // ignore } user = null; } async function editUser(updatedFields: Record) { if (!user) return; const data = await apiFetch(`/users/${user.id}`, { method: 'PUT', body: JSON.stringify(updatedFields), }); if (data?.user) { user = { ...user, ...data.user }; } } export const authStore = { get user() { return user; }, get loading() { return loading; }, init, refresh, logout, editUser, };