import type { HeadscaleServiceWidget } from "@/lib/config/schema"; import type { ServiceStat } from "@/lib/types/service-result"; import { serviceBaseUrl } from "./base-url"; async function fetchList(url: string, apiToken: string, label: string, key: "users" | "nodes"): Promise { const response = await fetch(url, { headers: { Authorization: `Bearer ${apiToken}` }, signal: AbortSignal.timeout(5_000), }); if (!response.ok) { throw new Error(`Headscale ${label} API returned ${response.status}`); } const body = (await response.json()) as Record; return body[key] ?? []; } export async function collectHeadscale(widget: HeadscaleServiceWidget): Promise<{ stats: ServiceStat[] }> { const base = serviceBaseUrl(widget); const [users, nodes] = await Promise.all([ fetchList(`${base}/api/v1/user`, widget.apiToken, "user", "users"), fetchList(`${base}/api/v1/node`, widget.apiToken, "node", "nodes"), ]); return { stats: [ { label: "Users", value: String(users.length) }, { label: "Nodes", value: String(nodes.length) }, ], }; }