Something went wrong. Try again.
Reference implementation for the Phoenix Architecture. Work in progress. aicoding.leaflet.pub
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242/** * Web Dashboard — Web Server * * AUTO-GENERATED by Phoenix VCS * Serves the web client HTML, plus health/metrics/modules endpoints. */
import { createServer, IncomingMessage, ServerResponse } from 'node:http';
import * as analyticsPanel from './analytics-panel.js';import * as dashboardPage from './dashboard-page.js';import * as styles from './styles.js';import * as taskListDisplay from './task-list-display.js';
// ─── Metrics ─────────────────────────────────────────────────────────────────
const _svcMetrics = { requests_total: 0, requests_by_path: {} as Record<string, number>, errors_total: 0, uptime_start: Date.now(),};
// ─── Module Registry ─────────────────────────────────────────────────────────
const _svcModules = { 'analytics-panel': analyticsPanel, 'dashboard-page': dashboardPage, 'styles': styles, 'task-list-display': taskListDisplay,};
// ─── HTML Renderer ───────────────────────────────────────────────────────────
function renderPage(): string { // Collect CSS from style modules let css = ''; try { const styleMod = styles as Record<string, unknown>; for (const key of Object.keys(styleMod)) { const val = styleMod[key]; if (typeof val === 'function' && /css|style/i.test(key)) { const result = (val as Function)(); if (typeof result === 'string') css += result; else if (result && typeof result === 'object' && 'generateCSS' in result) { css += (result as { generateCSS: () => string }).generateCSS(); } } } } catch { /* style module may not have expected exports */ }
// Collect HTML from UI modules const sections: string[] = []; try { const uiMod = analyticsPanel as Record<string, unknown>; for (const key of Object.keys(uiMod)) { const val = uiMod[key]; // Look for factory functions that return objects with render/renderHTML if (typeof val === 'function' && /^create|^make|^render|^build/i.test(key)) { try { const instance = (val as Function)(); if (typeof instance === 'string' && instance.includes('<')) { sections.push(instance); } else if (instance && typeof instance === 'object') { const obj = instance as Record<string, unknown>; if (typeof obj.render === 'function') { const html = (obj.render as Function)(); if (typeof html === 'string') sections.push(html); } else if (typeof obj.renderHTML === 'function') { const html = (obj.renderHTML as Function)(); if (typeof html === 'string') sections.push(html); } } } catch { /* factory may require args */ } } } } catch { /* module may not have renderable exports */ } try { const uiMod = dashboardPage as Record<string, unknown>; for (const key of Object.keys(uiMod)) { const val = uiMod[key]; // Look for factory functions that return objects with render/renderHTML if (typeof val === 'function' && /^create|^make|^render|^build/i.test(key)) { try { const instance = (val as Function)(); if (typeof instance === 'string' && instance.includes('<')) { sections.push(instance); } else if (instance && typeof instance === 'object') { const obj = instance as Record<string, unknown>; if (typeof obj.render === 'function') { const html = (obj.render as Function)(); if (typeof html === 'string') sections.push(html); } else if (typeof obj.renderHTML === 'function') { const html = (obj.renderHTML as Function)(); if (typeof html === 'string') sections.push(html); } } } catch { /* factory may require args */ } } } } catch { /* module may not have renderable exports */ } try { const uiMod = taskListDisplay as Record<string, unknown>; for (const key of Object.keys(uiMod)) { const val = uiMod[key]; // Look for factory functions that return objects with render/renderHTML if (typeof val === 'function' && /^create|^make|^render|^build/i.test(key)) { try { const instance = (val as Function)(); if (typeof instance === 'string' && instance.includes('<')) { sections.push(instance); } else if (instance && typeof instance === 'object') { const obj = instance as Record<string, unknown>; if (typeof obj.render === 'function') { const html = (obj.render as Function)(); if (typeof html === 'string') sections.push(html); } else if (typeof obj.renderHTML === 'function') { const html = (obj.renderHTML as Function)(); if (typeof html === 'string') sections.push(html); } } } catch { /* factory may require args */ } } } } catch { /* module may not have renderable exports */ }
return `<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Web Dashboard</title> <style>${css}</style></head><body> <div class="game-container"> ${sections.join('\n')} </div></body></html>`;}
// ─── Router ──────────────────────────────────────────────────────────────────
type Handler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
const routes: Record<string, Handler> = { '/': (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(renderPage()); },
'/health': (_req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'ok', service: 'Web Dashboard', uptime: Math.floor((Date.now() - _svcMetrics.uptime_start) / 1000), modules: Object.keys(_svcModules), })); },
'/metrics': (_req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ..._svcMetrics, uptime_seconds: Math.floor((Date.now() - _svcMetrics.uptime_start) / 1000), }, null, 2)); },
'/modules': (_req, res) => { const info = Object.entries(_svcModules).map(([name, mod]) => { const phoenix = (mod as Record<string, unknown>)._phoenix as Record<string, unknown> | undefined; return { name, risk_tier: phoenix?.risk_tier ?? 'unknown', exports: Object.keys(mod).filter(k => k !== '_phoenix'), }; }); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(info, null, 2)); },};
// ─── Server ──────────────────────────────────────────────────────────────────
function handleRequest(req: IncomingMessage, res: ServerResponse): void { const url = req.url ?? '/'; const path = url.split('?')[0];
_svcMetrics.requests_total++; _svcMetrics.requests_by_path[path] = (_svcMetrics.requests_by_path[path] ?? 0) + 1;
const handler = routes[path]; if (handler) { try { handler(req, res); } catch (err) { _svcMetrics.errors_total++; res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: String(err) })); } } else { res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Not Found', path, available: Object.keys(routes), })); }}
export function startServer(port?: number): { server: ReturnType<typeof createServer>; port: number; ready: Promise<void> } { const requestedPort = port ?? parseInt(process.env.WEB_DASHBOARD_PORT ?? process.env.PORT ?? '3002', 10); const server = createServer(handleRequest); let actualPort = requestedPort;
const ready = new Promise<void>(resolve => { server.listen(requestedPort, () => { const addr = server.address(); if (addr && typeof addr === 'object') actualPort = addr.port; result.port = actualPort; console.log(`Web Dashboard listening on http://localhost:${actualPort}`); console.log(` / — web client`); console.log(` /health — health check`); console.log(` /metrics — request metrics`); console.log(` /modules — registered modules`); resolve(); }); });
const result = { server, port: actualPort, ready }; return result;}
// Start when run directlyconst isMain = process.argv[1]?.endsWith('/web-dashboard/server.js') || process.argv[1]?.endsWith('/web-dashboard/server.ts');if (isMain) { startServer();}