import type { ApiErrorBody } from './types.ts'; /** 类型化 fetch 封装:非 2xx 抛 Error(后端 detail.message)。 */ export async function api(method: string, url: string, body?: unknown): Promise { const headers: Record = {}; const opt: RequestInit = { method, headers }; if (body !== undefined) { headers['Content-Type'] = 'application/json'; opt.body = JSON.stringify(body); } const r = await fetch(url, opt); const data = (await r.json().catch(() => ({}))) as T & ApiErrorBody; if (!r.ok) { const detail = data.detail; const msg = typeof detail === 'string' ? detail : detail && detail.message; throw new Error(msg || String(r.status)); } return data as T; }