Repository Public
1"use client";23export class ApiClientError extends Error {4 constructor(public status: number, public code: string, message: string, public details?: unknown) { super(message); }5}67let csrf: string | null = null;8export const setCsrf = (t: string | null) => { csrf = t; };9export const getCsrf = () => csrf;1011/** JSON fetch against our own API. Network failures surface as code "network". */12export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown; raw?: BodyInit; headers?: Record<string, string>; keepalive?: boolean } = {}): Promise<T> {13 let res: Response;14 try {15 res = await fetch(path, {16 method: init.method ?? (init.body !== undefined || init.raw !== undefined ? "POST" : "GET"),17 headers: { ...(init.body !== undefined ? { "Content-Type": "application/json" } : {}), ...(csrf ? { "X-CSRF-Token": csrf } : {}), ...(init.headers ?? {}) },18 body: init.raw ?? (init.body !== undefined ? JSON.stringify(init.body) : undefined),19 credentials: "same-origin", cache: "no-store", keepalive: init.keepalive,20 });21 } catch { throw new ApiClientError(0, "network", "Network error"); }22 const text = await res.text();23 let data: unknown = null;24 try { data = text ? JSON.parse(text) : null; } catch { /* not JSON */ }25 if (!res.ok) {26 // The session ended (expired or revoked elsewhere): back to the sign-in page.27 if (res.status === 401 && !path.startsWith("/api/v1/auth/") && typeof window !== "undefined" && !/^\/(login|setup)/.test(window.location.pathname)) window.location.assign("/login");28 const e = (data as { error?: { code?: string; message?: string; details?: unknown } } | null)?.error;29 throw new ApiClientError(res.status, e?.code ?? "http_" + res.status, e?.message ?? `HTTP ${res.status}`, e?.details);30 }31 return data as T;32}33