/** * Backup API client. * * File : frontend/src/api/backup.ts (new) * Purpose : call the backend routes in backend/app/backup_routes.py. * Consumers: ExportBackupButton, ImportBackupPanel. * * Same-origin path, matching BASE = "/api/v1/protocols" in api/protocols.ts. */ const API_ROOT = "/api/v1"; const MAX_BACKUP_BYTES = 25 * 1024 * 1024; export interface SectionPlan { total: number; new: number; duplicate: number; } export interface RestorePlan { protocol_id: string; protocol_exists: boolean; sections: Record; search_run: string; synthesis: string; warnings: string[]; restored: boolean; } export type BackupDocument = Record; export class BackupApiError extends Error {} /** Turn any error body the backend can send into one readable message. */ function describeError(status: number, body: unknown): string { const detail = (body as { detail?: unknown } | null)?.detail; if (typeof detail === "string") return detail; if (Array.isArray(detail)) { // FastAPI's own validation errors (e.g. the file isn't a backup at all) return "This file is not a valid backup file."; } if (detail && typeof detail === "object") { const d = detail as { message?: string; problems?: string[]; total_problems?: number }; const problems = (d.problems ?? []).map((p) => `• ${p}`).join("\n"); const more = d.total_problems && d.problems && d.total_problems > d.problems.length ? `\n…and ${d.total_problems - d.problems.length} more.` : ""; return `${d.message ?? "The backup file has problems."}\n${problems}${more}`.trim(); } return `Request failed (${status}).`; } async function readBody(res: Response): Promise { try { return await res.json(); } catch { return null; } } async function post(path: string, body: BackupDocument): Promise { let res: Response; try { res = await fetch(`${API_ROOT}${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); } catch { throw new BackupApiError("Could not reach the server. Check your connection and try again."); } const data = await readBody(res); if (!res.ok) throw new BackupApiError(describeError(res.status, data)); return data as T; } /** Read a chosen file and check it is JSON. Does not contact the server. */ export async function readBackupFile(file: File): Promise { if (file.size > MAX_BACKUP_BYTES) { throw new BackupApiError("This file is too large to be a backup (limit 25 MB)."); } let parsed: unknown; try { parsed = JSON.parse(await file.text()); } catch { throw new BackupApiError("This file is not valid JSON, so it cannot be a backup."); } if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { throw new BackupApiError("This file is not a backup file."); } return parsed as BackupDocument; } export function previewBackup(doc: BackupDocument): Promise { return post("/backup/preview", doc); } export function restoreBackup(doc: BackupDocument, merge: boolean): Promise { return post(`/backup/restore?merge=${merge ? "true" : "false"}`, doc); } /** Download one project's backup as a saved file (not shown in the browser). */ export async function downloadBackup(protocolId: string): Promise { let res: Response; try { res = await fetch(`${API_ROOT}/protocols/${encodeURIComponent(protocolId)}/backup`); } catch { throw new BackupApiError("Could not reach the server. Check your connection and try again."); } if (!res.ok) throw new BackupApiError(describeError(res.status, await readBody(res))); const blob = await res.blob(); const safeId = protocolId.replace(/[^A-Za-z0-9_-]/g, "_"); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = `project-backup-${safeId}.json`; document.body.appendChild(link); link.click(); link.remove(); URL.revokeObjectURL(url); }