import { stat } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import { extname, resolve, sep } from "node:path"; import { browserBundle } from "./browser"; const root = fileURLToPath(new URL("../", import.meta.url)); const production = Bun.argv.includes("--dist"); const port = Number(Bun.env.PORT ?? 4176); const types: Record = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", }; const headers = { "cache-control": "no-store", "x-content-type-options": "nosniff", }; const server = Bun.serve({ port, hostname: "127.0.0.1", async fetch(request): Promise { try { const path = decodeURIComponent(new URL(request.url).pathname); if (request.method !== "GET" && request.method !== "HEAD") return new Response(null, { status: 405 }); if (path.split("/").includes("..")) return new Response(null, { status: 403 }); if ( path.startsWith("/v1/") || ["/health", "/ready", "/version"].includes(path) ) { return Response.json( { error: "preview_has_no_backend" }, { status: 503, headers }, ); } if (!production && path === "/src/app.js") { const bundle = await browserBundle(); return new Response(request.method === "HEAD" ? null : bundle, { headers: { ...headers, "content-type": types[".js"]! }, }); } const sourceStyle = !production && path === "/src/styles.css"; const base = production ? resolve(root, "dist") : sourceStyle ? resolve(root, "src") : resolve(root, "public"); let file = resolve(base, sourceStyle ? "styles.css" : `.${path}`); if ( path === "/" || path === "/account" || path === "/account/" || path === "/privacy" || path === "/privacy/" ) file = resolve(base, "index.html"); if (!file.startsWith(base + sep)) return new Response(null, { status: 403 }); if (!(await stat(file)).isFile()) return new Response("Not found", { status: 404 }); return new Response(request.method === "HEAD" ? null : Bun.file(file), { headers: { ...headers, "content-type": types[extname(file)] ?? "application/octet-stream", }, }); } catch { return new Response("Not found", { status: 404, headers }); } }, }); console.log(`VNOX Web: http://127.0.0.1:${server.port}`); for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, () => { void server.stop(true).then(() => process.exit(0)); });