"use client"; /** The admin API from the browser (same origin: the session cookie goes along, and so does Origin). */ export class AdminError extends Error { constructor(message: string, public code: string, public status: number, public fields: Record = {}) { super(message); } } export async function api(path: string, opts: { method?: string; body?: unknown; raw?: Blob } = {}): Promise { const res = await fetch(`/api/v1/admin${path}`, { method: opts.method ?? (opts.body !== undefined || opts.raw ? "POST" : "GET"), headers: opts.raw ? { "Content-Type": "application/octet-stream" } : opts.body !== undefined ? { "Content-Type": "application/json" } : undefined, body: opts.raw ?? (opts.body !== undefined ? JSON.stringify(opts.body) : undefined), cache: "no-store", }); const data = await res.json().catch(() => null); if (!res.ok) { const e = (data as { error?: { message?: string; code?: string; fields?: Record } } | null)?.error; // Signed out: off to sign in (a route on the backend), and back to this page. // eslint-disable-next-line @next/next/no-location-assign-relative-destination if (res.status === 401) window.location.href = `/api/auth/signin?returnTo=${encodeURIComponent(window.location.pathname)}`; throw new AdminError(e?.message ?? `Something went wrong (${res.status}).`, e?.code ?? "ERROR", res.status, e?.fields ?? {}); } return data as T; } export const ROLE_NAMES: Record = { owner: "Owner", admin: "Admin", editor: "Editor", ministry_leader: "Ministry leader", viewer: "Viewer" }; export const canEdit = (role: string) => ["owner", "admin", "editor"].includes(role);