import { createReadStream, existsSync, statSync } from "node:fs"; import { createServer } from "node:http"; import { extname, join, normalize } from "node:path"; import { fileURLToPath } from "node:url"; const root = join(fileURLToPath(new URL(".", import.meta.url)), "dist"); const port = Number(process.env.PORT || 7860); const contentTypes = { ".css": "text/css; charset=utf-8", ".html": "text/html; charset=utf-8", ".js": "application/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".map": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".wasm": "application/wasm", }; function resolvePath(urlPath) { const decoded = decodeURIComponent(urlPath.split("?")[0] || "/"); const clean = normalize(decoded).replace(/^(\.\.[/\\])+/, ""); const candidate = join(root, clean); if (existsSync(candidate) && statSync(candidate).isFile()) { return candidate; } return join(root, "index.html"); } const server = createServer((request, response) => { const filePath = resolvePath(request.url || "/"); const type = contentTypes[extname(filePath)] || "application/octet-stream"; response.setHeader("content-type", type); response.setHeader("cross-origin-opener-policy", "same-origin"); response.setHeader("cross-origin-embedder-policy", "credentialless"); response.setHeader("cross-origin-resource-policy", "cross-origin"); response.setHeader("cache-control", filePath.endsWith("index.html") ? "no-store" : "public, max-age=31536000, immutable"); createReadStream(filePath).pipe(response); }); server.listen(port, "0.0.0.0", () => { console.log(`Pi CLI Web serving ${root} on ${port}`); });