| 1 | export async function api(path, opts = {}) { |
| 2 | const r = await fetch(path, { |
| 3 | credentials: 'include', |
| 4 | ...opts, |
| 5 | headers: { 'Content-Type': 'application/json', ...(opts.headers || {}) }, |
| 6 | }); |
| 7 | if (r.status === 401) { |
| 8 | // Reload to show the login screen |
| 9 | if (path !== '/api/auth/whoami' && path !== '/api/auth/login') window.location.reload(); |
| 10 | } |
| 11 | if (!r.ok) { |
| 12 | const txt = await r.text().catch(() => ''); |
| 13 | let parsed; |
| 14 | try { parsed = JSON.parse(txt); } catch {} |
| 15 | throw new Error(parsed?.error || `${r.status} ${r.statusText}`); |
| 16 | } |
| 17 | if (r.headers.get('content-type')?.includes('application/json')) return r.json(); |
| 18 | return r.text(); |
| 19 | } |
| 20 | |
| 21 | export function streamSSE(path, onMessage, onError) { |
| 22 | const es = new EventSource(path, { withCredentials: true }); |
| 23 | es.onmessage = (e) => { |
| 24 | try { onMessage(JSON.parse(e.data)); } catch {} |
| 25 | }; |
| 26 | es.onerror = (e) => { onError && onError(e); }; |
| 27 | return () => es.close(); |
| 28 | } |