'use client'; /** Fetch wrapper with automatic access-token refresh on 401. */ let refreshing: Promise | null = null; async function tryRefresh(): Promise { if (!refreshing) { refreshing = fetch('/api/auth/refresh', { method: 'POST' }) .then((r) => r.ok) .catch(() => false) .finally(() => setTimeout(() => (refreshing = null), 100)); } return refreshing; } export class ApiClientError extends Error { status: number; constructor(status: number, message: string) { super(message); this.status = status; } } export async function api(path: string, init?: RequestInit & { json?: unknown }): Promise { const opts: RequestInit = { ...init }; if (init?.json !== undefined) { opts.body = JSON.stringify(init.json); opts.headers = { 'Content-Type': 'application/json', ...(init.headers ?? {}) }; } let res = await fetch(path, opts); if (res.status === 401 && !path.startsWith('/api/auth/')) { const ok = await tryRefresh(); if (ok) res = await fetch(path, opts); else if (typeof window !== 'undefined') { window.location.href = '/login'; throw new ApiClientError(401, 'Session expired'); } } if (!res.ok) { let message = `Request failed (${res.status})`; try { const data = await res.json(); if (data?.error) message = data.error; else if (data?.message) message = data.message; } catch { /* not json */ } throw new ApiClientError(res.status, message); } const ct = res.headers.get('content-type') ?? ''; return (ct.includes('json') ? res.json() : res.text()) as Promise; }