/** * API client utilities for CLI commands */ import { readConfig } from "./config.js"; export interface ApiClientError { code: string; message: string; } /** * Create an API client with the stored credentials * Throws an error if not logged in */ export const createApiClient = async () => { const config = await readConfig(); if (!config) { throw new Error( "Not logged in. Run 'reviq bootstrap' or 'reviq auth login' first.", ); } return { /** * Call an oRPC procedure */ call: async (path: string, input?: unknown): Promise => { const url = `${config.apiUrl}/api/v1/rpc/${path}`; const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "X-API-Key": config.token, }, body: input !== undefined ? JSON.stringify(input) : undefined, }); if (!response.ok) { const text = await response.text(); let errorMessage = `API error: ${String(response.status)} ${response.statusText}`; try { const error = JSON.parse(text) as ApiClientError; if (error.message) { errorMessage = error.message; } } catch { if (text) { errorMessage = text; } } throw new Error(errorMessage); } return response.json() as Promise; }, config, }; }; export type ApiClient = Awaited>;