website

#astro#js#html#css

git clone https://git.pyrossh.dev/website

木 Personal website of pyrossh. Built with astrojs, shiki, vite.


tests/helpers/static-server.js
import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import path from "node:path";

const MIME_TYPES = {
  ".html": "text/html; charset=utf-8",
  ".css": "text/css; charset=utf-8",
  ".js": "text/javascript; charset=utf-8",
  ".json": "application/json; charset=utf-8",
  ".svg": "image/svg+xml",
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".ico": "image/x-icon",
  ".xml": "application/xml; charset=utf-8",
  ".txt": "text/plain; charset=utf-8",
  ".woff2": "font/woff2",
  ".pdf": "application/pdf",
};

async function resolveFile(rootDir, urlPath) {
  const decoded = decodeURIComponent(urlPath.split("?")[0]);
  const safeSuffix = path.normalize(decoded).replace(/^(\.\.[/\\])+/, "");
  const requestedPath = path.join(rootDir, safeSuffix);

  const candidates = requestedPath.endsWith("/")
    ? [path.join(requestedPath, "index.html")]
    : [requestedPath, path.join(requestedPath, "index.html"), `${requestedPath}.html`];

  for (const candidate of candidates) {
    try {
      const info = await stat(candidate);
      if (info.isFile()) return candidate;
    } catch {
      // try next candidate
    }
  }
  return null;
}

/**
 * Serves a pre-built static site directory (e.g. Eleventy's `dist/`) over HTTP,
 * falling back to `404.html` so tests see the same not-found page as production.
 */
export async function startStaticServer(rootDir, { notFoundFile = "404.html" } = {}) {
  const server = createServer(async (req, res) => {
    try {
      const filePath = await resolveFile(rootDir, req.url ?? "/");
      if (filePath) {
        const body = await readFile(filePath);
        res.writeHead(200, { "content-type": MIME_TYPES[path.extname(filePath)] ?? "application/octet-stream" });
        res.end(body);
        return;
      }
      const fallback = path.join(rootDir, notFoundFile);
      try {
        const body = await readFile(fallback);
        res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
        res.end(body);
      } catch {
        res.writeHead(404, { "content-type": "text/plain" });
        res.end("Not found");
      }
    } catch (err) {
      res.writeHead(500, { "content-type": "text/plain" });
      res.end(String(err));
    }
  });

  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  const { port } = server.address();
  return {
    url: `http://127.0.0.1:${port}`,
    close: () => new Promise((resolve) => server.close(resolve)),
  };
}