(opts: {
cwd: string;
preferredPort?: number;
buildHtml: (token: string) => Promise<string>;
getState: () => Promise<any>;
})
| 47 | /** Start the control server on 127.0.0.1. `renderHtml`/`getState` close over the token so the |
| 48 | * page can call the API. Returns a handle with the tokened URL. */ |
| 49 | export async function startDashboardServer(opts: { |
| 50 | cwd: string; |
| 51 | preferredPort?: number; |
| 52 | buildHtml: (token: string) => Promise<string>; |
| 53 | getState: () => Promise<any>; |
| 54 | }): Promise<DashboardServer> { |
| 55 | const token = randomBytes(16).toString('hex'); |
| 56 | |
| 57 | const server = http.createServer((req, res) => { |
| 58 | void (async () => { |
| 59 | try { |
| 60 | const u = new URL(req.url ?? '/', 'http://127.0.0.1'); |
| 61 | const provided = u.searchParams.get('k') ?? req.headers['x-qodex-token']; |
| 62 | const tokenOk = provided === token; |
| 63 | |
| 64 | let body: any = undefined; |
| 65 | if (req.method === 'POST') { |
| 66 | const chunks: Buffer[] = []; |
| 67 | for await (const c of req) chunks.push(c as Buffer); |
| 68 | const raw = Buffer.concat(chunks).toString('utf-8'); |
| 69 | try { body = raw ? JSON.parse(raw) : {}; } catch { body = {}; } |
| 70 | } |
| 71 | |
| 72 | const result = await handleRequest({ |
| 73 | method: req.method ?? 'GET', pathname: u.pathname, tokenOk, body, cwd: opts.cwd, |
| 74 | renderHtml: () => opts.buildHtml(token), getState: opts.getState, |
| 75 | }); |
| 76 | res.writeHead(result.status, { 'content-type': result.contentType, 'cache-control': 'no-store' }); |
| 77 | res.end(result.body); |
| 78 | } catch (e: any) { |
| 79 | res.writeHead(500, { 'content-type': 'application/json' }); |
| 80 | res.end(JSON.stringify({ ok: false, message: e?.message ?? 'error' })); |
| 81 | } |
| 82 | })(); |
| 83 | }); |
| 84 | |
| 85 | await new Promise<void>((resolve, reject) => { |
| 86 | server.once('error', reject); |
| 87 | server.listen(opts.preferredPort ?? 0, '127.0.0.1', () => resolve()); |
| 88 | }); |
| 89 | const addr = server.address(); |
| 90 | const port = typeof addr === 'object' && addr ? addr.port : (opts.preferredPort ?? 0); |
| 91 | return { |
| 92 | port, token, |
| 93 | url: `http://127.0.0.1:${port}/?k=${token}`, |
| 94 | close: () => new Promise<void>(r => server.close(() => r())), |
| 95 | }; |
| 96 | } |
no test coverage detected