import type { ServerEvent } from "./types"; // Authentication uses an HttpOnly session cookie set by /api/auth/login. export class ApiError extends Error { constructor( public status: number, message: string, ) { super(message); } } export async function api(path: string, init: RequestInit & { json?: unknown } = {}): Promise { const headers: Record = { ...(init.headers as Record) }; let body = init.body; if (init.json !== undefined) { headers["Content-Type"] = "application/json"; body = JSON.stringify(init.json); } const res = await fetch(`/api${path}`, { ...init, headers, body, credentials: "same-origin" }); if (res.status === 401 && !path.startsWith("/auth/") && path !== "/info") onUnauthorized?.(); const text = await res.text(); let data: any = null; try { data = text ? JSON.parse(text) : null; } catch { // Proxies answer with HTML error pages (e.g. 413 from nginx). const hint = res.status === 413 ? "request too large – the reverse proxy rejected the upload (client_max_body_size)" : res.statusText || "unexpected response"; throw new ApiError(res.status, `HTTP ${res.status}: ${hint}`); } if (!res.ok) throw new ApiError(res.status, data?.error ?? res.statusText); return data as T; } /** Called when the session expired (set by the app to show the login). */ let onUnauthorized: (() => void) | undefined; export function setUnauthorizedHandler(fn: () => void) { onUnauthorized = fn; } export const get = (path: string) => api(path); export const post = (path: string, json?: unknown) => api(path, { method: "POST", json: json ?? {} }); export const patch = (path: string, json: unknown) => api(path, { method: "PATCH", json }); export const put = (path: string, json: unknown) => api(path, { method: "PUT", json }); export const del = (path: string) => api(path, { method: "DELETE" }); /** WebSocket with automatic reconnect. `onOpen` runs after every (re)connect so * the caller can resync state that may have been missed. */ export function connectEvents(handlers: { onEvent: (ev: ServerEvent) => void; onOpen: () => void; onClose: () => void; }): () => void { let ws: WebSocket | null = null; let stopped = false; let retry = 0; let timer: ReturnType | undefined; const open = () => { const proto = location.protocol === "https:" ? "wss" : "ws"; ws = new WebSocket(`${proto}://${location.host}/api/ws`); ws.onopen = () => { retry = 0; reportVisibility(); handlers.onOpen(); }; ws.onmessage = (m) => { try { handlers.onEvent(JSON.parse(m.data)); } catch { /* ignore malformed */ } }; ws.onclose = () => { handlers.onClose(); if (stopped) return; retry = Math.min(retry + 1, 6); timer = setTimeout(open, 500 * 2 ** retry); }; }; open(); // Reconnect immediately when the app comes back to the foreground (mobile PWA). // The server sends push notifications only while no app window is visible. const reportVisibility = () => { if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "visibility", visible: document.visibilityState === "visible" })); }; const onVisible = () => { reportVisibility(); if (document.visibilityState === "visible" && ws && ws.readyState > WebSocket.OPEN) { clearTimeout(timer); open(); } }; document.addEventListener("visibilitychange", onVisible); return () => { stopped = true; clearTimeout(timer); document.removeEventListener("visibilitychange", onVisible); ws?.close(); }; } const CHUNK = 8 * 1024 * 1024; /** * Upload a file in 8 MB chunks (stays below reverse proxy body limits; up to the * server's max_upload_mb). `onProgress` gets the uploaded fraction 0..1. */ export async function uploadFile(path: string, file: Blob, onProgress?: (fraction: number) => void): Promise { let offset = 0; do { const chunk = file.slice(offset, offset + CHUNK); const res = await fetch(`/api/files/upload?path=${encodeURIComponent(path)}&offset=${offset}`, { method: "PUT", body: chunk, credentials: "same-origin" }); if (!res.ok) { let msg = `HTTP ${res.status}`; try { msg = (await res.json()).error ?? msg; } catch { if (res.status === 413) msg = "too large for the reverse proxy"; } throw new Error(msg); } offset += chunk.size; onProgress?.(file.size ? offset / file.size : 1); } while (offset < file.size); }