import type { ApiResponse } from "@/types/api"; // API routes are served by Next.js App Router — no external base URL needed. const API_BASE_URL = ""; const DEFAULT_TIMEOUT_MS = 30_000; function fetchWithTimeout( url: string, options: RequestInit, timeoutMs = DEFAULT_TIMEOUT_MS, ): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); return fetch(url, { credentials: "same-origin", ...options, signal: controller.signal, }).finally(() => clearTimeout(timer)); } export interface ApiClientErrorDetails { upstreamCode?: string; upstreamRequestId?: string; upstreamHostId?: string; upstreamStatus?: number; [key: string]: unknown; } class ApiClientError extends Error { code: string; status: number; requestId?: string; traceId?: string; details?: ApiClientErrorDetails; constructor( code: string, message: string, status: number, requestId?: string, traceId?: string, details?: ApiClientErrorDetails, ) { super(message); this.name = "ApiClientError"; this.code = code; this.status = status; this.requestId = requestId; this.traceId = traceId; this.details = details; } /** * `[CODE] message` for UI display. Prefers the upstream code (e.g. * `SignatureDoesNotMatch`) over our internal bucket code (`OSS_FORBIDDEN`) * because the upstream value is what helps a user / support agent * distinguish "bad creds" from "clock drift" from "actually denied". */ get displayMessage(): string { const upstreamCode = this.details?.upstreamCode; // Some gateways mask a supported business error as // OTSInternalServerError. When the BFF recovered the canonical code, that // code is more useful to the user while the raw upstream value remains in // details for diagnostics. const prefix = upstreamCode === "OTSInternalServerError" && this.code !== "INTERNAL_SERVER_ERROR" ? this.code : upstreamCode || this.code; return prefix ? `[${prefix}] ${this.message}` : this.message; } } const HTTP_STATUS_CODE_MAP: Record = { 401: "UNAUTHORIZED", 403: "FORBIDDEN", 404: "NOT_FOUND", 429: "RATE_LIMITED", 503: "SERVICE_UNAVAILABLE", }; async function handleResponse(response: Response): Promise { if (!response.ok) { let errorCode = HTTP_STATUS_CODE_MAP[response.status] ?? "UNKNOWN_ERROR"; let errorMessage = `Request failed with status ${response.status}`; let requestId: string | undefined; let details: ApiClientErrorDetails | undefined; const traceId = response.headers.get("x-trace-id") ?? undefined; try { const errorBody = await response.json(); errorCode = errorBody.code ?? errorCode; errorMessage = errorBody.message ?? errorMessage; requestId = errorBody.requestId; if (errorBody.details && typeof errorBody.details === "object") { details = errorBody.details as ApiClientErrorDetails; } } catch { // Response body is not JSON, use defaults } reportClientApiError({ code: errorCode, message: errorMessage, status: response.status, requestId, traceId, url: response.url, upstreamCode: details?.upstreamCode, upstreamRequestId: details?.upstreamRequestId, }); throw new ApiClientError( errorCode, errorMessage, response.status, requestId, traceId, details, ); } const body: ApiResponse = await response.json(); if (body.code !== "SUCCESS") { const traceId = response.headers.get("x-trace-id") ?? undefined; reportClientApiError({ code: body.code, message: body.message ?? "Unknown error", status: response.status, requestId: body.requestId, traceId, url: response.url, }); throw new ApiClientError( body.code, body.message ?? "Unknown error", response.status, body.requestId, traceId, ); } return body.data; } function buildUrl(path: string): string { return `${API_BASE_URL}${path}`; } function buildHeaders(contentType?: string): HeadersInit { const headers: HeadersInit = {}; if (contentType) { headers["Content-Type"] = contentType; } return headers; } export async function apiGet( path: string, options: Pick = {}, ): Promise { const response = await requestWithClientLogging(path, () => fetchWithTimeout(buildUrl(path), { method: "GET", headers: buildHeaders("application/json"), ...options, }), ); return handleResponse(response); } export async function apiPost( path: string, body?: unknown, timeoutMs?: number, ): Promise { const response = await requestWithClientLogging(path, () => fetchWithTimeout( buildUrl(path), { method: "POST", headers: buildHeaders("application/json"), body: body !== undefined ? JSON.stringify(body) : undefined, }, timeoutMs, ), ); return handleResponse(response); } export async function apiPut(path: string, body?: unknown): Promise { const response = await requestWithClientLogging(path, () => fetchWithTimeout(buildUrl(path), { method: "PUT", headers: buildHeaders("application/json"), body: body !== undefined ? JSON.stringify(body) : undefined, }), ); return handleResponse(response); } export async function apiDelete(path: string, body?: unknown): Promise { const response = await requestWithClientLogging(path, () => fetchWithTimeout(buildUrl(path), { method: "DELETE", headers: buildHeaders("application/json"), body: body !== undefined ? JSON.stringify(body) : undefined, }), ); return handleResponse(response); } export async function apiPatch(path: string, body?: unknown): Promise { const response = await requestWithClientLogging(path, () => fetchWithTimeout(buildUrl(path), { method: "PATCH", headers: buildHeaders("application/json"), body: body !== undefined ? JSON.stringify(body) : undefined, }), ); return handleResponse(response); } export async function apiUpload( path: string, formData: FormData, timeoutMs?: number, ): Promise { const response = await requestWithClientLogging(path, () => fetchWithTimeout( buildUrl(path), { method: "POST", body: formData, // Do not set Content-Type — browser sets multipart boundary automatically }, timeoutMs, ), ); return handleResponse(response); } export { ApiClientError }; async function requestWithClientLogging( path: string, fn: () => Promise, ): Promise { try { return await fn(); } catch (error) { reportClientApiError({ code: error instanceof DOMException && error.name === "AbortError" ? "NETWORK_ERROR" : "BROWSER_ERROR", message: error instanceof Error ? error.message : String(error), status: 0, url: path, name: error instanceof Error ? error.name : undefined, stack: error instanceof Error ? error.stack : undefined, }); throw error; } } function reportClientApiError(payload: Record): void { if (typeof window === "undefined") return; if ( typeof payload.url === "string" && payload.url.includes("/api/v1/logs/client") ) { return; } try { const body = JSON.stringify({ event: "browser.api_error", ...payload, }); if (navigator.sendBeacon) { navigator.sendBeacon( "/api/v1/logs/client", new Blob([body], { type: "application/json" }), ); return; } void fetch("/api/v1/logs/client", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true, }); } catch { // Best-effort only. } }