import type { AnalyzeResponse, BuildStatus } from "../types"; async function errMsg(res: Response): Promise { try { const j = await res.json(); const d = j.detail; if (typeof d === "string") return d; if (d?.message) return `${d.message}${d.code ? ` [${d.code}]` : ""}`; return JSON.stringify(d || j); } catch { return `HTTP ${res.status} ${res.statusText}`; } } export async function analyzeSpace(space_url: string, hf_token?: string): Promise { const res = await fetch("/api/analyze", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ space_url, hf_token: hf_token || undefined }), }); if (!res.ok) throw new Error(await errMsg(res)); return res.json(); } export async function startBuild( space_url: string, target: string, mode: string, hf_token?: string, options: Record = {} ): Promise<{ build_id: string; status: string }> { const res = await fetch("/api/build", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ space_url, target, mode, options, hf_token: hf_token || undefined }), }); if (!res.ok) throw new Error(await errMsg(res)); return res.json(); } export async function getBuild(id: string): Promise { const res = await fetch(`/api/build/${id}`); if (!res.ok) throw new Error(await errMsg(res)); return res.json(); } export async function getLogs(id: string): Promise { const res = await fetch(`/api/build/${id}/logs`); if (!res.ok) throw new Error(await errMsg(res)); return res.text(); } export async function deleteBuild(id: string): Promise { const res = await fetch(`/api/build/${id}`, { method: "DELETE" }); if (!res.ok) throw new Error(await errMsg(res)); } export function downloadUrl(id: string, target: string): string { return `/api/build/${id}/download?target=${encodeURIComponent(target)}`; }