/** Typed-ish client for the dashboard API (M16-T11). */ export class ApiError extends Error { constructor(status, message, details) { super(message); this.name = 'ApiError'; this.status = status; this.details = details; } } async function request(method, path, body) { const response = await fetch(path, { method, headers: { Accept: 'application/json', ...(body !== undefined && { 'Content-Type': 'application/json' }), // Required by the server for every write: a cross-site form cannot set it. 'X-Requested-With': 'fws-dashboard', }, body: body === undefined ? undefined : JSON.stringify(body), credentials: 'same-origin', }); const payload = await response.json().catch(() => null); if (!response.ok) { throw new ApiError(response.status, payload?.error ?? `Erreur ${response.status}`, payload?.details); } return payload; } const withQuery = (path, params) => { const search = new URLSearchParams( Object.entries(params ?? {}).filter(([, value]) => value !== undefined && value !== null && value !== ''), ).toString(); return search ? `${path}?${search}` : path; }; export const api = { get: (path, params) => request('GET', withQuery(path, params)), post: (path, body = {}) => request('POST', path, body), put: (path, body = {}) => request('PUT', path, body), patch: (path, body = {}) => request('PATCH', path, body), delete: (path, body = {}) => request('DELETE', path, body), }; export const encodeRepo = (fullName) => String(fullName) .split('/') .map((part) => encodeURIComponent(part)) .join('/');