serve.mjs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env node
  2. /**
  3. * scrollcraft static server.
  4. *
  5. * A scrollcraft page cannot be verified from file://. The engine fetches each
  6. * clip as a Blob, and file:// fetches are blocked by CORS in every browser, so
  7. * the page silently falls back to posters and looks fine while proving nothing.
  8. * Serve it.
  9. *
  10. * node serve.mjs --root builds/perkform --port 4500
  11. */
  12. import http from "node:http";
  13. import fs from "node:fs";
  14. import path from "node:path";
  15. const argv = process.argv.slice(2);
  16. const arg = (n, d) => { const i = argv.indexOf(n); return i > -1 && argv[i + 1] ? argv[i + 1] : d; };
  17. const ROOT = path.resolve(arg("--root", "."));
  18. const PORT = parseInt(arg("--port", "4500"), 10);
  19. const TYPES = {
  20. ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8",
  21. ".js": "text/javascript; charset=utf-8", ".json": "application/json",
  22. ".mp4": "video/mp4", ".webm": "video/webm",
  23. ".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg",
  24. ".svg": "image/svg+xml", ".woff2": "font/woff2",
  25. };
  26. http.createServer((req, res) => {
  27. const url = decodeURIComponent(req.url.split("?")[0]);
  28. let file = path.join(ROOT, url === "/" ? "/index.html" : url);
  29. // Refuse to serve outside the root even if the path walks up.
  30. if (!file.startsWith(ROOT)) { res.writeHead(403).end("forbidden"); return; }
  31. if (fs.existsSync(file) && fs.statSync(file).isDirectory()) file = path.join(file, "index.html");
  32. if (!fs.existsSync(file)) { res.writeHead(404).end("not found"); return; }
  33. const ext = path.extname(file).toLowerCase();
  34. const stat = fs.statSync(file);
  35. res.writeHead(200, {
  36. "Content-Type": TYPES[ext] || "application/octet-stream",
  37. "Content-Length": stat.size,
  38. // No caching: verification loops re-shoot the same URLs after edits, and a
  39. // cached clip or stylesheet makes you screenshot the previous build.
  40. "Cache-Control": "no-store",
  41. "Accept-Ranges": "bytes",
  42. });
  43. fs.createReadStream(file).pipe(res);
  44. }).listen(PORT, () => {
  45. console.log(`scrollcraft: ${ROOT}\n http://localhost:${PORT}`);
  46. });