import type { NotebookListResponse, HostsResponse, NotebookResponse, SaveNotebookResponse, StartRunRequest, StartRunResponse, ServerEvent, } from "@shellbook/core"; export class HttpError extends Error { constructor(public status: number) { super(`Request failed (${status})`); } } export async function json( path: string, method = "GET", body?: unknown, ): Promise { const response = await fetch(`/api${path}`, { method, credentials: "same-origin", headers: body === undefined ? {} : { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!response.ok) throw new HttpError(response.status); return response.status === 204 ? (undefined as T) : (response.json() as Promise); } export interface Api { me(): Promise; login(password: string): Promise; list(): Promise; hosts(): Promise; notebook(path: string): Promise; save( path: string, source: string, baseVersion: string, ): Promise; run(request: StartRunRequest): Promise; events( receive: (event: ServerEvent) => void, connection: (connected: boolean) => void, ): () => void; artifact(runId: string, name: string): string; } export const liveApi: Api = { me: () => json("/auth/me"), login: (password) => json("/auth/login", "POST", { password }), list: () => json("/notebooks"), hosts: () => json("/hosts"), notebook: (path) => json(`/notebooks/${encodeURIComponent(path)}`), save: (path, source, baseVersion) => json(`/notebooks/${encodeURIComponent(path)}`, "PUT", { source, baseVersion, }), run: (request) => json("/runs", "POST", request), artifact: (id, name) => `/api/runs/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(name)}`, events(receive, connection) { const ws = new WebSocket( `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/events`, ); ws.onopen = () => connection(true); ws.onclose = () => connection(false); ws.onerror = () => connection(false); ws.onmessage = (message) => { try { receive(JSON.parse(String(message.data)) as ServerEvent); } catch { connection(false); } }; return () => ws.close(); }, };