import http from "node:http"; import fs from "node:fs"; import path from "node:path"; import { URL } from "node:url"; const MIME: Record = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".ico": "image/x-icon", ".woff2": "font/woff2", ".map": "application/json", }; function proxy(req: http.IncomingMessage, res: http.ServerResponse, apiBase: string) { const target = new URL(req.url || "/", apiBase); const headers = { ...req.headers, host: target.host }; const preq = http.request( { protocol: target.protocol, hostname: target.hostname, port: target.port, path: target.pathname + target.search, method: req.method, headers, }, (pres) => { res.writeHead(pres.statusCode || 502, pres.headers); pres.pipe(res); }, ); preq.on("error", (err) => { res.writeHead(502, { "Content-Type": "text/plain" }); res.end(`proxy error: ${err.message}`); }); req.pipe(preq); } export function startUiServer(opts: { distDir: string; apiBase: string; port?: number; }): Promise<{ port: number; url: string; close: () => void }> { const port = opts.port ?? 18574; const server = http.createServer((req, res) => { const url = req.url || "/"; if (url.startsWith("/api") || url.startsWith("/covers")) { proxy(req, res, opts.apiBase); return; } let filePath = path.join(opts.distDir, url === "/" ? "index.html" : decodeURIComponent(url.split("?")[0])); if (!filePath.startsWith(opts.distDir)) { res.writeHead(403); res.end("forbidden"); return; } if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { filePath = path.join(opts.distDir, "index.html"); } const ext = path.extname(filePath).toLowerCase(); res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream" }); fs.createReadStream(filePath).pipe(res); }); return new Promise((resolve, reject) => { server.listen(port, "127.0.0.1", () => { resolve({ port, url: `http://127.0.0.1:${port}`, close: () => server.close(), }); }); server.on("error", reject); }); }