Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108// The sidecar's API (app/sidecar/server.js), as the page calls it.import { sidecar } from './desktop.ts';import type { DocInfo, DocJson, Settings, Status, SyncEvent, SyncSummary } from './model.ts';
export class ApiError extends Error { status: number; constructor(message: string, status: number, name?: string) { super(message); this.status = status; if (name) this.name = name; }}
function base(): { origin: string; token: string } { const s = sidecar(); if (!s) throw new ApiError('Notable reaches the cloud through its desktop app; open it with mollusc', 0, 'NoSidecar'); return s;}
async function failure(res: Response, path: string): Promise<ApiError> { const data = (await res.json().catch(() => ({}))) as { error?: string; name?: string }; return new ApiError(data.error ?? `${path}: ${res.status}`, res.status, data.name);}
async function call<T>(path: string, body: unknown = {}): Promise<T> { const s = base(); const res = await fetch(`${s.origin}${path}`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${s.token}` }, body: JSON.stringify(body) }); if (!res.ok) throw await failure(res, path); return (await res.json()) as T;}
async function getBytes(path: string): Promise<Uint8Array | null> { const s = base(); const res = await fetch(`${s.origin}${path}`, { headers: { authorization: `Bearer ${s.token}` } }); if (res.status === 204) return null; if (!res.ok) throw await failure(res, path); return new Uint8Array(await res.arrayBuffer());}
async function putBytes<T>(path: string, data: Uint8Array | Blob, type = 'application/octet-stream'): Promise<T> { const s = base(); const body = data instanceof Blob ? data : new Blob([data as BlobPart], { type }); const res = await fetch(`${s.origin}${path}`, { method: 'PUT', headers: { 'content-type': type, authorization: `Bearer ${s.token}` }, body }); if (!res.ok) throw await failure(res, path); return (await res.json()) as T;}
export const api = { available: () => sidecar() !== null, status: () => call<Status>('/status'), login: (code: string) => call<Status>('/login', { code }), logout: () => call<Status>('/logout'), settings: (patch?: Partial<Settings>) => call<Settings>('/settings', patch ? { patch } : {}), tree: (force = false) => call<{ hash: string; generation: number; docs: DocJson[] }>('/tree', { force }), doc: (id: string) => call<DocInfo>('/doc', { id }), page: (id: string, pageId: string) => getBytes(`/doc/${id}/page/${pageId}`), savePage: (id: string, pageId: string, data: Uint8Array) => putBytes<{ doc: DocJson }>(`/doc/${id}/page/${pageId}`, data), thumbnail: (id: string, pageId: string) => getBytes(`/doc/${id}/thumbnail/${pageId}`), saveThumbnail: (id: string, pageId: string, png: Blob) => putBytes<{ doc: DocJson }>(`/doc/${id}/thumbnail/${pageId}`, png, 'image/png'), file: (id: string, kind: 'pdf' | 'epub') => getBytes(`/doc/${id}/file/${kind}`), savePdf: (id: string, data: Uint8Array) => putBytes<{ doc: DocJson }>(`/doc/${id}/pdf`, data, 'application/pdf'), addPage: (id: string, after: string | null, template: string | null) => call<{ doc: DocJson; pageId: string }>('/doc/add-page', { id, after, template }), removePage: (id: string, pageId: string) => call<{ doc: DocJson }>('/doc/remove-page', { id, pageId }), setTemplate: (id: string, pageId: string, template: string) => call<{ doc: DocJson }>('/doc/template', { id, pageId, template }), newNotebook: (name: string, parent: string, template = 'Blank') => call<{ doc: DocJson }>('/notebook', { name, parent, template }), newFolder: (name: string, parent: string) => call<{ doc: DocJson }>('/folder', { name, parent }), rename: (id: string, name: string) => call<{ doc: DocJson }>('/rename', { id, name }), move: (ids: string[], parent: string) => call<{ docs: DocJson[] }>('/move', { ids, parent }), trash: (ids: string[]) => call<{ docs: DocJson[] }>('/trash', { ids }), restore: (ids: string[], parent = '') => call<{ docs: DocJson[] }>('/restore', { ids, parent }), purge: (ids: string[]) => call<{ docs: DocJson[] }>('/purge', { ids }), upload: (paths: string[], parent: string) => call<{ docs: DocJson[] }>('/upload', { paths, parent }), exportDoc: (id: string, format: 'markdown' | 'svg' | 'pdf', path: string) => call<{ files: string[] }>('/export', { id, format, path }), download: (id: string, dir: string) => call<{ files: string[] }>('/download', { id, dir }),
/** Mirror the cloud into a directory, reporting each step as it goes. */ async sync(opts: { dir: string; formats: string[]; raw: boolean; trash: boolean; prune: boolean; dryRun: boolean }, onEvent: (e: SyncEvent) => void): Promise<SyncSummary> { const s = base(); const res = await fetch(`${s.origin}/sync`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${s.token}` }, body: JSON.stringify(opts) }); if (!res.ok || !res.body) throw await failure(res, '/sync'); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; let summary: SyncSummary | null = null; const handle = (line: string) => { if (!line.trim()) return; const o = JSON.parse(line) as { event?: SyncEvent; summary?: SyncSummary; error?: string; name?: string }; if (o.event) onEvent(o.event); if (o.summary) summary = o.summary; if (o.error) throw new ApiError(o.error, 500, o.name); }; for (;;) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let nl = buffer.indexOf('\n'); while (nl >= 0) { handle(buffer.slice(0, nl)); buffer = buffer.slice(nl + 1); nl = buffer.indexOf('\n'); } } handle(buffer); if (!summary) throw new ApiError('the mirror ended without a summary', 500); return summary; },};