// Client-safe fetchers for the app's own same-origin /api/* route handlers. // MUST NOT import any server module — this runs in the browser. // Route handlers respond with the data as JSON on success, or // `{ error: string, ... }` with a 4xx/5xx status on failure. export class ApiError extends Error { status: number; data?: unknown; constructor(message: string, status: number, data?: unknown) { super(message); this.name = "ApiError"; this.status = status; this.data = data; } } function safeJson(text: string): unknown { try { return JSON.parse(text); } catch { return text; } } async function clientFetch(path: string, init?: RequestInit): Promise { const res = await fetch(path, { ...init, headers: { ...(init?.body ? { "Content-Type": "application/json" } : {}), ...init?.headers }, }); const text = await res.text(); const body = text ? safeJson(text) : undefined; if (!res.ok) { const message = (body && typeof body === "object" && "error" in body ? String((body as Record).error) : null) || `Request failed (${res.status})`; // 401 means the session is missing/expired — bounce to login. if (res.status === 401 && typeof window !== "undefined") { window.location.assign("/login"); } if ( res.status === 403 && typeof window !== "undefined" && (body as Record | undefined)?.phoneVerificationRequired === true && window.location.pathname !== "/register/verify" ) { window.location.assign("/register/verify"); } throw new ApiError(message, res.status, body); } return body as T; } export const apiGet = (path: string): Promise => clientFetch(path); export const apiPost = (path: string, body?: unknown): Promise => clientFetch(path, { method: "POST", body: body !== undefined ? JSON.stringify(body) : undefined }); export const apiPut = (path: string, body?: unknown): Promise => clientFetch(path, { method: "PUT", body: body !== undefined ? JSON.stringify(body) : undefined });