Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import type { CliConfig } from './config.js';
export type ApiResult<T> = { ok: true; data: T } | { ok: false; error: string };
export class SubstrateClient { private url: string; private headers: Record<string, string>;
constructor(config: CliConfig) { this.url = config.apiUrl; this.headers = { 'Content-Type': 'application/json', ...(config.apiKey ? { 'x-substrate-key': config.apiKey } : {}), }; }
private async get<T>(path: string): Promise<ApiResult<T>> { 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<T>(path: string, body?: any): Promise<ApiResult<T>> { 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<ApiResult<{ status: string; timestamp: string; services: Record<string, string>; }>> { return this.get('/health'); }
async services(): Promise<ApiResult<Record<string, { status: string; url?: string; stats?: any; details?: any; }>>> { return this.get('/services'); }
async containers(): Promise<ApiResult<{ containers: Array<{ id: string; name: string; image: string; status: string; ports: any[]; networks: string[]; allowInternet: boolean; }>; }>> { return this.get('/containers'); }
async containerLogs(id: string, tail = 50): Promise<ApiResult<{ logs: string }>> { return this.get(`/containers/${id}/logs?tail=${tail}`); }
async tapStats(): Promise<ApiResult<any>> { return this.get('/stats'); }
async tapFilters(): Promise<ApiResult<{ filters: string[]; source: string }>> { return this.get('/tap/filters'); }
async repos(): Promise<ApiResult<{ repos: any[]; total: number }>> { return this.get('/repos'); }
async containerStart(id: string): Promise<ApiResult<any>> { return this.post(`/containers/${id}/start`); }
async containerStop(id: string): Promise<ApiResult<any>> { return this.post(`/containers/${id}/stop`); }}