Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

3.1 KB
Raw Blame
import { createServer } from "node:http";
import { createReadStream, existsSync, statSync, realpathSync } from "node:fs";
import { resolve, join, extname, sep } from "node:path";
import { fileURLToPath } from "node:url";
import submitHandler from "../api/submit.js";

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

export function createPreviewServer(directory) {
  const root = realpathSync(directory);
  return createServer(async (req, res) => {
    try {
      const pathname = decodeURIComponent(
        new URL(req.url, "http://localhost").pathname,
      );
      if (pathname === "/api/submit") {
        const resAdapter = {
          setHeader: (k, v) => res.setHeader(k, v),
          status(code) {
            res.statusCode = code;
            return {
              json(obj) {
                res.setHeader("Content-Type", "application/json; charset=utf-8");
                res.end(JSON.stringify(obj));
              },
            };
          },
        };
        await submitHandler(req, resAdapter);
        return;
      }
      if (!["GET", "HEAD"].includes(req.method || "")) {
        res.writeHead(405);
        res.end();
        return;
      }
      const requested = resolve(root, "." + pathname);
      if (requested !== root && !requested.startsWith(root + sep)) {
        res.writeHead(403);
        res.end();
        return;
      }
      const target = [
        requested,
        requested + ".html",
        join(requested, "index.html"),
      ].find((p) => existsSync(p) && statSync(p).isFile());
      if (!target) {
        res.writeHead(404);
        res.end("Not found");
        return;
      }
      if (!realpathSync(target).startsWith(root + sep)) {
        res.writeHead(403);
        res.end();
        return;
      }
      res.writeHead(200, {
        "Content-Type": types[extname(target)] || "application/octet-stream",
        "X-Content-Type-Options": "nosniff",
        "Cache-Control": "no-store",
      });
      if (req.method === "HEAD") {
        res.end();
        return;
      }
      const stream = createReadStream(target);
      stream.on("error", () => res.destroy());
      stream.pipe(res);
    } catch {
      res.writeHead(400);
      res.end("Invalid request");
    }
  });
}

if (
  process.argv[1] &&
  resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
  const root = resolve(
    fileURLToPath(new URL("../apps/gallery/out", import.meta.url)),
  );
  if (!existsSync(join(root, "index.html")))
    throw Error("Build the gallery first: npm run build");
  createPreviewServer(root).listen(4382, "127.0.0.1", () =>
    console.log("Gallery preview: http://127.0.0.1:4382"),
  );
}