import { FetchError } from '@opencode-manager/shared' import type { ApiErrorResponse } from '@opencode-manager/shared' export { FetchError } interface FetchWrapperOptions extends RequestInit { timeout?: number params?: Record acceptedStatuses?: number[] } function formatDetails(details: unknown): string | undefined { if (Array.isArray(details)) { return details .map((d) => { if (typeof d !== 'object' || d === null) return null const path = Array.isArray((d as Record).path) ? ((d as Record).path as string[]) : undefined const message = typeof (d as Record).message === 'string' ? (d as Record).message as string : undefined return path?.length ? `${path.join('.')}: ${message}` : message }) .filter(Boolean) .join('; ') } if (typeof details === 'string') return details return undefined } async function handleResponse(response: Response): Promise { const text = await response.text().catch(() => '') const data: ApiErrorResponse = (() => { if (!text) return { error: 'An error occurred' } try { return JSON.parse(text) as ApiErrorResponse } catch { return { error: /^\s*): URL { const urlObj = new URL(url, window.location.origin) if (params) { Object.entries(params).forEach(([key, value]) => { if (value !== undefined) { urlObj.searchParams.append(key, String(value)) } }) } return urlObj } async function fetchWithTimeout( url: string, options: FetchWrapperOptions = {} ): Promise { const { timeout = 30000, params, acceptedStatuses, ...fetchOptions } = options const urlObj = buildUrl(url, params) const controller = new AbortController() const timeoutId = timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null try { const response = await fetch(urlObj.toString(), { credentials: 'include', ...fetchOptions, signal: controller.signal, }) if (timeoutId) clearTimeout(timeoutId) if (!response.ok && !acceptedStatuses?.includes(response.status)) { await handleResponse(response) } return response } catch (error) { if (timeoutId) clearTimeout(timeoutId) if (error instanceof Error && error.name === 'AbortError') { throw new FetchError('Request timeout', 408, 'TIMEOUT') } throw error } } async function fetchWrapper( url: string, options: FetchWrapperOptions = {} ): Promise { const response = await fetchWithTimeout(url, options) try { return await response.json() } catch { throw new FetchError('Invalid JSON response', response.status, 'INVALID_JSON') } } async function fetchWrapperVoid( url: string, options: FetchWrapperOptions = {} ): Promise { await fetchWithTimeout(url, options) } async function fetchWrapperBlob( url: string, options: FetchWrapperOptions = {} ): Promise { const response = await fetchWithTimeout(url, options) return response.blob() } export { fetchWrapper, fetchWrapperVoid, fetchWrapperBlob }