type JsonErrorPayload = { error?: string; message?: string; detail?: unknown; }; const MAX_ERROR_TEXT = 240; function summarizeResponseText(raw: string): string { const compact = raw.replace(/\s+/g, " ").trim(); if (!compact) return ""; if (compact.length <= MAX_ERROR_TEXT) return compact; return `${compact.slice(0, MAX_ERROR_TEXT - 3)}...`; } function defaultHttpMessage(response: Response): string { const suffix = response.statusText?.trim() ? ` ${response.statusText.trim()}` : ""; return `HTTP ${response.status}${suffix}`; } function stringifyDetail(detail: unknown): string { if (typeof detail === "string") return detail.trim(); if (Array.isArray(detail)) { const parts = detail .map((item) => { if (typeof item === "string") return item.trim(); if (item && typeof item === "object" && "msg" in item) { return String((item as { msg?: unknown }).msg ?? "").trim(); } return ""; }) .filter(Boolean); return parts.join("; "); } if (detail && typeof detail === "object") { try { return summarizeResponseText(JSON.stringify(detail)); } catch { return ""; } } return ""; } function extractErrorMessage( response: Response, raw: string, payload: JsonErrorPayload | null, ): string { const candidate = (typeof payload?.error === "string" && payload.error.trim()) || (typeof payload?.message === "string" && payload.message.trim()) || stringifyDetail(payload?.detail) || summarizeResponseText(raw); return candidate || defaultHttpMessage(response); } export async function fetchJsonResponse(url: string, init?: RequestInit): Promise { let response: Response; try { response = await fetch(url, { cache: "no-store", ...init }); } catch (error) { const message = error instanceof Error && error.message.trim() ? error.message : "Network request failed"; throw new Error(`Failed to fetch ${url}: ${message}`); } const raw = await response.text(); const trimmed = raw.trim(); let payload: (T & JsonErrorPayload) | null = null; if (trimmed) { try { payload = JSON.parse(trimmed) as T & JsonErrorPayload; } catch { if (!response.ok) { throw new Error(extractErrorMessage(response, trimmed, null)); } throw new Error(`Invalid JSON response from ${url}`); } } if (!response.ok) { throw new Error(extractErrorMessage(response, trimmed, payload)); } if (payload !== null) { return payload as T; } return {} as T; } export async function readErrorMessage(response: Response): Promise { let raw = ""; try { raw = (await response.text()).trim(); } catch { raw = ""; } let payload: JsonErrorPayload | null = null; if (raw) { try { payload = JSON.parse(raw) as JsonErrorPayload; } catch { payload = null; } } return extractErrorMessage(response, raw, payload); }