/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/stats/dashboard * * Live HTTP dashboard for Bxc statistics. * Exposes a minimal single-page HTML dashboard (auto-refresh every 1 s) * and a JSON API endpoint for CI consumption. * * All served via `Bun.serve` — zero external dependencies. * * Usage: * ```ts * import { Statistics } from "./Statistics.ts"; * import { startDashboard } from "./dashboard.ts"; * * const stats = new Statistics(); * stats.startTracking(); * * const dashboard = await startDashboard(stats, 9229); * // ... run crawler ... * await dashboard.stop(); * ``` */ import type { Statistics, StatisticsSnapshot } from "./Statistics.ts"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface DashboardHandle { /** The port the dashboard is listening on. */ readonly port: number; /** Base URL of the dashboard (e.g. `http://localhost:9229`). */ readonly url: string; /** Stop the HTTP server and release the port. */ stop(): Promise; } // --------------------------------------------------------------------------- // HTML template // --------------------------------------------------------------------------- function renderHtml(): string { return ` Bxc Stats Dashboard

Bxc Stats Dashboard

Live crawler statistics — auto-refresh every second

Requests Total
-
Finished
-
Failed
-
Retried
-
Success Rate
-
Req / min
-
Avg Duration
-
p50 Latency
-
p95 Latency
-
Runtime
-
Error Breakdown
Error TypeCount
No errors recorded
Last updated: -
`; } // --------------------------------------------------------------------------- // startDashboard // --------------------------------------------------------------------------- /** * Start a live HTTP dashboard on `port` (default 9229) backed by `stats`. * * Routes: * GET / -> HTML dashboard (auto-refresh every 1 s) * GET /api/stats -> JSON snapshot of current statistics * * Returns a handle with `stop()` to tear down the server. * * @example * ```ts * const stats = new Statistics(); * stats.startTracking(); * const dash = await startDashboard(stats, 9229); * // navigate to http://localhost:9229 * await dash.stop(); * ``` */ export async function startDashboard( stats: Statistics, port = 9229, ): Promise { const html = renderHtml(); const htmlBytes = new TextEncoder().encode(html); const server = Bun.serve({ port, fetch(req) { const url = new URL(req.url); if (url.pathname === "/api/stats") { const snap: StatisticsSnapshot = stats.snapshot(); return new Response(JSON.stringify(snap), { headers: { "Content-Type": "application/json", "Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*", }, }); } // Serve the HTML dashboard for all other GET requests if (req.method === "GET") { return new Response(htmlBytes, { headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-cache", }, }); } return new Response("Method Not Allowed", { status: 405 }); }, error(err) { return new Response(`Internal server error: ${err.message}`, { status: 500, }); }, }); const actualPort = server.port ?? port; const baseUrl = `http://localhost:${actualPort}`; return { port: actualPort, url: baseUrl, async stop(): Promise { await server.stop(true); }, }; }