'use strict'; const fs = require('fs'); const path = require('path'); const { Service } = require('egg'); const markdown = require('../lib/markdown'); const SITE_NAME = '云仓视频溯源'; /** 目录 / 文件名只允许安全的 ASCII:分类 code、文章 slug 都按这个校验 */ const SAFE_SEGMENT = /^[a-z0-9][a-z0-9_-]{0,63}$/; function ensureDir(dir) { fs.mkdirSync(dir, { recursive: true }); } function writeFile(file, content) { ensureDir(path.dirname(file)); fs.writeFileSync(file, content, 'utf8'); } function escape(value) { return markdown.escapeHtml(value); } /** 日期只留 YYYY-MM-DD */ function dateOnly(value) { if (!value) return ''; const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) return ''; return date.toISOString().slice(0, 10); } /** * 文档站生成器(`/doc/**` 的静态 HTML + `/sitemap.txt`) * * 设计取舍: * - **静态优先**:每次内容变更(增删改分类 / 栏目 / 文章)整站重写一遍,文章量级小(几十篇)足够快; * - 首次访问 / 部署后文件不存在时 **按需生成**(`ensureSite`),不依赖启动钩子; * - 生成目录放在 `run/doc-site`(不进仓库),由 `controller/web/doc.js` 直接读文件返回。 */ class DocSiteService extends Service { get siteDir() { return this.app.config.docSite.dir; } get indexPath() { return path.join(this.siteDir, 'index.html'); } get sitemapPath() { return path.join(this.siteDir, 'sitemap.txt'); } /** 站点根地址(sitemap 用绝对地址):优先配置,其次当前请求的 origin */ baseUrl(ctx) { const configured = (this.app.config.docSite && this.app.config.docSite.baseUrl) || ''; if (configured) return String(configured).replace(/\/+$/, ''); const origin = ctx && ctx.origin ? String(ctx.origin) : ''; return origin.replace(/\/+$/, ''); } /** 已发布的分类 → 栏目 → 文章(仅 status=1,按 sort 排序) */ async loadModel() { const { DocCategory, DocSection, DocArticle } = this.app.model; const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ]; const [ categories, sections, articles ] = await Promise.all([ DocCategory.findAll({ where: { status: 1 }, order }), DocSection.findAll({ where: { status: 1 }, order }), DocArticle.findAll({ where: { status: 1 }, order }), ]); const articlesBySection = new Map(); for (const article of articles) { const key = String(article.sectionId); if (!articlesBySection.has(key)) articlesBySection.set(key, []); articlesBySection.get(key).push(article); } const sectionsByCategory = new Map(); for (const section of sections) { const key = String(section.categoryId); if (!sectionsByCategory.has(key)) sectionsByCategory.set(key, []); sectionsByCategory.get(key).push(section); } return categories.map(category => { const ownSections = sectionsByCategory.get(String(category.id)) || []; const groups = ownSections.map(section => ({ id: Number(section.id), name: section.name, articles: articlesBySection.get(String(section.id)) || [], })).filter(group => group.articles.length > 0); return { id: Number(category.id), code: category.code, name: category.name, description: category.description || '', groups, articles: groups.reduce((all, group) => all.concat(group.articles), []), }; }).filter(category => SAFE_SEGMENT.test(category.code)); } /** 生成整站(页面 + sitemap),返回生成的文件相对路径列表 */ async generate(ctx) { const model = await this.loadModel(); const base = this.baseUrl(ctx); ensureDir(this.siteDir); const written = []; const firstCategory = model[0] || null; // `/doc/`:默认展示第一个分类(没有分类就展示空态) writeFile(this.indexPath, this.renderPage({ model, base, active: firstCategory, article: null })); written.push('index.html'); for (const category of model) { writeFile( path.join(this.siteDir, category.code, 'index.html'), this.renderPage({ model, base, active: category, article: null }), ); written.push(`${category.code}/index.html`); for (const article of category.articles) { writeFile( path.join(this.siteDir, category.code, `${article.slug}.html`), this.renderPage({ model, base, active: category, article }), ); written.push(`${category.code}/${article.slug}.html`); } } this.prune(model); this.writeSitemap(this.buildSitemapUrls(model, base)); return written; } /** 文件不存在就生成(部署后第一次访问 / 清缓存后) */ async ensureSite(ctx) { if (fs.existsSync(this.indexPath)) return; await this.generate(ctx); } /** 删掉已经不该存在的目录 / 页面(分类改名、文章下架后不留旧链接) */ prune(model) { const codes = new Set(model.map(category => category.code)); const slugsByCode = new Map(model.map(category => [ category.code, new Set(category.articles.map(article => `${article.slug}.html`)) ])); for (const entry of fs.readdirSync(this.siteDir, { withFileTypes: true })) { if (!entry.isDirectory()) continue; if (!codes.has(entry.name)) { fs.rmSync(path.join(this.siteDir, entry.name), { recursive: true, force: true }); continue; } const allow = slugsByCode.get(entry.name) || new Set(); for (const file of fs.readdirSync(path.join(this.siteDir, entry.name))) { if (file === 'index.html') continue; if (!allow.has(file)) fs.rmSync(path.join(this.siteDir, entry.name, file), { force: true }); } } } /** 全站 URL:站点首页 + 文档站各级页面(顺序稳定,新增的排在最后) */ buildSitemapUrls(model, base) { const urls = [ `${base}/`, `${base}/doc/` ]; for (const category of model) { urls.push(`${base}/doc/${category.code}/`); for (const article of category.articles) { urls.push(`${base}/doc/${category.code}/${article.slug}.html`); } } return urls; } /** * 写 sitemap.txt:**已有顺序保持不变,新链接追加到末尾**(文章新增即"在尾部加入")。 * 已经不存在的 URL 会被清掉(下架 / 删除的文章不给搜索引擎留着)。 */ writeSitemap(urls) { const wanted = new Set(urls); let existing = []; try { existing = fs.readFileSync(this.sitemapPath, 'utf8') .split(/\r?\n/) .map(line => line.trim()) .filter(Boolean); } catch { existing = []; } const kept = []; const keptSet = new Set(); for (const url of existing) { if (!wanted.has(url) || keptSet.has(url)) continue; kept.push(url); keptSet.add(url); } const appended = urls.filter(url => !keptSet.has(url)); writeFile(this.sitemapPath, `${kept.concat(appended).join('\n')}\n`); } /** 单个文件在磁盘上的位置(拒绝 `..` 越界) */ resolveFile(relative) { const clean = String(relative || '').replace(/^\/+/, '').replace(/\\/g, '/'); const target = path.resolve(this.siteDir, clean); const root = path.resolve(this.siteDir); if (target !== root && !target.startsWith(`${root}${path.sep}`)) return null; return target; } // ---------------- 渲染 ---------------- /** 顶部 tab(分类全量展示,全局可切换) */ renderTabs(model, active) { return model.map(category => { const isActive = active && category.code === active.code; return `${escape(category.name)}`; }).join(''); } /** 侧边栏:当前分类下的「栏目 → 内容页」 */ renderSidebar(active, article) { if (!active) return '

还没有文档分类。

'; if (!active.groups.length) return '

这个分类下还没有内容。

'; return active.groups.map(group => `
${escape(group.name)}
`).join(''); } /** 正文第一行如果就是文章标题(`# 标题`),去掉它:标题已经在页头渲染过了 */ stripLeadingTitle(content, title) { const source = String(content || ''); const lines = source.split('\n'); const first = (lines[0] || '').trim(); if (first === `# ${String(title || '').trim()}`) return lines.slice(1).join('\n'); return source; } /** 文章正文(分类首页展示该分类第一篇文章) */ renderBody(active, article) { if (!active) { return `

${SITE_NAME} · 文档

文档站还没有内容。平台管理员可以在「平台管理 → 文档管理」里新建分类与内容页。

`; } const current = article || active.articles[0] || null; if (!current) { return `

${escape(active.name)}

${escape(active.description || '这个分类下还没有已发布的内容。')}

`; } const rendered = markdown.render(this.stripLeadingTitle(current.content, current.title)); const toc = rendered.toc.filter(item => item.level >= 2 && item.level <= 4); const updated = dateOnly(current.updatedAt || current.updated_at); const summary = current.summary || markdown.plainText(current.content, 140); return `

${escape(current.title)}

${summary ? `

${escape(summary)}

` : ''} ${updated ? `

最近更新:${updated}

` : ''}
${rendered.html}
${toc.length ? `` : ''}
`; } renderPage({ model, base, active, article }) { const current = article || (active && active.articles[0]) || null; const pagePath = current && active ? `/doc/${active.code}/${current.slug}.html` : active ? `/doc/${active.code}/` : '/doc/'; const title = current ? `${current.title} · ${active.name}` : active ? active.name : '文档'; const description = (current && current.summary) || (active && active.description) || `${SITE_NAME} 使用文档`; return ` ${escape(title)} · ${SITE_NAME}
${SITE_NAME} · 文档 返回控制台 →
${this.renderBody(active, current)}
`; } styles() { return ` :root { --brand: #2563eb; --brand-soft: rgba(37, 99, 235, 0.08); --text: #1f2937; --text-muted: #64748b; --border: #e5e7eb; --side-bg: #f8fafc; --code-bg: #0f172a; } * { box-sizing: border-box; } html, body { margin: 0; padding: 0; } body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; color: var(--text); background: #fff; line-height: 1.75; font-size: 15px; } a { color: var(--brand); text-decoration: none; } a:hover { text-decoration: underline; } .topbar { position: sticky; top: 0; z-index: 10; display: flex; align-items: center; gap: 16px; padding: 0 20px; height: 56px; background: rgba(255, 255, 255, 0.94); backdrop-filter: blur(8px); border-bottom: 1px solid var(--border); } .brand { display: inline-flex; align-items: center; gap: 8px; font-weight: 700; color: var(--text); white-space: nowrap; } .brand-dot { width: 10px; height: 10px; border-radius: 50%; background: linear-gradient(135deg, #24bbcd, #2563eb); box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.12); } .tabs { display: flex; align-items: center; gap: 4px; flex: 1 1 auto; min-width: 0; overflow-x: auto; scrollbar-width: none; } .tabs::-webkit-scrollbar { display: none; } .tab { padding: 6px 12px; border-radius: 999px; color: #475569; font-size: 13px; white-space: nowrap; } .tab:hover { background: var(--brand-soft); text-decoration: none; } .tab.is-active { background: var(--brand); color: #fff; } .tab.is-active:hover { background: var(--brand); } .back { font-size: 13px; color: var(--text-muted); white-space: nowrap; } .layout { display: grid; grid-template-columns: 248px minmax(0, 1fr); max-width: 1440px; margin: 0 auto; min-height: calc(100vh - 56px - 60px); } .sidebar { padding: 24px 16px 40px; background: var(--side-bg); border-right: 1px solid var(--border); } .side-head { font-size: 12px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--text-muted); margin: 0 6px 14px; } .side-group { margin-bottom: 18px; } .side-group__title { font-size: 12px; font-weight: 700; color: #334155; margin: 0 6px 6px; } .sidebar ul { list-style: none; margin: 0; padding: 0; } .side-link { display: block; padding: 5px 10px; border-radius: 8px; font-size: 13.5px; color: #334155; line-height: 1.5; } .side-link:hover { background: rgba(37, 99, 235, 0.08); text-decoration: none; } .side-link.is-active { background: var(--brand); color: #fff; } .side-empty { color: var(--text-muted); font-size: 13px; padding: 0 6px; } .content { padding: 32px 40px 64px; min-width: 0; } .doc { max-width: 820px; } .doc-head h1 { font-size: 30px; line-height: 1.35; margin: 0 0 8px; } .doc-summary { margin: 0 0 6px; color: var(--text-muted); } .doc-meta { margin: 0 0 24px; font-size: 12.5px; color: #94a3b8; } .doc-body h2 { font-size: 22px; margin: 36px 0 12px; padding-bottom: 6px; border-bottom: 1px solid var(--border); } .doc-body h3 { font-size: 18px; margin: 28px 0 10px; } .doc-body h4 { font-size: 16px; margin: 24px 0 8px; } .doc-body p { margin: 0 0 14px; } .doc-body ul, .doc-body ol { margin: 0 0 16px; padding-left: 22px; } .doc-body li { margin: 4px 0; } .doc-body code { font-family: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; font-size: 0.9em; background: #f1f5f9; border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; } .doc-body pre { background: var(--code-bg); color: #e2e8f0; border-radius: 10px; padding: 16px 18px; overflow-x: auto; margin: 0 0 18px; } .doc-body pre code { background: transparent; border: 0; padding: 0; color: inherit; } .doc-body blockquote { margin: 0 0 18px; padding: 10px 16px; border-left: 3px solid var(--brand); background: var(--brand-soft); border-radius: 0 8px 8px 0; color: #334155; } .doc-body hr { border: 0; border-top: 1px solid var(--border); margin: 28px 0; } .doc-body a { word-break: break-word; } .doc-toc { margin-top: 40px; padding: 16px 18px; border: 1px solid var(--border); border-radius: 10px; background: var(--side-bg); max-width: 820px; } .doc-toc__title { font-size: 12px; letter-spacing: 0.08em; color: var(--text-muted); margin-bottom: 8px; } .doc-toc ul { list-style: none; margin: 0; padding: 0; } .doc-toc li { margin: 3px 0; font-size: 13.5px; } .doc-toc .lv-3 { padding-left: 14px; } .doc-toc .lv-4 { padding-left: 28px; } .empty { max-width: 720px; } .empty h1 { font-size: 26px; } .empty p { color: var(--text-muted); } .footer { border-top: 1px solid var(--border); padding: 20px; text-align: center; font-size: 12.5px; color: #94a3b8; } @media (max-width: 900px) { .layout { grid-template-columns: 1fr; } .sidebar { border-right: 0; border-bottom: 1px solid var(--border); } .content { padding: 24px 20px 48px; } .doc-head h1 { font-size: 24px; } } `; } } module.exports = DocSiteService;