ShtukbaseStandard
файл пакета→ .shtukbase/packages/lenses/kit/server/serve.ts

kit/server/serve.ts

39 строк, 2.7 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. import { readFileSync, writeFileSync, readdirSync } from "node:fs";
  2. import { resolve, sep, extname } from "node:path";
  3. const root = resolve(process.argv[2]), port = Number(process.argv[3]), token = crypto.randomUUID();
  4. const inside = (p: string) => {
  5. const f = resolve(root, p);
  6. if (!f.startsWith(root + sep) || p.split("/").some((s) => s.startsWith("."))) throw new Error("refused: outside the base");
  7. return f;
  8. };
  9. const head = (t: string) => {
  10. const m = t.match(/^---\n([\s\S]*?)\n---/); const o: Record<string, string> = {};
  11. if (m) for (const l of m[1].split("\n")) { const i = l.indexOf(":"); if (i > 0) o[l.slice(0, i).trim()] = l.slice(i + 1).trim().replace(/^"|"$/g, ""); }
  12. return o;
  13. };
  14. const actions: Record<string, (p: any) => unknown> = {
  15. read: (p) => readFileSync(inside(p.path), "utf8"),
  16. records: (p) => readdirSync(inside(p.from)).filter((n) => n.endsWith(".md")).map((n) => ({ path: `${p.from}/${n}`, ...head(readFileSync(inside(`${p.from}/${n}`), "utf8")) })),
  17. patch: (p) => {
  18. const f = inside(p.path); let t = readFileSync(f, "utf8");
  19. for (const [k, v] of Object.entries(p.set)) { const re = new RegExp(`^${k}:.*$`, "m"), line = `${k}: "${v}"`; t = re.test(t) ? t.replace(re, line) : t.replace(/^---\n/, `---\n${line}\n`); }
  20. writeFileSync(f, t); return { ok: true };
  21. },
  22. };
  23. const types: Record<string, string> = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".md": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png" };
  24. Bun.serve({ port, hostname: "127.0.0.1", async fetch(req) {
  25. const url = new URL(req.url);
  26. if (url.pathname === "/_api") {
  27. const origin = req.headers.get("origin"), cookie = req.headers.get("cookie") ?? "";
  28. if (req.method !== "POST" || (origin && origin !== `http://127.0.0.1:${port}`) || !cookie.includes(`kit=${token}`)) return new Response("refused", { status: 403 });
  29. try { const p = await req.json(); const fn = actions[p.do]; if (!fn) throw new Error("unknown action"); return Response.json({ result: fn(p) }); }
  30. catch (e) { return Response.json({ error: String((e as Error).message) }); }
  31. }
  32. try {
  33. const f = inside(decodeURIComponent(url.pathname.slice(1))), ext = extname(f), h = new Headers({ "content-type": types[ext] ?? "application/octet-stream" });
  34. if (ext === ".html") h.set("set-cookie", `kit=${token}; SameSite=Strict; HttpOnly; Path=/`);
  35. // an SVG opened by itself is a document of this origin: it gets no scripts, so it cannot reach the API (icons, card art)
  36. if (ext === ".svg") h.set("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'");
  37. return new Response(readFileSync(f), { headers: h });
  38. } catch { return new Response("not found", { status: 404 }); }
  39. } });