const BASE = (import.meta.env.VITE_API_BASE as string | undefined) || "/api"; export const API_BASE = BASE.replace(/\/$/, ""); async function parseError(res: Response): Promise { try { const data = await res.json(); return data?.detail || res.statusText; } catch { return res.statusText; } } export async function request( path: string, options: RequestInit = {}, ): Promise { const url = `${API_BASE}${path}`; const res = await fetch(url, { credentials: "same-origin", ...options, }); if (!res.ok) { throw new Error(await parseError(res)); } if (res.status === 204) return null as T; const contentType = res.headers.get("content-type") || ""; if (contentType.includes("application/json")) { return (await res.json()) as T; } return (await res.text()) as T; } export async function postForm(path: string, data: FormData): Promise { return request(path, { method: "POST", body: data }); } export async function postJson( path: string, body: unknown, ): Promise { return request(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); } export async function putJson(path: string, body: unknown): Promise { return request(path, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); }