import { API_ROOT } from "@/lib/config" import type { AuthState, Account, CreateAccountInput, Template, CreateTemplateInput, Domain, CreateDomainInput, ChangesetResponse, ApplyRequest, } from "./types" export class UnauthorizedError extends Error { constructor() { super("Unauthorized") this.name = "UnauthorizedError" } } async function req(path: string, init?: RequestInit): Promise { const res = await fetch(path, { headers: { "Content-Type": "application/json" }, method: "GET", credentials: "include", ...init, }) if (res.status === 401) throw new UnauthorizedError() if (!res.ok) { let msg = `HTTP ${res.status}` try { const b = await res.json(); if (b?.error) msg = String(b.error) } catch { /* ignore */ } throw new Error(msg) } if (res.status === 204) return undefined as T return (await res.json()) as T } function projectPath(projectId: string, path: string): string { return `${API_ROOT}/projects/${projectId}${path}` } export const api = { auth: { register: (email: string, password: string) => req(`${API_ROOT}/auth/register`, { method: "POST", body: JSON.stringify({ email, password }), }), login: (email: string, password: string) => req(`${API_ROOT}/auth/login`, { method: "POST", body: JSON.stringify({ email, password }), }), logout: () => req(`${API_ROOT}/auth/logout`, { method: "POST" }), me: () => req(`${API_ROOT}/auth/me`), }, listAccounts: (projectId: string) => req(projectPath(projectId, "/accounts")), createAccount: (projectId: string, input: CreateAccountInput) => req(projectPath(projectId, "/accounts"), { method: "POST", body: JSON.stringify(input) }), deleteAccount: (projectId: string, id: string) => req(projectPath(projectId, `/accounts/${id}`), { method: "DELETE" }), listTemplates: (projectId: string) => req(projectPath(projectId, "/templates")), createTemplate: (projectId: string, input: CreateTemplateInput) => req