import type { AccountDetail, AccountListResponse, ChannelDetail, ChannelListResponse, CommandResult, GroupMessageDetail, GroupMessageListResponse, MessageDetail, MessageListResponse } from "./types"; export class APIError extends Error { status: number; constructor(status: number, message: string) { super(message); this.status = status; } } async function request(url: string, init: RequestInit = {}): Promise { const response = await fetch(url, { credentials: "same-origin", headers: { "Content-Type": "application/json", ...(init.headers ?? {}) }, ...init }); const text = await response.text(); const data = text ? JSON.parse(text) : null; if (!response.ok) { const message = data?.error || data?.Error || data?.message || response.statusText; throw new APIError(response.status, message); } return data as T; } export function errorMessage(error: unknown): string { if (error instanceof Error) { return error.message; } return String(error); } export const api = { session: () => request<{ actor: string }>("/api/session"), login: (secret: string) => request<{ actor: string }>("/api/login", { method: "POST", body: JSON.stringify({ secret }) }), logout: () => request<{ ok: boolean }>("/api/logout", { method: "POST", body: "{}" }), accounts: (params: URLSearchParams) => request(`/api/accounts?${params.toString()}`), account: (id: number) => request(`/api/accounts/${id}`), channels: (params: URLSearchParams) => request(`/api/channels?${params.toString()}`), channel: (id: number) => request(`/api/channels/${id}`), messages: (params: URLSearchParams) => request(`/api/messages?${params.toString()}`), message: (ownerUserID: number, msgID: number) => { const params = new URLSearchParams({ owner_user_id: String(ownerUserID), msg_id: String(msgID) }); return request(`/api/messages/detail?${params.toString()}`); }, groupMessages: (params: URLSearchParams) => request(`/api/messages/groups?${params.toString()}`), groupMessage: (channelID: number, msgID: number) => { const params = new URLSearchParams({ channel_id: String(channelID), msg_id: String(msgID) }); return request(`/api/messages/groups/detail?${params.toString()}`); }, action: (path: string, payload: Record) => request(path, { method: "POST", body: JSON.stringify(payload) }) };