Files
sproutblog/worker.js
2026-04-14 13:17:55 +08:00

662 lines
20 KiB
JavaScript

const DEFAULT_SITE_TITLE = "SproutBlog";
export default {
async fetch(request, env) {
const url = new URL(request.url);
const path = normalizePath(url.pathname);
if (!env.DB) {
return htmlResponse(renderLayout("配置缺失", `
<h1>DB 绑定未配置</h1>
<p>请先在 <code>wrangler.toml</code> 里配置 D1 数据库。</p>
`), 500);
}
if (request.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders() });
}
try {
if (request.method === "GET") {
if (path === "/") return await handleIndex(env, url);
if (path.startsWith("/post/")) return await handlePost(env, path.slice(6));
if (path === "/admin" || path === "/admin/new" || path.startsWith("/admin/edit/")) {
return await handleAdminPage(request, env, url, path);
}
if (path === "/api/posts") return await handleApiList(env, url);
if (path.startsWith("/api/posts/")) return await handleApiRead(env, path.slice(11));
}
if (path === "/admin/save" && request.method === "POST") {
return await handleAdminSave(request, env, url);
}
if (path === "/admin/delete" && request.method === "POST") {
return await handleAdminDelete(request, env, url);
}
if (path === "/api/posts" && request.method === "POST") {
return await handleApiCreate(request, env);
}
if (path.startsWith("/api/posts/")) {
const idOrSlug = path.slice(11);
if (request.method === "PUT") return await handleApiUpdate(request, env, idOrSlug);
if (request.method === "DELETE") return await handleApiDelete(request, env, idOrSlug);
}
return notFoundPage();
} catch (error) {
return htmlResponse(renderLayout("错误", `
<h1>发生错误</h1>
<pre>${escapeHtml(error?.stack || error?.message || String(error))}</pre>
`), 500);
}
}
};
async function handleIndex(env, url) {
const q = (url.searchParams.get("q") || "").trim();
const posts = await listPosts(env.DB, { publishedOnly: true, q });
return htmlResponse(renderLayout(pageTitle(env, "首页"), `
<header>
<h1>${escapeHtml(pageTitle(env))}</h1>
<p><a href="/admin">后台</a></p>
</header>
${q ? `<p>搜索:<strong>${escapeHtml(q)}</strong></p>` : ""}
${posts.length ? posts.map(renderPostCard).join("") : "<p>暂无文章。</p>"}
`));
}
async function handlePost(env, slug) {
const post = await env.DB.prepare(
"SELECT * FROM posts WHERE slug = ? AND published = 1 LIMIT 1"
).bind(decodeURIComponent(slug)).first();
if (!post) return notFoundPage();
return htmlResponse(renderLayout(`${post.title} - ${pageTitle(env)}`, `
<p><a href="/">返回首页</a></p>
<article>
<h1>${escapeHtml(post.title)}</h1>
<p>${formatDateTime(post.updated_at)}</p>
<div>${renderMarkdown(post.content)}</div>
</article>
`));
}
async function handleAdminPage(request, env, url, path) {
const auth = requireAdmin(request, env);
if (auth) return auth;
let post = blankPost();
if (path.startsWith("/admin/edit/")) {
const id = Number(path.slice("/admin/edit/".length));
if (Number.isFinite(id) && id > 0) {
post = await getPostById(env.DB, id) || post;
}
} else if (path === "/admin" && url.searchParams.get("id")) {
const id = Number(url.searchParams.get("id"));
if (Number.isFinite(id) && id > 0) {
post = await getPostById(env.DB, id) || post;
}
}
const q = (url.searchParams.get("q") || "").trim();
const posts = await listPosts(env.DB, { publishedOnly: false, q });
return htmlResponse(renderLayout(`后台 - ${pageTitle(env)}`, `
<p><a href="/">返回首页</a></p>
<h1>后台</h1>
<section>
<h2>${post.id ? `编辑 #${post.id}` : "新建文章"}</h2>
<form method="post" action="/admin/save">
<input type="hidden" name="id" value="${escapeAttr(post.id || "")}">
<p>
<label>标题<br><input name="title" type="text" value="${escapeAttr(post.title || "")}" required></label>
</p>
<p>
<label>Slug<br><input name="slug" type="text" value="${escapeAttr(post.slug || "")}"></label>
</p>
<p>
<label>摘要<br><input name="excerpt" type="text" value="${escapeAttr(post.excerpt || "")}"></label>
</p>
<p>
<label>内容<br><textarea name="content" required>${escapeHtml(post.content || "")}</textarea></label>
</p>
<p>
<label><input name="published" type="checkbox" value="1" ${post.published ? "checked" : ""}> 发布</label>
</p>
<p><button type="submit">保存</button></p>
</form>
</section>
<hr>
<section>
<h2>文章列表</h2>
<form method="get" action="/admin">
<p>
<label>查询<br><input name="q" type="text" value="${escapeAttr(q)}"></label>
</p>
<p><button type="submit">搜索</button></p>
</form>
${posts.length ? posts.map(renderAdminCard).join("") : "<p>没有找到文章。</p>"}
</section>
`));
}
async function handleAdminSave(request, env, url) {
const auth = requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
const rawId = data.id ? Number(data.id) : null;
const id = Number.isFinite(rawId) && rawId > 0 ? rawId : null;
const title = cleanText(data.title);
const content = cleanText(data.content);
const excerpt = cleanText(data.excerpt);
const slugBase = cleanText(data.slug) || title;
const published = isTruthy(data.published) ? 1 : 0;
if (!title || !content) {
return htmlResponse(renderLayout("表单错误", `
<h1>标题和内容不能为空</h1>
<p><a href="/admin">返回后台</a></p>
`), 400);
}
const slug = await uniqueSlug(env.DB, slugify(slugBase), id);
const now = new Date().toISOString();
if (id) {
const exists = await getPostById(env.DB, id);
if (!exists) return notFoundPage();
await env.DB.prepare(`
UPDATE posts
SET title = ?, slug = ?, excerpt = ?, content = ?, published = ?, updated_at = ?
WHERE id = ?
`).bind(title, slug, excerpt, content, published, now, id).run();
} else {
const result = await env.DB.prepare(`
INSERT INTO posts (title, slug, excerpt, content, published, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
`).bind(title, slug, excerpt, content, published, now, now).run();
return Response.redirect(new URL(`/admin?id=${result.meta.last_row_id}&saved=1`, url), 303);
}
return Response.redirect(new URL(`/admin?id=${id}&saved=1`, url), 303);
}
async function handleAdminDelete(request, env, url) {
const auth = requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
const id = Number(data.id);
if (!Number.isFinite(id) || id <= 0) {
return htmlResponse(renderLayout("表单错误", `
<h1>无效的文章 ID</h1>
<p><a href="/admin">返回后台</a></p>
`), 400);
}
await env.DB.prepare("DELETE FROM posts WHERE id = ?").bind(id).run();
return Response.redirect(new URL(`/admin?deleted=1`, url), 303);
}
async function handleApiList(env, url) {
const q = (url.searchParams.get("q") || "").trim();
const posts = await listPosts(env.DB, { publishedOnly: false, q });
return jsonResponse({ ok: true, posts });
}
async function handleApiRead(env, idOrSlug) {
const post = await readPost(env.DB, idOrSlug);
if (!post) return jsonResponse({ ok: false, error: "Not found" }, 404);
return jsonResponse({ ok: true, post });
}
async function handleApiCreate(request, env) {
const auth = requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
const created = await createOrUpdatePost(env.DB, data, null);
return jsonResponse({ ok: true, post: created }, 201);
}
async function handleApiUpdate(request, env, idOrSlug) {
const auth = requireAdmin(request, env);
if (auth) return auth;
const data = await readBody(request);
const existing = await readPost(env.DB, idOrSlug);
if (!existing) return jsonResponse({ ok: false, error: "Not found" }, 404);
const updated = await createOrUpdatePost(env.DB, data, existing.id);
return jsonResponse({ ok: true, post: updated });
}
async function handleApiDelete(request, env, idOrSlug) {
const auth = requireAdmin(request, env);
if (auth) return auth;
const post = await readPost(env.DB, idOrSlug);
if (!post) return jsonResponse({ ok: false, error: "Not found" }, 404);
await env.DB.prepare("DELETE FROM posts WHERE id = ?").bind(post.id).run();
return jsonResponse({ ok: true, deleted: post.id });
}
async function createOrUpdatePost(db, data, currentId) {
const rawId = currentId ? Number(currentId) : null;
const id = Number.isFinite(rawId) && rawId > 0 ? rawId : null;
const title = cleanText(data.title);
const content = cleanText(data.content);
const excerpt = cleanText(data.excerpt);
const slugBase = cleanText(data.slug) || title;
const published = isTruthy(data.published) ? 1 : 0;
if (!title || !content) {
throw new Error("title 和 content 不能为空");
}
const slug = await uniqueSlug(db, slugify(slugBase), id);
const now = new Date().toISOString();
if (id) {
await db.prepare(`
UPDATE posts
SET title = ?, slug = ?, excerpt = ?, content = ?, published = ?, updated_at = ?
WHERE id = ?
`).bind(title, slug, excerpt, content, published, now, id).run();
return await getPostById(db, id);
}
const result = await db.prepare(`
INSERT INTO posts (title, slug, excerpt, content, published, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
`).bind(title, slug, excerpt, content, published, now, now).run();
return await getPostById(db, result.meta.last_row_id);
}
async function readPost(db, idOrSlug) {
if (!idOrSlug) return null;
const trimmed = decodeURIComponent(String(idOrSlug)).trim();
if (/^\d+$/.test(trimmed)) {
return await getPostById(db, Number(trimmed));
}
return await db.prepare("SELECT * FROM posts WHERE slug = ? LIMIT 1").bind(trimmed).first();
}
async function getPostById(db, id) {
return await db.prepare("SELECT * FROM posts WHERE id = ? LIMIT 1").bind(Number(id)).first();
}
async function listPosts(db, { publishedOnly = true, q = "" } = {}) {
const params = [];
const where = [];
if (publishedOnly) where.push("published = 1");
if (q) {
where.push("(title LIKE ? OR slug LIKE ? OR excerpt LIKE ? OR content LIKE ?)");
const like = `%${q}%`;
params.push(like, like, like, like);
}
const sql = `
SELECT * FROM posts
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY published DESC, updated_at DESC, id DESC
`;
const statement = db.prepare(sql);
const { results } = params.length ? await statement.bind(...params).all() : await statement.all();
return results || [];
}
async function uniqueSlug(db, baseSlug, currentId) {
let slug = baseSlug || "post";
let suffix = 2;
while (true) {
const existing = await db.prepare("SELECT id FROM posts WHERE slug = ? LIMIT 1").bind(slug).first();
if (!existing || Number(existing.id) === Number(currentId)) return slug;
slug = `${baseSlug || "post"}-${suffix++}`;
}
}
function slugify(value) {
const raw = cleanText(value);
const slug = raw
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^\p{L}\p{N}]+/gu, "-")
.replace(/^-+|-+$/g, "")
.replace(/-+/g, "-")
.toLowerCase();
return slug || "post";
}
function renderPostCard(post) {
const excerpt = post.excerpt || stripMarkdown(post.content).slice(0, 180);
return `
<article>
<h2><a href="/post/${encodeURIComponent(post.slug)}">${escapeHtml(post.title)}</a></h2>
<p>${formatDateTime(post.updated_at)}</p>
<p>${escapeHtml(excerpt)}${excerpt.length >= 180 ? "…" : ""}</p>
</article>
`;
}
function renderAdminCard(post) {
return `
<article>
<h3>${escapeHtml(post.title)}</h3>
<p>ID: ${post.id} | Slug: ${escapeHtml(post.slug)} | ${post.published ? "已发布" : "草稿"} | ${formatDateTime(post.updated_at)}</p>
<div>
<a href="/admin/edit/${post.id}">编辑</a>
<form method="post" action="/admin/delete" style="display:inline">
<input type="hidden" name="id" value="${post.id}">
<button type="submit">删除</button>
</form>
</div>
</article>
`;
}
function renderLayout(title, body) {
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<style>
html, body { margin: 0; padding: 0; background: #fff; color: #111; }
body { font-family: Arial, sans-serif; line-height: 1.7; }
main { max-width: 820px; margin: 0 auto; padding: 16px; }
header { margin-bottom: 24px; }
h1, h2, h3 { line-height: 1.3; margin: 0 0 12px; }
article, section { margin: 0 0 24px; }
p { margin: 0 0 12px; }
a { color: inherit; }
input, textarea, button { font: inherit; }
input[type="text"], textarea { width: 100%; box-sizing: border-box; }
textarea { min-height: 320px; }
pre { white-space: pre-wrap; word-break: break-word; }
img { max-width: 100%; height: auto; }
hr { border: 0; border-top: 1px solid #ddd; margin: 24px 0; }
form { margin: 0; }
@media (max-width: 640px) {
main { padding: 12px; }
textarea { min-height: 240px; }
}
</style>
</head>
<body>
<main>
${body}
</main>
</body>
</html>`;
}
function renderMarkdown(source) {
const lines = String(source || "").replace(/\r\n?/g, "\n").split("\n");
let html = "";
let i = 0;
while (i < lines.length) {
const line = lines[i];
const trimmed = line.trim();
if (!trimmed) {
i += 1;
continue;
}
if (trimmed.startsWith("```")) {
const fence = trimmed.slice(3).trim();
i += 1;
const code = [];
while (i < lines.length && !lines[i].trim().startsWith("```")) {
code.push(lines[i]);
i += 1;
}
if (i < lines.length) i += 1;
html += `<pre><code${fence ? ` class="language-${escapeAttr(fence)}"` : ""}>${escapeHtml(code.join("\n"))}</code></pre>`;
continue;
}
const heading = trimmed.match(/^(#{1,6})\s+(.*)$/);
if (heading) {
const level = heading[1].length;
html += `<h${level}>${parseInline(heading[2])}</h${level}>`;
i += 1;
continue;
}
if (/^(\*{3,}|-{3,}|_{3,})$/.test(trimmed)) {
html += "<hr>";
i += 1;
continue;
}
if (/^>\s?/.test(trimmed)) {
const quote = [];
while (i < lines.length && /^>\s?/.test(lines[i].trim())) {
quote.push(lines[i].trim().replace(/^>\s?/, ""));
i += 1;
}
html += `<blockquote>${renderMarkdown(quote.join("\n"))}</blockquote>`;
continue;
}
if (/^(\s*[-*+]\s+|\s*\d+[.)]\s+)/.test(line)) {
const ordered = /^\s*\d+[.)]\s+/.test(line);
const tag = ordered ? "ol" : "ul";
const items = [];
while (i < lines.length && /^(\s*[-*+]\s+|\s*\d+[.)]\s+)/.test(lines[i])) {
items.push(lines[i].replace(/^(\s*[-*+]\s+|\s*\d+[.)]\s+)/, ""));
i += 1;
}
html += `<${tag}>${items.map((item) => `<li>${parseInline(item)}</li>`).join("")}</${tag}>`;
continue;
}
const paragraph = [];
while (i < lines.length) {
const current = lines[i];
const currentTrimmed = current.trim();
if (!currentTrimmed) break;
if (
currentTrimmed.startsWith("```") ||
/^(#{1,6})\s+/.test(currentTrimmed) ||
/^(\*{3,}|-{3,}|_{3,})$/.test(currentTrimmed) ||
/^>\s?/.test(currentTrimmed) ||
/^(\s*[-*+]\s+|\s*\d+[.)]\s+)/.test(current)
) {
break;
}
paragraph.push(currentTrimmed);
i += 1;
}
html += `<p>${parseInline(paragraph.join(" "))}</p>`;
}
return html;
}
function parseInline(text) {
const placeholders = [];
let output = escapeHtml(String(text || ""));
output = output.replace(/`([^`]+?)`/g, (_, code) => {
placeholders.push(`<code>${escapeHtml(code)}</code>`);
return `\u0000${placeholders.length - 1}\u0000`;
});
output = output.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, alt, src, title) => {
const attrs = [`alt="${escapeAttr(alt)}"`, `src="${escapeAttr(src)}"`];
if (title) attrs.push(`title="${escapeAttr(title)}"`);
return `<img ${attrs.join(" ")}>`;
});
output = output.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, href, title) => {
const attrs = [`href="${escapeAttr(href)}"`];
if (title) attrs.push(`title="${escapeAttr(title)}"`);
return `<a ${attrs.join(" ")}>${label}</a>`;
});
output = output.replace(/(\*\*|__)(.+?)\1/g, "<strong>$2</strong>");
output = output.replace(/(\*|_)([^*_].*?)\1/g, "<em>$2</em>");
output = output.replace(/\u0000(\d+)\u0000/g, (_, index) => placeholders[Number(index)] || "");
return output;
}
function stripMarkdown(text) {
return String(text || "")
.replace(/```[\s\S]*?```/g, " ")
.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, "$1")
.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, "$1")
.replace(/[`*_>#-]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function pageTitle(env, suffix = "") {
const site = cleanText(env.SITE_TITLE) || DEFAULT_SITE_TITLE;
return suffix ? `${site} - ${suffix}` : site;
}
function normalizePath(pathname) {
if (pathname === "/") return "/";
return pathname.replace(/\/+$/, "");
}
function htmlResponse(html, status = 200, headers = {}) {
return new Response(html, {
status,
headers: {
"content-type": "text/html; charset=UTF-8",
...headers
}
});
}
function jsonResponse(data, status = 200) {
return new Response(JSON.stringify(data, null, 2), {
status,
headers: {
"content-type": "application/json; charset=UTF-8",
...corsHeaders()
}
});
}
function notFoundPage() {
return htmlResponse(renderLayout("404", `
<h1>404</h1>
<p>页面不存在。</p>
<p><a href="/">返回首页</a></p>
`), 404);
}
function corsHeaders() {
return {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "*"
};
}
function requireAdmin(request, env) {
const password = cleanText(env.ADMIN_PASSWORD);
if (!password) return null;
const header = request.headers.get("Authorization") || "";
if (!header.startsWith("Basic ")) {
return unauthorized();
}
try {
const decoded = atob(header.slice(6));
const split = decoded.indexOf(":");
const inputPassword = split >= 0 ? decoded.slice(split + 1) : "";
if (inputPassword === password) return null;
} catch {
// ignore
}
return unauthorized();
}
function unauthorized() {
return new Response("Authentication required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="SproutBlog admin", charset="UTF-8"'
}
});
}
async function readBody(request) {
const type = request.headers.get("content-type") || "";
if (type.includes("application/json")) {
return await request.json();
}
if (type.includes("multipart/form-data") || type.includes("application/x-www-form-urlencoded")) {
const form = await request.formData();
const data = {};
for (const [key, value] of form.entries()) {
data[key] = value;
}
return data;
}
return {};
}
function cleanText(value) {
return String(value ?? "").trim();
}
function isTruthy(value) {
return value === true || value === "true" || value === "1" || value === 1 || value === "on" || value === "yes";
}
function blankPost() {
return {
id: "",
title: "",
slug: "",
excerpt: "",
content: "",
published: 1
};
}
function escapeHtml(value) {
return String(value ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function escapeAttr(value) {
return escapeHtml(value).replace(/`/g, "&#96;");
}
function formatDateTime(value) {
if (!value) return "";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return escapeHtml(value);
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0");
const dd = String(date.getDate()).padStart(2, "0");
const hh = String(date.getHours()).padStart(2, "0");
const mi = String(date.getMinutes()).padStart(2, "0");
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
}