包文件→ .shtukbase/packages/lenses/kit/server/serve.ts
kit/server/serve.ts
39 行, 2.7 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- import { readFileSync, writeFileSync, readdirSync } from "node:fs";
- import { resolve, sep, extname } from "node:path";
- const root = resolve(process.argv[2]), port = Number(process.argv[3]), token = crypto.randomUUID();
- const inside = (p: string) => {
- const f = resolve(root, p);
- if (!f.startsWith(root + sep) || p.split("/").some((s) => s.startsWith("."))) throw new Error("refused: outside the base");
- return f;
- };
- const head = (t: string) => {
- const m = t.match(/^---\n([\s\S]*?)\n---/); const o: Record<string, string> = {};
- 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, ""); }
- return o;
- };
- const actions: Record<string, (p: any) => unknown> = {
- read: (p) => readFileSync(inside(p.path), "utf8"),
- records: (p) => readdirSync(inside(p.from)).filter((n) => n.endsWith(".md")).map((n) => ({ path: `${p.from}/${n}`, ...head(readFileSync(inside(`${p.from}/${n}`), "utf8")) })),
- patch: (p) => {
- const f = inside(p.path); let t = readFileSync(f, "utf8");
- 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`); }
- writeFileSync(f, t); return { ok: true };
- },
- };
- 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" };
- Bun.serve({ port, hostname: "127.0.0.1", async fetch(req) {
- const url = new URL(req.url);
- if (url.pathname === "/_api") {
- const origin = req.headers.get("origin"), cookie = req.headers.get("cookie") ?? "";
- if (req.method !== "POST" || (origin && origin !== `http://127.0.0.1:${port}`) || !cookie.includes(`kit=${token}`)) return new Response("refused", { status: 403 });
- try { const p = await req.json(); const fn = actions[p.do]; if (!fn) throw new Error("unknown action"); return Response.json({ result: fn(p) }); }
- catch (e) { return Response.json({ error: String((e as Error).message) }); }
- }
- try {
- const f = inside(decodeURIComponent(url.pathname.slice(1))), ext = extname(f), h = new Headers({ "content-type": types[ext] ?? "application/octet-stream" });
- if (ext === ".html") h.set("set-cookie", `kit=${token}; SameSite=Strict; HttpOnly; Path=/`);
- // an SVG opened by itself is a document of this origin: it gets no scripts, so it cannot reach the API (icons, card art)
- if (ext === ".svg") h.set("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'");
- return new Response(readFileSync(f), { headers: h });
- } catch { return new Response("not found", { status: 404 }); }
- } });