import { createServer, type Server } from 'http' import { exec } from 'child_process' import { readFile } from 'fs/promises' import { existsSync } from 'fs' import { join, normalize, extname, dirname, sep } from 'path' import { fileURLToPath } from 'url' import { AddressInfo } from 'net' import { hostname } from 'os' import { loadPricing } from './models.js' import { buildMenubarPayloadForRange } from './usage-aggregator.js' import type { MenubarPayload } from './menubar-json.js' import { periodInfoFromQuery, UsageQueryError } from './cli-date.js' import { pullDevices, linkRemote } from './sharing/host.js' import { browse } from './sharing/discovery.js' import { loadOrCreateIdentity } from './sharing/identity.js' import { pairingCode } from './sharing/pairing.js' import { getSharingDir, loadRemotes, loadShareAlways, saveShareAlways } from './sharing/store.js' import { ShareController } from './sharing/share-controller.js' import { sanitizeForSharing } from './sharing/sanitize.js' import { buildContextTree, findClaudeSession, listRecentTitledSessions, snapshotRows, type ContextTreeResult, type SessionRef } from './context-tree.js' import { buildCodexContextTree, findCodexSession, listRecentCodexSessions } from './context-tree-codex.js' function readBody(req: import('http').IncomingMessage): Promise { return new Promise((resolve, reject) => { let body = '' req.on('data', (c) => { body += c if (body.length > 1_000_000) reject(new Error('request body too large')) }) req.on('end', () => resolve(body)) req.on('error', reject) }) } function writeJsonError(res: import('http').ServerResponse, status: number, error: string): void { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' }) res.end(JSON.stringify({ error })) } // Cap on the cached local payload, matched to the parser's own session cache // (parser.ts) so the assembled payload is never staler than its source data. const LOCAL_PAYLOAD_TTL_MS = 180_000 const HERE = dirname(fileURLToPath(import.meta.url)) // Locate the built React dashboard (dist/dash). Works both when running from a // published package (dist/dash next to the bundled CLI) and from source. function resolveDashDir(): string | null { const candidates = [ process.env['CODEBURN_DASH_DIR'], join(HERE, 'dash'), join(HERE, '..', 'dist', 'dash'), join(HERE, '..', 'dash', 'dist'), ].filter(Boolean) as string[] for (const dir of candidates) { if (existsSync(join(dir, 'index.html'))) return dir } return null } const CONTENT_TYPES: Record = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json; charset=utf-8', '.woff2': 'font/woff2', '.woff': 'font/woff', '.png': 'image/png', '.ico': 'image/x-icon', '.map': 'application/json', } const NOT_BUILT_PAGE = '' + '' + '

Dashboard not built yet

' + '

Build the web UI once, then reload:

' + '
cd dash && npm install && npm run build
' + '

The CLI keeps serving the live data API in the meantime.

' function openBrowser(url: string): void { const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start ""' : 'xdg-open' try { exec(`${cmd} ${url}`) } catch { /* user can open it manually */ } } export function injectDashboardBootstrap(html: string, payload: unknown): string { const json = JSON.stringify(payload) if (json === undefined) throw new TypeError('dashboard bootstrap payload is not serializable') // Keep the JSON safe at the boundary where it enters an HTML script. This is // deliberately inside the helper so callers cannot forget the escape. const safeJson = json.replace(/ `\n