// Thin wrappers around the server API (SPEC.md ยง8.1). import type { StoredEvent } from './idb.ts'; export class ApiError extends Error { status: number; constructor(status: number, message: string) { super(message); this.status = status; } } /** True for errors that mean "try again later" rather than "this is wrong". */ export const isOffline = (e: unknown) => !(e instanceof ApiError) || e.status >= 500 || e.status === 429; async function req(method: string, path: string, opts: { token?: string; json?: unknown; body?: BodyInit; signal?: AbortSignal } = {}): Promise { const headers: Record = {}; if (opts.token) headers.Authorization = `Bearer ${opts.token}`; if (opts.json !== undefined) headers['Content-Type'] = 'application/json'; const res = await fetch(path, { method, headers, body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body, signal: opts.signal, cache: 'no-store', }); if (!res.ok) { let msg = res.statusText; try { msg = (await res.json()).error ?? msg; } catch { /* not JSON */ } throw new ApiError(res.status, msg); } const type = res.headers.get('content-type') ?? ''; return (type.includes('application/json') ? res.json() : res.arrayBuffer()) as Promise; } export interface ServerConfig { vapidPublicKey: string | null; maxPhotoBytes: number; maxGroupBytes: number; } let configP: Promise | null = null; export function serverConfig(): Promise { configP ??= req('GET', '/api/config').catch((e) => { configP = null; throw e; }); return configP; } export const api = { createGroup: (id: string, authHash: string) => req('POST', '/api/groups', { json: { id, authHash } }), deleteGroup: (id: string, token: string) => req('DELETE', `/api/groups/${id}`, { token }), events: (id: string, token: string, after: number) => req<{ events: Omit[]; latest: number }>('GET', `/api/groups/${id}/events?after=${after}&limit=500`, { token }), append: (id: string, token: string, events: Omit[]) => req<{ seqs: number[] }>('POST', `/api/groups/${id}/events`, { token, json: { events } }), putBlob: (id: string, token: string, blobId: string, data: ArrayBuffer) => req('PUT', `/api/groups/${id}/blobs/${blobId}`, { token, body: data }), getBlob: (id: string, token: string, blobId: string) => req('GET', `/api/groups/${id}/blobs/${blobId}`, { token }), pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) => req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }), pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }), rates: (date: string) => req<{ base: string; date: string; rates: Record }>('GET', `/api/rates?date=${date}`), }; /** * Listen for "new seq" pings on the group's SSE stream. EventSource can't * send an Authorization header, so this reads the stream with fetch. * Resolves when the stream ends; throws on errors. */ export async function listen(id: string, token: string, signal: AbortSignal, onSeq: (seq: number) => void): Promise { const res = await fetch(`/api/groups/${id}/stream`, { headers: { Authorization: `Bearer ${token}` }, signal, cache: 'no-store' }); if (!res.ok || !res.body) throw new ApiError(res.status, 'stream failed'); const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); let buf = ''; for (;;) { const { value, done } = await reader.read(); if (done) return; buf += value; let i: number; while ((i = buf.indexOf('\n\n')) >= 0) { const msg = buf.slice(0, i); buf = buf.slice(i + 2); const m = /^data: (\d+)$/m.exec(msg); if (m) onSeq(Number(m[1])); } } }