static-server.mjs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Zero-dependency static file server for ZCode Sites packages.
  2. // Usage: node static-server.mjs <site-dir>
  3. // Env: PORT (default 3000), SPA_FALLBACK=1 to answer unknown extensionless paths with index.html.
  4. // Listens on 0.0.0.0 so the runtime health check can reach it.
  5. import { createReadStream } from "node:fs";
  6. import { stat } from "node:fs/promises";
  7. import { createServer } from "node:http";
  8. import { extname, join, normalize, resolve, sep } from "node:path";
  9. const root = resolve(process.argv[2] ?? "dist");
  10. const port = Number(process.env.PORT ?? 3000);
  11. const spaFallback = process.env.SPA_FALLBACK === "1";
  12. const MIME = {
  13. ".html": "text/html; charset=utf-8",
  14. ".htm": "text/html; charset=utf-8",
  15. ".js": "text/javascript; charset=utf-8",
  16. ".mjs": "text/javascript; charset=utf-8",
  17. ".css": "text/css; charset=utf-8",
  18. ".json": "application/json; charset=utf-8",
  19. ".map": "application/json; charset=utf-8",
  20. ".webmanifest": "application/manifest+json",
  21. ".txt": "text/plain; charset=utf-8",
  22. ".xml": "application/xml; charset=utf-8",
  23. ".svg": "image/svg+xml",
  24. ".png": "image/png",
  25. ".jpg": "image/jpeg",
  26. ".jpeg": "image/jpeg",
  27. ".gif": "image/gif",
  28. ".webp": "image/webp",
  29. ".avif": "image/avif",
  30. ".ico": "image/x-icon",
  31. ".woff": "font/woff",
  32. ".woff2": "font/woff2",
  33. ".ttf": "font/ttf",
  34. ".otf": "font/otf",
  35. ".wasm": "application/wasm",
  36. ".mp4": "video/mp4",
  37. ".webm": "video/webm",
  38. ".mp3": "audio/mpeg",
  39. ".wav": "audio/wav",
  40. ".pdf": "application/pdf",
  41. };
  42. async function fileAt(path) {
  43. try {
  44. const info = await stat(path);
  45. return info.isFile() ? { path, size: info.size } : undefined;
  46. } catch {
  47. return undefined;
  48. }
  49. }
  50. // /about → about, about.html, about/index.html (covers static exports of Next, Astro, Hugo…).
  51. async function resolveFile(urlPath) {
  52. const rel = normalize(decodeURIComponent(urlPath)).replace(/^([/\\])+/, "");
  53. const base = join(root, rel);
  54. if (base !== root && !base.startsWith(root + sep)) return undefined;
  55. return (
  56. (await fileAt(base)) ??
  57. (await fileAt(`${base}.html`)) ??
  58. (await fileAt(join(base, "index.html")))
  59. );
  60. }
  61. function send(req, res, status, file) {
  62. const type = MIME[extname(file.path).toLowerCase()] ?? "application/octet-stream";
  63. // Only the hashed-asset directories of common bundlers are cached forever (Vite/Rollup `assets/`,
  64. // Astro `_astro/`, Next `_next/static/`, CRA `static/{js,css,media}/`). Everything else, HTML
  65. // in particular, is revalidated so a redeploy shows up immediately.
  66. const rel = file.path.slice(root.length).split(sep).join("/");
  67. const immutable =
  68. !type.startsWith("text/html") &&
  69. /^\/(assets|_astro|_next\/static|static\/(js|css|media))\//.test(rel);
  70. res.writeHead(status, {
  71. "Content-Type": type,
  72. "Content-Length": file.size,
  73. "Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
  74. });
  75. if (req.method === "HEAD") return res.end();
  76. createReadStream(file.path).pipe(res);
  77. }
  78. createServer(async (req, res) => {
  79. if (req.method !== "GET" && req.method !== "HEAD") {
  80. res.writeHead(405, { Allow: "GET, HEAD" }).end();
  81. return;
  82. }
  83. let pathname;
  84. try {
  85. pathname = new URL(req.url ?? "/", "http://localhost").pathname;
  86. decodeURIComponent(pathname);
  87. } catch {
  88. res.writeHead(400).end();
  89. return;
  90. }
  91. const file = await resolveFile(pathname);
  92. if (file) return send(req, res, 200, file);
  93. if (spaFallback && !extname(pathname)) {
  94. const index = await fileAt(join(root, "index.html"));
  95. if (index) return send(req, res, 200, index);
  96. }
  97. const notFound = await fileAt(join(root, "404.html"));
  98. if (notFound) return send(req, res, 404, notFound);
  99. res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not Found");
  100. }).listen(port, "0.0.0.0", () => {
  101. console.log(
  102. `static-server: serving ${root} on 0.0.0.0:${port}${spaFallback ? " (SPA fallback)" : ""}`,
  103. );
  104. });