import type { CliConfig } from './config.js'; export type ApiResult = { ok: true; data: T } | { ok: false; error: string }; export class SubstrateClient { private url: string; private headers: Record; constructor(config: CliConfig) { this.url = config.apiUrl; this.headers = { 'Content-Type': 'application/json', ...(config.apiKey ? { 'x-substrate-key': config.apiKey } : {}), }; } private async get(path: string): Promise> { try { const res = await fetch(`${this.url}${path}`, { headers: this.headers, signal: AbortSignal.timeout(5000), }); if (!res.ok) { const body = await res.json().catch(() => ({})); return { ok: false, error: (body as any).error || `HTTP ${res.status}` }; } return { ok: true, data: await res.json() as T }; } catch (e: any) { if (e.name === 'TimeoutError' || e.code === 'ECONNREFUSED') { return { ok: false, error: 'Substrate not reachable' }; } return { ok: false, error: e.message || 'Request failed' }; } } private async post(path: string, body?: any): Promise> { try { const res = await fetch(`${this.url}${path}`, { method: 'POST', headers: this.headers, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(10000), }); if (!res.ok) { const data = await res.json().catch(() => ({})); return { ok: false, error: (data as any).error || `HTTP ${res.status}` }; } const data = res.status === 204 ? ({} as T) : await res.json() as T; return { ok: true, data }; } catch (e: any) { return { ok: false, error: e.message || 'Request failed' }; } } async health(): Promise; }>> { return this.get('/health'); } async services(): Promise>> { return this.get('/services'); } async containers(): Promise; }>> { return this.get('/containers'); } async containerLogs(id: string, tail = 50): Promise> { return this.get(`/containers/${id}/logs?tail=${tail}`); } async tapStats(): Promise> { return this.get('/stats'); } async tapFilters(): Promise> { return this.get('/tap/filters'); } async repos(): Promise> { return this.get('/repos'); } async containerStart(id: string): Promise> { return this.post(`/containers/${id}/start`); } async containerStop(id: string): Promise> { return this.post(`/containers/${id}/stop`); } }