feat: 每个资料子页面加回导航页的返回入口;导航页与 Docker/Linux/Nginx/408 站点入库

一、子页面返回入口(本次改动)
- 新增 assets/back.js:在页面顶栏的站点标题之后挂「← 资料库」,点一下回根目录
  index.html 并直接落在本资料的详情路由(如 #/knowledge/docker);注册表之外的目录
  (408/)回首页;没有顶栏的页面(408 的 404)退化为左下角浮动按钮
- 层级由脚本自己的 src 反推(new URL('../', src)),任何目录深度都不必改 back.js;
  样式跟随各站点:描边 / 文字用 currentColor、主色用 var(--brand) / var(--accent)、
  圆角跟随 var(--btn-radius),深浅色主题都自适应,打印时自动隐藏;页面里已有
  index.html#/ 形式的返回链接时(interview/ 占位页)不再重复挂
- 新增 tools/add-back-links.js:按 assets/portal.data.js 反查路由与名称,给每个子页面
  注入 <script src="…assets/back.js" data-portal-back=… data-portal-label=…>。
  先删旧标签再按规则插回,位置写错也能自动纠正;--check 只检查(缺一个即退出码 1)、
  --dry 只预演、写入失败不会中断整轮
- 共注入 454 个页面,3 个有意跳过:根 index.html(它本身就是导航页)、
  interview/index.html(已有「← 返回导航」)、408/ds12-tree/og.html(分享预览图页面)
- 末尾是内联 <script> 的 7 个 index.html:标签插在内联脚本之前,保持
  </script>\s*</body> 的既有形态,各站点自检规则不受影响
- .sre-s23/gen.js 的两处模板同步带上该行,重新生成 SRE 模块页不会丢入口
- README 补「子页面怎么回到导航页」一节,并在新增资料流程里加上这一步

二、此前未入库的内容(一并提交)
- 导航页:index.html + assets/portal.css|portal.data.js|portal.js + tools/check-portal.js
- knowledge/docker(14 章)、knowledge/linux(17 章)、knowledge/nginx(17 章)
- 408/ds12-tree 知识卡片(app.js / styles.css / verify.mjs / favicon / og)
- interview 占位页、README.md

校验
- add-back-links --check:454 / 454 已就绪
- check-portal:3 个模块 / 6 份资料全部命中(无死链)
- check-pages:docker 15 页、linux 18 页、nginx 18 页、sre-learning-path 399 页 全部 OK
- 无头 Chrome 实测点击:docker 章节页 / SRE 模块页 / 场景题库 / 项目题库 / 408 卡片页
  都落到对应资料详情,404 的浮动按钮回导航首页;按钮颜色浅色 rgb(23,33,46) 深色
  rgb(231,237,246) 自适应,408 站点圆角保持 0px
- 受版本管理的 402 个页面每个只 +1 行(gen.js +2 行),没有整文件改写

说明:本机沙箱下 knowledge/sre-learning-path/**、408/、knowledge/scenario、project/、
interview/ 这些文件当时不可写(缺低完整性标记),注入是在一次完全权限授权下完成的。
This commit is contained in:
2026-10-14 22:42:38 +08:00
parent ebe280808c
commit 558eb9ae90
493 changed files with 45878 additions and 0 deletions

253
tools/add-back-links.js Normal file
View File

@@ -0,0 +1,253 @@
#!/usr/bin/env node
/* ============================================================================
* 资料库导航 · 给每个资料子页面注入「返回资料库」入口
* ----------------------------------------------------------------------------
* 在页面 </body> 之前插入一行(样式与行为都在 assets/back.js 里):
*
* <script src="../../assets/back.js"
* data-portal-back="knowledge/docker"
* data-portal-label="知识库 › Docker 专题知识库"></script>
*
* 返回目标从 assets/portal.data.js 反查:注册过的资料 → 该资料在导航页里的详情
* (index.html#/knowledge/docker);注册表之外的目录(如 408/)→ 导航页首页
* (index.html#/)。script src 按页面的目录深度自动补 ../。
*
* node tools/add-back-links.js # 注入 / 更新(幂等,可重复运行)
* node tools/add-back-links.js --check # 只检查:有页面没挂就退出码 1
* node tools/add-back-links.js --dry # 只报告将改动的文件,不写盘
*
* 有意不动的页面(会打印在「跳过」里):
* - 仓库根 index.html 它本身就是资料库导航
* - 已有 index.html#/ 返回链接的页面 如 interview/ 占位页,避免出现两个返回入口
* - 408/ds12-tree/og.html 社交分享预览图页面,多一个按钮会污染出图
*
* 末尾是内联 <script> 的页面(各站点 index.html),新标签插在内联脚本之前,
* 这样 `</script>\s*</body>` 这类既有自检规则不受影响。
* ==========================================================================*/
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const ROOT = path.resolve(__dirname, '..');
const CHECK = process.argv.includes('--check');
const DRY = process.argv.includes('--dry');
/* 根目录 index.html、以及预览图页面 */
const SKIP_FILES = new Set(['index.html', '408/ds12-tree/og.html']);
const BACK_JS = path.join(ROOT, 'assets', 'back.js');
const DATA_FILE = path.join(ROOT, 'assets', 'portal.data.js');
/* 匹配本工具注入的那一行(用于幂等 / 更新) */
const TAG_RE = /[ \t]*<script\b[^>]*\bsrc="[^"]*assets\/back\.js"[^>]*><\/script>/;
/* 连同行尾一起删,删完再按规则插回去,位置就唯一了 */
const STRIP_RE = /[ \t]*<script\b[^>]*\bsrc="[^"]*assets\/back\.js"[^>]*><\/script>\r?\n?/;
const SRC_RE = /\bsrc="([^"]*assets\/back\.js)"/;
const problems = [];
const fail = (m) => problems.push(m);
/* ------------------------------------------------------------ 读取注册表 */
function loadPortalData() {
if (!fs.existsSync(DATA_FILE)) {
console.error('✗ 找不到 ' + path.relative(ROOT, DATA_FILE));
process.exit(1);
}
const sandbox = { window: {} };
try {
vm.createContext(sandbox);
vm.runInContext(fs.readFileSync(DATA_FILE, 'utf8'), sandbox, { filename: 'portal.data.js' });
} catch (e) {
console.error('✗ portal.data.js 解析失败:' + e.message);
process.exit(1);
}
const d = sandbox.window.PORTAL_DATA;
if (!d || !Array.isArray(d.modules)) {
console.error('✗ portal.data.js 里没有 window.PORTAL_DATA.modules');
process.exit(1);
}
return d;
}
const DATA = loadPortalData();
/* 路由表:资料目录 → 路由 + 说明文字;目录越长越优先 */
const routes = [];
for (const m of DATA.modules) {
const modDir = (m.id || '').replace(/\/+$/, '');
if (!modDir) continue;
for (const e of m.entries || []) {
const dir = (e.dir || (e.path ? e.path.replace(/\/[^/]*$/, '') : '')).replace(/\/+$/, '');
if (!dir) continue;
routes.push({ dir, route: modDir + '/' + e.id, label: `${m.name} › ${e.name}` });
}
}
routes.sort((a, b) => b.dir.length - a.dir.length);
const modules = DATA.modules
.filter((m) => m && m.id)
.map((m) => ({ dir: m.id.replace(/\/+$/, ''), route: m.id.replace(/\/+$/, ''), label: m.name }));
/* 页面相对路径 → 导航页 hash 路由;未登记的目录返回首页 */
function resolveRoute(rel) {
for (const r of routes) {
if (rel.startsWith(r.dir + '/')) return r;
}
for (const r of modules) {
if (rel.startsWith(r.dir + '/')) return { route: r.route, label: r.label };
}
return { route: '', label: '' };
}
/* ------------------------------------------------------------ 扫描页面 */
const pages = [];
function walk(dir) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
if (e.isDirectory()) {
if (e.name.startsWith('.')) continue; // .git / .sre-s23 / .acl-report
if (e.name === 'node_modules') continue;
walk(path.join(dir, e.name));
} else if (/\.html?$/i.test(e.name)) {
pages.push(path.join(dir, e.name));
}
}
}
walk(ROOT);
pages.sort();
/* ------------------------------------------------------------ 注入位置 */
/* 返回插入了多少个字符的偏移(在 html 里插新标签的位置) */
function insertion(html) {
const bodyIdx = html.lastIndexOf('</body>');
if (bodyIdx < 0) return null;
const before = html.slice(0, bodyIdx);
// 末尾是内联 <script>(各站点 index.html):插到它前面,让「内联脚本紧贴
// </body>」这个既有形态保持不变,各站点自检里 </script>\s*</body> 才不会失配
const close = before.lastIndexOf('</script>');
if (close >= 0 && /^\s*$/.test(before.slice(close + 9))) {
const start = before.lastIndexOf('<script>', close);
if (start >= 0) {
const indent = (before.slice(0, start).match(/[ \t]*$/) || [''])[0];
return { at: start, before: '', after: indent };
}
}
const ws = (before.match(/[ \t]*$/) || [''])[0];
return { at: bodyIdx - ws.length, before: ws, after: '' };
}
function esc(s) {
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function tagLine(rel, info) {
const depth = rel.split('/').length - 1;
const prefix = new Array(depth + 1).join('../');
const attrs = info.route
? ` data-portal-back="${esc(info.route)}" data-portal-label="${esc(info.label)}"`
: '';
return `<script src="${prefix}assets/back.js"${attrs}></script>`;
}
/* ------------------------------------------------------------ 主流程 */
const stats = new Map();
const changed = [];
const missing = [];
let ok = 0, skipped = 0;
function note(rel, status) {
const group = rel.includes('/') ? rel.split('/').slice(0, 2).join('/') : '(根目录)';
if (!stats.has(group)) stats.set(group, { total: 0, ok: 0, skip: 0, todo: 0 });
const s = stats.get(group);
s.total++;
if (status === 'ok') { s.ok++; ok++; }
else if (status === 'skip') { s.skip++; skipped++; }
else s.todo++;
}
for (const file of pages) {
const rel = path.relative(ROOT, file).split(path.sep).join('/');
if (SKIP_FILES.has(rel)) { note(rel, 'skip'); continue; }
const html = fs.readFileSync(file, 'utf8');
// 已有 index.html#/ 形式的返回链接(且不是我们注入的)→ 保持原样
if (!TAG_RE.test(html) && /index\.html#\//.test(html)) { note(rel, 'skip'); continue; }
const info = resolveRoute(rel);
const line = tagLine(rel, info);
const hadTag = TAG_RE.test(html);
// src 指向的 assets/back.js 必须真的能从这一页走到
const srcRel = path.join(path.dirname(rel), line.match(SRC_RE)[1]);
if (!fs.existsSync(path.join(ROOT, srcRel))) {
note(rel, 'todo');
fail(`${rel}: back.js 相对路径不对(${line.match(SRC_RE)[1]})`);
continue;
}
// 先删掉旧标签再按规则插回去:位置不对(例如早先插在内联脚本后面)也能自动纠正,
// 位置本来就对时删插之后字节完全一致,于是天然幂等
const stripped = html.replace(STRIP_RE, '');
const pos = insertion(stripped);
if (!pos) { note(rel, 'todo'); fail(`${rel}: 找不到 </body>,无法注入`); continue; }
const nl = stripped.includes('\r\n') ? '\r\n' : '\n';
const next = stripped.slice(0, pos.at) + pos.before + line + nl + pos.after + stripped.slice(pos.at);
if (next === html) { note(rel, 'ok'); continue; }
if (CHECK || DRY) {
note(rel, 'todo');
if (CHECK) missing.push(`${rel}(${hadTag ? '位置或属性与预期不一致' : '缺少返回入口'})`);
else changed.push(rel);
continue;
}
try {
fs.writeFileSync(file, next, 'utf8');
} catch (e) {
note(rel, 'todo');
fail(`${rel}: 写入失败(${e.code || e.message})—— 若为 EPERM/EACCES,说明该文件不在本次沙箱的写入范围内`);
continue;
}
note(rel, 'todo');
changed.push(rel);
}
/* ------------------------------------------------------------ 输出 */
const line = '─'.repeat(66);
console.log(line);
console.log(CHECK ? '资料库导航 · 返回入口检查' : DRY ? '资料库导航 · 返回入口注入(预演)' : '资料库导航 · 返回入口注入');
console.log(line);
for (const [group, s] of [...stats.entries()].sort()) {
const state = s.todo ? `待处理 ${s.todo}` : '已就绪';
console.log(` ${group.padEnd(28)} ${String(s.total).padStart(3)} 页 已挂 ${s.ok} 跳过 ${s.skip} ${state}`);
}
console.log(line);
console.log(` 页面 ${pages.length - skipped} 个(另跳过 ${skipped} 个)· 已挂 ${ok} · 本次处理 ${changed.length}`);
if (!fs.existsSync(BACK_JS)) fail('assets/back.js 不存在');
if (problems.length) {
console.log('\n✗ 问题:');
problems.forEach((p) => console.log(' - ' + p));
process.exit(1);
}
if (CHECK && missing.length) {
console.log('\n✗ 以下页面还没有返回入口(跑 node tools/add-back-links.js 注入):');
missing.slice(0, 30).forEach((p) => console.log(' - ' + p));
if (missing.length > 30) console.log(` … 另有 ${missing.length - 30} 个`);
process.exit(1);
}
if (CHECK) console.log('\n✓ 全部页面都能返回资料库导航。');
else if (DRY) {
console.log('\n(预演,未写盘)将改动:');
changed.forEach((p) => console.log(' ~ ' + p));
} else if (changed.length) {
console.log(`\n✓ 已写入 ${changed.length} 个页面。`);
} else {
console.log('\n✓ 无需改动:所有页面都已挂好返回入口。');
}

153
tools/check-portal.js Normal file
View File

@@ -0,0 +1,153 @@
#!/usr/bin/env node
/* ============================================================================
* 资料库导航 · 注册表自检
* ----------------------------------------------------------------------------
* 校验 assets/portal.data.js 里登记的每一条资料在磁盘上真实存在,
* 避免导航页出现死链(这也是纯静态 + 手写注册表的唯一风险点)。
*
* node tools/check-portal.js
*
* 检查项:
* 1. 模块 / 资料 id 唯一,path、dir 在仓库内(不允许绝对路径或 .. 逃逸)
* 2. 每个 path 指向的文件存在,且是 .html;每个 dir 指向的目录存在
* 3. path / dir 位于该模块自己的顶层目录下(如 knowledge/… 属于 knowledge 模块)
* 4. 统计条目数与未登记资料(interview/ 这类空目录允许为空)
* 退出码:0 全部通过,1 有问题。
* ==========================================================================*/
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const ROOT = path.resolve(__dirname, '..');
const DATA_FILE = path.join(ROOT, 'assets', 'portal.data.js');
const problems = [];
const warnings = [];
const fail = (m) => problems.push(m);
const warn = (m) => warnings.push(m);
/* ------------------------------------------------------------ 读取注册表 */
if (!fs.existsSync(DATA_FILE)) {
console.error('✗ 找不到 ' + path.relative(ROOT, DATA_FILE));
process.exit(1);
}
const sandbox = { window: {} };
try {
vm.createContext(sandbox);
vm.runInContext(fs.readFileSync(DATA_FILE, 'utf8'), sandbox, { filename: 'portal.data.js' });
} catch (e) {
console.error('✗ portal.data.js 解析失败:' + e.message);
process.exit(1);
}
const DATA = sandbox.window.PORTAL_DATA;
if (!DATA || !Array.isArray(DATA.modules)) {
console.error('✗ portal.data.js 里没有 window.PORTAL_DATA.modules');
process.exit(1);
}
/* ------------------------------------------------------------ 工具 */
const isPlain = (p) => !path.isAbsolute(p) && !/^[a-zA-Z]:/.test(p);
function inside(p, label, where) {
if (typeof p !== 'string' || !p.trim()) { fail(`${where}:${label} 为空`); return false; }
if (!isPlain(p)) { fail(`${where}:${label} 必须是相对路径,实际为 "${p}"`); return false; }
if (p.split(/[\\/]/).includes('..')) { fail(`${where}:${label} 不允许出现 ..("${p}")`); return false; }
return true;
}
function exists(rel, kind) {
const abs = path.join(ROOT, rel);
let st;
try { st = fs.statSync(abs); } catch (e) { return null; }
if (kind === 'dir' && !st.isDirectory()) return null;
if (kind === 'file' && !st.isFile()) return null;
return st;
}
/* ------------------------------------------------------------ 主检查 */
const modIds = new Set();
let total = 0;
const rows = [];
for (const m of DATA.modules) {
const where = `模块 ${m && m.id ? m.id : '(缺少 id)'}`;
if (!m || typeof m !== 'object') { fail(`${where}:不是对象`); continue; }
for (const f of ['id', 'name', 'icon', 'num', 'accent', 'accentSoft']) {
if (!m[f]) fail(`${where}:缺少字段 ${f}`);
}
if (m.id) {
if (modIds.has(m.id)) fail(`${where}:模块 id 重复`);
modIds.add(m.id);
}
if (!Array.isArray(m.entries)) { fail(`${where}:entries 必须是数组`); continue; }
if (m.temp) {
if (inside(m.temp.path, 'temp.path', where) && !exists(m.temp.path, 'file')) {
fail(`${where}:临时页 ${m.temp.path} 不存在`);
}
}
const entryIds = new Set();
let n = 0;
for (const e of m.entries) {
n++;
const w = `${where} › 资料 ${e && e.id ? e.id : '(缺少 id)'}`;
if (!e || typeof e !== 'object') { fail(`${w}:不是对象`); continue; }
for (const f of ['id', 'name', 'desc']) {
if (!e[f]) fail(`${w}:缺少字段 ${f}`);
}
if (e.id) {
if (entryIds.has(e.id)) fail(`${w}:同一模块内 id 重复`);
entryIds.add(e.id);
}
if (e.path) {
if (inside(e.path, 'path', w)) {
if (!exists(e.path, 'file')) fail(`${w}:path ${e.path} 不存在`);
else if (!/\.html?$/i.test(e.path)) warn(`${w}:path ${e.path} 不是 .html,点开会是下载或源码`);
if (m.id && !e.path.startsWith(m.id + '/')) {
fail(`${w}:path ${e.path} 不在 ${m.id}/ 目录下`);
}
}
} else {
fail(`${w}:缺少 path`);
}
if (e.dir && inside(e.dir, 'dir', w) && !exists(e.dir, 'dir')) {
fail(`${w}:dir ${e.dir} 不是已存在的目录`);
}
for (const s of e.stats || []) {
if (!Array.isArray(s) || s.length !== 2) fail(`${w}:stats 每一项必须是 [值, 说明]`);
}
}
total += n;
rows.push([m.id, m.name, n, m.statusText || m.status || '']);
// 模块自己的目录应当存在(interview / knowledge / project)
if (m.id && !exists(m.id, 'dir')) fail(`${where}:目录 ${m.id}/ 不存在`);
}
/* ------------------------------------------------------------ 输出 */
const line = '─'.repeat(64);
console.log(line);
console.log('资料库导航 · 注册表自检');
console.log(line);
for (const [id, name, n, st] of rows) {
console.log(` ${id.padEnd(12)} ${String(n).padStart(2)} 份 ${st.padEnd(10)} ${name}`);
}
console.log(line);
console.log(` 模块 ${rows.length} 个 · 资料 ${total} 份`);
if (warnings.length) {
console.log('\n⚠ 提示:');
warnings.forEach((w) => console.log(' - ' + w));
}
if (problems.length) {
console.log('\n✗ 问题:');
problems.forEach((p) => console.log(' - ' + p));
console.log(`\n共 ${problems.length} 个问题,请修正 assets/portal.data.js 或补齐文件。`);
process.exit(1);
}
console.log('\n✓ 全部通过:注册表里的每个入口都能在磁盘上找到。');