import { getToken, getEndpoint, loadCache, saveCache } from "./config.js"; export async function api( method: string, path: string, body?: unknown ): Promise<{ data: any; status: number }> { const url = `${getEndpoint()}${path}`; const headers: Record = { Authorization: `Bearer ${getToken()}`, "Content-Type": "application/json", }; let res: Response; try { res = await fetch(url, { method, headers, body: body !== undefined ? JSON.stringify(body) : undefined, }); } catch (err: any) { console.error( `Error: ${err?.cause?.message || err?.message || "network error"}` ); process.exit(1); } if (res.status === 204) return { data: null, status: 204 }; const text = await res.text(); let data: any; try { data = JSON.parse(text); } catch { data = text; } if (!res.ok) { const msg = data?.error || text; console.error(`Error: ${msg}`); process.exit(1); } return { data, status: res.status }; } export async function trySyncRemote(): Promise { const url = `${getEndpoint()}/config`; const headers: Record = { Authorization: `Bearer ${getToken()}`, "Content-Type": "application/json", }; try { const res = await fetch(url, { method: "GET", headers }); if (!res.ok) return false; const data = await res.json() as any; if (!data?.secrets) return false; const now = new Date().toISOString(); const cache = { agent_id: data.agent_id, secrets: data.secrets, synced_at: now, attempted_at: now, }; saveCache(cache); return true; } catch { const cache = loadCache(); if (cache) { cache.attempted_at = new Date().toISOString(); saveCache(cache); } return false; } }