import { createServer } from "node:http"import { readFile } from "node:fs/promises"import { join } from "node:path"const PORT = Number(process.env.PORT ?? 3000)const ROOT = join(import.meta.dirname, "public")type Handler = (url: URL) => Promise<Response>const TYPES: Record<string, string> = { html: "text/html", css: "text/css", js: "text/javascript", svg: "image/svg+xml",}function typeOf(path: string): string { const ext = path.split(".").at(-1) ?? "" return TYPES[ext] ?? "application/octet-stream"}const routes: Record<string, Handler> = { "/health": async () => new Response("ok"), "/time": async () => Response.json({ now: Date.now() }),}async function files(url: URL): Promise<Response> { const path = join(ROOT, url.pathname) if (!path.startsWith(ROOT)) return new Response("no", { status: 403 }) const body = await readFile(path) return new Response(body, { headers: { "content-type": typeOf(path) }, })}async function handle(url: URL): Promise<Response> { const route = routes[url.pathname] if (route) return route(url) return files(url)}const server = createServer(async (req, res) => { const url = new URL(req.url ?? "/", `http://${req.headers.host}`) const answer = await handle(url) res.writeHead(answer.status, Object.fromEntries(answer.headers)) res.end(Buffer.from(await answer.arrayBuffer()))})server.listen(PORT, () => { console.log(`listening on ${PORT}`)})