docs(tools): generate full tool usage manual (HTML)

Static scan of tools/ and web/tools/ (1691 files, no tool execution):
purpose/usage/env extraction with provenance badges, family folding
(67 families covering 953 files), 16 directory records, 42 hand-written
chapters plus 4 environment contracts, and a 1996-entry search index.

- tools/tools-manual/{config,scan,extract,chapters,render,verify}.mjs
- tools/build-tools-manual.mjs (--check/--verify/--stats)
- tools/check-tools-manual.mjs (Playwright, desktop + mobile)
- docs/current/tools-manual/index.html (1.08 MB, self-contained)
- web/package.json: manual:tools, check:tools-manual

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 03:22:36 +08:00
parent facbb196d8
commit 5b61c77c2c
10 changed files with 2879 additions and 0 deletions

View File

@@ -0,0 +1,195 @@
#!/usr/bin/env node
/**
* Purpose: 生成项目工具使用手册(docs/current/tools-manual/index.html)。
*
* 静态扫描 tools/ 与 web/tools/ 下的全部脚本,提取用途/用法/环境变量,
* 归并同族脚本,叠加手写核心章节,输出单文件自包含 HTML。
* 全程不执行任何工具(emcc 垫片等脚本带副作用)。
*
* Usage:
* node tools/build-tools-manual.mjs # 生成
* node tools/build-tools-manual.mjs --check # 校验磁盘文件是否为最新(不一致 exit 1)
* node tools/build-tools-manual.mjs --verify # 生成后做语义断言
* node tools/build-tools-manual.mjs --stats # 只打印统计
* node tools/build-tools-manual.mjs --root <dir> --out <file.html>
*
* Exit: 0 成功 / 1 --check 不一致或校验失败 / 2 参数或读取错误
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { REPO_ROOT, CATEGORIES } from "./tools-manual/config.mjs";
import { scan } from "./tools-manual/scan.mjs";
import { extract } from "./tools-manual/extract.mjs";
import { CHAPTERS, CONTRACT_CHAPTERS } from "./tools-manual/chapters.mjs";
import { render } from "./tools-manual/render.mjs";
import { verify } from "./tools-manual/verify.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const DEFAULT_ROOT = path.resolve(HERE, "..");
const DEFAULT_OUT = path.join(DEFAULT_ROOT, "docs/current/tools-manual/index.html");
function parseArgs(argv) {
const options = { check: false, verify: false, stats: false, root: DEFAULT_ROOT, out: DEFAULT_OUT };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--check") options.check = true;
else if (arg === "--verify") options.verify = true;
else if (arg === "--stats") options.stats = true;
else if (arg === "--help" || arg === "-h") {
console.log("node tools/build-tools-manual.mjs [--check] [--verify] [--stats] [--root <dir>] [--out <file>]");
process.exit(0);
} else if (arg === "--root") options.root = path.resolve(argv[++index] ?? ".");
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? DEFAULT_OUT);
else {
console.error(`未知参数:${arg}`);
process.exit(2);
}
}
return options;
}
function slug(value) {
return String(value).toLowerCase().replace(/[^a-z0-9一-龥]+/g, "-").replace(/^-|-$/g, "");
}
/** Anchors must be unique across the whole document. */
function makeAnchorFactory() {
const used = new Set();
return {
/** Hand-authored ids (chapters already carry a `tool-` prefix) are taken as-is. */
reserve(anchor) {
used.add(anchor);
return anchor;
},
unique(prefix, key) {
const base = prefix ? `${prefix}-${slug(key) || "x"}` : slug(key) || "x";
let anchor = base;
let counter = 1;
while (used.has(anchor)) anchor = `${base}-${(counter += 1)}`;
used.add(anchor);
return anchor;
},
};
}
function readNpmCatalog(root) {
const catalog = [];
for (const [rel, cwd] of [["package.json", ""], ["web/package.json", "web"]]) {
let pkg;
try {
pkg = JSON.parse(fs.readFileSync(path.join(root, rel), "utf8"));
} catch {
continue;
}
for (const [name, command] of Object.entries(pkg.scripts ?? {})) catalog.push({ name, command, cwd });
}
return catalog;
}
function buildModel(root) {
const scanned = scan(root);
const extracted = extract(scanned);
const anchors = makeAnchorFactory();
const chapters = CHAPTERS.map((chapter) => ({
...chapter,
anchor: anchors.reserve(chapter.id),
shortTitle: chapter.title.split(" — ")[0],
}));
// Reserved first so generated anchors can never shadow a hand-written id.
for (const contract of CONTRACT_CHAPTERS) anchors.reserve(contract.id);
for (const section of ["overview", "quickstart", "contracts", "topology", "core", "inventory", "npm", "env", "troubleshooting", "maintenance", "appendix"]) anchors.reserve(section);
const families = extracted.families.map((family) => ({ ...family, anchor: anchors.unique("fam", family.id) }));
const records = extracted.records.map((record) => ({ ...record, anchor: anchors.unique("file", record.relPath) }));
const directories = extracted.directories.map((directory) => ({ ...directory, anchor: anchors.unique("dir", directory.relPath) }));
const byCategory = {};
for (const entry of [...families, ...records.filter((record) => !record.familyId), ...directories]) {
byCategory[entry.categoryId] = (byCategory[entry.categoryId] ?? 0) + 1;
}
const stats = {
...extracted.stats,
byCategory,
npmScripts: readNpmCatalog(root).length,
envVars: extracted.envUsage.size,
};
return {
root,
chapters,
contracts: CONTRACT_CHAPTERS,
families,
records,
directories,
envUsage: extracted.envUsage,
npmCatalog: readNpmCatalog(root),
stats,
badges: extracted.badges,
categories: CATEGORIES,
};
}
function main() {
const options = parseArgs(process.argv.slice(2));
if (!fs.existsSync(options.root)) {
console.error(`根目录不存在:${options.root}`);
process.exit(2);
}
const model = buildModel(options.root);
const html = render(model);
if (options.stats) {
const rows = model.stats.rows;
console.log(`文件 ${model.stats.files}`);
console.log(`族 ${model.stats.families}(覆盖 ${model.families.reduce((sum, family) => sum + family.count, 0)} 个文件)`);
console.log(`单列 ${model.stats.singles}`);
console.log(`目录记录 ${model.stats.directories}`);
console.log(`索引行 ${rows}`);
console.log(`手写章节 ${model.chapters.length} + 契约 ${model.contracts.length}`);
console.log(`环境变量 ${model.stats.envVars}`);
console.log(`npm 脚本 ${model.stats.npmScripts}`);
console.log(`分类 ${Object.entries(model.stats.byCategory).map(([id, count]) => `${id}:${count}`).join(" ")}`);
console.log(`页面体积 ${(Buffer.byteLength(html) / 1024).toFixed(0)} KB`);
}
if (options.verify) {
const result = verify({ root: options.root, html, model });
for (const warning of result.warnings) console.warn(`WARN ${warning}`);
for (const error of result.errors) console.error(`FAIL ${error}`);
console.log(`verify: ${result.ok ? "OK" : "FAILED"}(${result.rows} 行,${result.searchEntries} 条搜索项,${(result.bytes / 1024).toFixed(0)} KB)`);
if (!result.ok) process.exit(1);
}
if (options.check) {
let existing = null;
try {
existing = fs.readFileSync(options.out, "utf8");
} catch {
console.error(`FAIL --check:目标文件不存在 ${options.out}`);
process.exit(1);
}
if (existing === html) {
console.log(`check: OK(${options.out} 已是最新)`);
return;
}
let offset = 0;
while (offset < existing.length && offset < html.length && existing[offset] === html[offset]) offset += 1;
console.error(`FAIL --check:磁盘文件与生成结果不一致,首个差异在偏移 ${offset}(磁盘 ${existing.length} 字节 / 生成 ${html.length} 字节)`);
console.error(` 磁盘:${JSON.stringify(existing.slice(offset, offset + 60))}`);
console.error(` 生成:${JSON.stringify(html.slice(offset, offset + 60))}`);
process.exit(1);
}
if (options.stats || options.verify) return;
fs.mkdirSync(path.dirname(options.out), { recursive: true });
fs.writeFileSync(options.out, html);
console.log(`written ${path.relative(options.root, options.out)} (${(Buffer.byteLength(html) / 1024).toFixed(0)} KB)`);
}
main();

View File

@@ -0,0 +1,164 @@
#!/usr/bin/env node
/**
* Purpose: 用真实浏览器校验项目工具手册页面(docs/current/tools-manual/index.html)。
*
* 覆盖:HTTP 200、0 pageerror / 0 console error / 0 失败请求、桌面与移动端无横向溢出、
* 章节锚点可达、搜索可用、分类与「只看核心工具」过滤正确、移动端目录抽屉可开合。
*
* Usage:
* node tools/check-tools-manual.mjs [--headed] [--keep] [--root <dir>]
*
* Exit: 0 通过 / 1 断言失败 / 2 前置缺失(Playwright、Chrome 或页面文件不存在)
*/
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { findChrome, startStaticHost } from "./static-host.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const DEFAULT_ROOT = path.resolve(HERE, "..");
const require = createRequire(path.join(DEFAULT_ROOT, "web", "package.json"));
function parseArgs(argv) {
const options = { headed: false, keep: false, root: DEFAULT_ROOT };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--headed") options.headed = true;
else if (arg === "--keep") options.keep = true;
else if (arg === "--root") options.root = path.resolve(argv[++index] ?? DEFAULT_ROOT);
else if (arg === "--help" || arg === "-h") {
console.log("node tools/check-tools-manual.mjs [--headed] [--keep] [--root <dir>]");
process.exit(0);
} else {
console.error(`未知参数:${arg}`);
process.exit(2);
}
}
return options;
}
const errors = [];
function fail(message) {
errors.push(message);
console.error(`FAIL ${message}`);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const pagefile = path.join(options.root, "docs/current/tools-manual/index.html");
if (!fs.existsSync(pagefile)) {
console.error(`前置缺失:${pagefile} 不存在,先运行 node tools/build-tools-manual.mjs`);
process.exit(2);
}
let chromium;
try {
({ chromium } = require("playwright"));
} catch {
console.error("前置缺失:web/node_modules 下找不到 playwright");
process.exit(2);
}
const chrome = findChrome();
if (!chrome) {
console.error("前置缺失:找不到 Chrome/Chromium(可用 FREECAD_CHROME 指定)");
process.exit(2);
}
// docs/current has no index.html of its own; serve the manual as the default document.
const host = await startStaticHost(path.join(options.root, "docs/current"), "tools-manual/index.html", 0);
const url = `${host.origin}/tools-manual/index.html`;
const browser = await chromium.launch({
executablePath: chrome,
headless: !options.headed,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
try {
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
const page = await browser.newPage({ viewport });
const pageErrors = [];
const consoleErrors = [];
const failedRequests = [];
page.on("pageerror", (error) => pageErrors.push(String(error)));
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText ?? ""}`));
const response = await page.goto(url, { waitUntil: "networkidle" });
const status = response?.status() ?? 0;
if (status !== 200) fail(`${viewport.width}px: HTTP ${status}`);
const dom = await page.evaluate(() => ({
overflow: Math.max(0, document.documentElement.scrollWidth - document.documentElement.clientWidth),
searchEntries: Array.isArray(window.__SEARCH_INDEX__) ? window.__SEARCH_INDEX__.length : -1,
rows: document.querySelectorAll("#inventory-table tbody tr").length,
anchors: {
overview: !!document.getElementById("overview"),
core: !!document.getElementById("core"),
inventory: !!document.getElementById("inventory"),
staticHost: !!document.getElementById("tool-static-host"),
panelScroll: !!document.getElementById("tool-panel-scroll") || !!document.getElementById("tool-layout-probe"),
},
}));
if (dom.overflow > 0) fail(`${viewport.width}px: 横向溢出 ${dom.overflow}px`);
if (dom.searchEntries < 1500) fail(`${viewport.width}px: 搜索索引仅 ${dom.searchEntries} 条(要求 ≥1500)`);
if (dom.rows < 300) fail(`${viewport.width}px: 索引行仅 ${dom.rows} 行(要求 ≥300)`);
for (const [name, present] of Object.entries(dom.anchors)) {
if (!present) fail(`${viewport.width}px: 缺少锚点 ${name}`);
}
if (viewport.width >= 900) {
// Search returns hits and they are reachable.
await page.fill("#search", "functional-suite");
const hits = await page.evaluate(() => [...document.querySelectorAll("#search-results a")].map((a) => a.getAttribute("href")).filter(Boolean));
if (hits.length === 0) fail("搜索 functional-suite 无结果");
// Category filter: every visible row belongs to the chosen category.
await page.selectOption("#cat-filter", "test");
const wrong = await page.evaluate(() => [...document.querySelectorAll("#inventory-table tbody tr")]
.filter((row) => !row.hidden && row.getAttribute("data-cat") !== "test").length);
if (wrong > 0) fail(`分类过滤后仍有 ${wrong} 行不属于 test`);
// Core-only filter: every visible row is a core tool.
await page.selectOption("#cat-filter", "");
await page.check("#core-only");
const nonCore = await page.evaluate(() => [...document.querySelectorAll("#inventory-table tbody tr")]
.filter((row) => !row.hidden && !row.hasAttribute("data-core")).length);
const coreVisible = await page.evaluate(() => [...document.querySelectorAll("#inventory-table tbody tr")]
.filter((row) => !row.hidden).length);
if (nonCore > 0) fail(`只看核心工具时仍有 ${nonCore} 行非核心行可见`);
if (coreVisible < 20) fail(`只看核心工具仅显示 ${coreVisible} 行`);
await page.uncheck("#core-only");
} else {
// Mobile drawer toggles.
await page.click("#drawer-toggle");
const open = await page.evaluate(() => !!document.getElementById("toc")?.classList.contains("open"));
if (!open) fail("移动端目录抽屉未打开");
await page.click("#drawer-toggle");
const closed = await page.evaluate(() => !document.getElementById("toc")?.classList.contains("open"));
if (!closed) fail("移动端目录抽屉未关闭");
}
if (pageErrors.length) fail(`${viewport.width}px: ${pageErrors.length} 个 pageerror,首个:${pageErrors[0]}`);
if (consoleErrors.length) fail(`${viewport.width}px: ${consoleErrors.length} 个 console error,首个:${consoleErrors[0]}`);
if (failedRequests.length) fail(`${viewport.width}px: ${failedRequests.length} 个失败请求,首个:${failedRequests[0]}`);
if (!options.keep) await page.close();
console.log(`${viewport.width}x${viewport.height}: status=${status} rows=${dom.rows} search=${dom.searchEntries} overflow=${dom.overflow}`);
}
} finally {
if (!options.keep) await browser.close();
await host.close();
}
if (errors.length) process.exit(1);
console.log("check-tools-manual: OK");
}
main().catch((error) => {
console.error(`FAIL ${error?.stack ?? error}`);
process.exit(1);
});

View File

@@ -0,0 +1,733 @@
/**
* Hand-written Chinese chapters for the ~40 core tools.
*
* These carry no inference badge: every command below was either declared in
* the tool's own header/argparse or is the exact command in
* web/package.json. Commands use `<repo>` for the workspace root
* (/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD);
* the page renders the literal path next to the overview, and every path
* contains a space, so it must stay quoted in a shell.
*/
const REPO_NOTE = "工作区根目录绝对路径含空格(`Elements SE`):shell 中整体加双引号,或用 `cd \"<绝对路径>\" && …`。";
function chapter(chapter) {
return { repoNote: REPO_NOTE, ...chapter };
}
export const CHAPTERS = [
/* --- 构建与产物 ------------------------------------------------------ */
chapter({
id: "tool-build-web-frontend",
title: "build_web_frontend.py — 前端交付构建",
path: "tools/build_web_frontend.py",
categoryId: "build",
summary: "从固定工作目录构建 operator 前端。不做 npm 生命周期钩子、独立类型检查、测试或原生构建,只执行交付构建。",
when: "改完前端源码、确认无其他待验证改动后,作为交付步骤执行。",
usage: [{ cmd: "cd <repo>/web && python3 ../tools/build_web_frontend.py", note: "工作目录由脚本自身固定,不要在其他目录调用。" }],
inputs: ["web/ 下已就绪的源码与依赖"],
outputs: ["前端构建产物(dist)"],
env: [],
notes: ["脚本刻意不跑 `tsc --noEmit` 与测试:类型检查请单独执行。", "改前端后若需完整发布,用 `npm run build-and-publish`。"],
related: ["tool-build-and-publish", "tool-sync-assets"],
}),
chapter({
id: "tool-build-web-module-artifacts",
title: "build_web_module_artifacts.py — WASM 模块产物构建",
path: "tools/build_web_module_artifacts.py",
categoryId: "build",
summary: "按配置构建 Web 端 WASM 模块产物;支持只构建指定 target,或构建全部 target。",
when: "内核/探针改动后需要重建模块产物时;发布前用 `--all` 做完整构建。",
usage: [
{ cmd: "cd <repo> && python3 tools/build_web_module_artifacts.py --target <name>", note: "只构建指定 target,可重复传入。" },
{ cmd: "cd <repo> && python3 tools/build_web_module_artifacts.py --all", note: "构建全部已配置 target(发布/CI 用)。" },
{ cmd: "cd <repo> && python3 tools/build_web_module_artifacts.py --dry-run", note: "只打印将构建哪些 target。" },
],
params: [
{ flag: "--target <name>", note: "只构建该 target,可重复。" },
{ flag: "--all", note: "构建全部 target。" },
{ flag: "--dry-run", note: "打印选择结果,不执行构建。" },
{ flag: "--jobs <n>", note: "并行度,默认 `FREECAD_BUILD_JOBS` 或 CPU 数。" },
{ flag: "--timeout <s>", note: "单 target 超时,默认 1800 秒。" },
],
env: ["FREECAD_BUILD_JOBS"],
notes: ["WASM 编译必须使用项目预置环境:`EM_CONFIG` / `EM_CACHE` 指向 `freecad-source/build-web/` 下的绝对路径。", "npm 入口:`npm run build:wasm-modules`。"],
related: ["tool-generate-web-module-registry", "tool-sync-assets"],
}),
chapter({
id: "tool-rebuild-occt-rapidjson",
title: "rebuild-occt-rwgltf-rapidjson.sh — 恢复 glTF/GLB 导出能力",
path: "tools/rebuild-occt-rwgltf-rapidjson.sh",
categoryId: "build",
summary: "以 `-DHAVE_RAPIDJSON` 单点重编 4 个 `RWGltf` 编译单元、替换 3 份 `libTKRWMesh.a`,再重链 `FreeCADWebDocumentProbe`、同步资产并重建 dist。OCCT 默认以 `USE_RAPIDJSON=OFF` 构建,缺此步 glTF/GLB 导出会报 “glTF writer is unavailable”。",
when: "任何一次完整 OCCT 重建之后。否则 glTF/GLB 导出静默失效。",
usage: [{ cmd: "cd <repo> && bash tools/rebuild-occt-rwgltf-rapidjson.sh", note: "需要已存在的 OCCT 构建目录与 RapidJSON 源码(`build-web/rapidjson/`)。" }],
inputs: ["`build-web/` 下的 OCCT 构建树", "RapidJSON 1.1.0 源码"],
outputs: ["替换后的 `libTKRWMesh.a`", "重链的 `FreeCADWebDocumentProbe`", "同步后的 kernel 资产与 dist"],
env: [],
notes: ["这是唯一能恢复 glTF/GLB 的路径;不要改为给整个 OCCT 打开 RapidJSON 后全量重建。", "脚本结束后按提示重建 dist。"],
related: ["tool-sync-assets", "tool-build-web-module-artifacts"],
}),
chapter({
id: "tool-build-and-publish",
title: "build-and-publish.mjs — 站点构建与发布",
path: "web/tools/build-and-publish.mjs",
categoryId: "build",
summary: "Web 站点的构建/发布编排脚本;支持 `--help` 打印用法。",
when: "需要一次完整发布时。",
usage: [
{ cmd: "cd <repo>/web && npm run build-and-publish", note: "package.json 中的正式入口。" },
{ cmd: "cd <repo>/web && node tools/build-and-publish.mjs --help", note: "打印用法后退出(少数支持 --help 的工具之一)。" },
],
env: [],
notes: ["依赖构建产物存在;先跑 `npm run build` 更稳。"],
related: ["tool-build-web-frontend", "tool-sync-assets"],
}),
chapter({
id: "tool-sync-assets",
title: "sync-assets.mjs — 内核产物同步",
path: "web/tools/sync-assets.mjs",
categoryId: "build",
summary: "把内核 WASM 产物同步到 `web/public/kernel` 与 `web/dist/kernel`。按 mtime 择新,写入内容指纹清单,仅在变化时复制;处理 pthread sidecar 与缺失产物对。",
when: "每次内核产物重建后、跑测试或构建 dist 之前。",
usage: [{ cmd: "cd <repo>/web && npm run sync-kernel", note: "等价于 `node tools/sync-assets.mjs`。" }],
inputs: ["`freecad-source/build-web/` 下的探针产物"],
outputs: ["`web/public/kernel/*`", "`web/dist/kernel/*`", "资产清单 JSON"],
env: [],
notes: ["曾因固定从旧目录复制 Fem 探针导致 `memory access out of bounds`;现行实现按 mtime 择新,勿改回固定路径。", "同目录的 `artifact-assets.mjs` 提供原子复制与清单写入。"],
related: ["tool-rebuild-occt-rapidjson", "tool-build-web-module-artifacts"],
}),
/* --- 代码生成 -------------------------------------------------------- */
chapter({
id: "tool-generate-web-module-registry",
title: "generate_web_module_registry.py — 模块路由表生成",
path: "tools/generate_web_module_registry.py",
categoryId: "codegen",
summary: "从 `docs/web-parity-matrix.json` 生成 React/Worker 的模块路由表(`module-registry.generated.ts`、`module-metadata.generated.ts`)。生成产物禁止手改。",
when: "改动 parity matrix、新增/删除工作台模块之后。",
usage: [{ cmd: "cd <repo>/web && npm run sync-module-registry", note: "等价于 `python3 ../tools/generate_web_module_registry.py`。" }],
inputs: ["`docs/web-parity-matrix.json`"],
outputs: ["`web/src/module-registry.generated.ts`", "`web/src/module-metadata.generated.ts`"],
env: [],
notes: ["OpenSCAD 已整体移除;生成结果不得再含 OpenSCAD 行,也不得手改生成文件。"],
related: ["tool-generate-release-manifest", "tool-generate-api-index"],
}),
chapter({
id: "tool-generate-api-index",
title: "generate_python_api_runtime_index.py — Python API 运行时索引",
path: "tools/generate_python_api_runtime_index.py",
categoryId: "codegen",
summary: "为生成的 Python API 分发器生成紧凑运行时索引(带哈希)。同族还有 object/format/viewprovider/property/geometry/document-graph/capability 等索引生成器,用法一致。",
when: "Python API 清单或分发器变化后。",
usage: [{ cmd: "cd <repo>/web && npm run sync-api-index", note: "同族:`sync-object-index`、`sync-format-index`、`sync-viewprovider-index`、`sync-property-index`、`sync-geometry-index`、`sync-document-graph-index`、`sync-capability-index`。" }],
inputs: ["生成的 Python API 清单"],
outputs: ["运行时索引 JSON(含内容哈希)"],
env: [],
notes: ["`npm run build` 会按顺序串起全部索引生成器,手工只需跑单个。"],
related: ["tool-generate-web-module-registry", "tool-generate-release-manifest"],
}),
chapter({
id: "tool-generate-adapter-manifest",
title: "generate_python_family_adapter_manifest.py — 适配层清单生成",
path: "tools/generate_python_family_adapter_manifest.py",
categoryId: "codegen",
summary: "按模块与 tier 生成 Python 家族适配层清单。位置参数 `module`、`tier`,可选 `--output`。PartDesign/Sketcher/TechDraw/Import/Mesh/Material 等都有对应 npm 脚本。",
when: "新增或调整某模块的 Python 适配层之后。",
usage: [
{ cmd: "cd <repo>/web && npm run sync-partdesign-tier2-adapter", note: "PartDesign + tier-2-pure。" },
{ cmd: "cd <repo>/web && python3 ../tools/generate_python_family_adapter_manifest.py Mesh tier-2-pure --output docs/p6/mesh-tier2-adapter-manifest.json", note: "直接调用形式。" },
],
params: [
{ flag: "<module>", note: "模块名,如 PartDesign、Sketcher、Mesh。" },
{ flag: "<tier>", note: "适配层级,如 `tier-2-pure`、`tier-1-readonly`。" },
{ flag: "--output <path>", note: "清单输出路径。" },
],
env: [],
notes: ["其余 tier2 模块用 `npm run sync-tier2-remainder` 一次生成。"],
related: ["tool-generate-api-index", "tool-generate-web-module-registry"],
}),
chapter({
id: "tool-generate-release-manifest",
title: "generate_web_release_manifest.py — 发布清单",
path: "tools/generate_web_release_manifest.py",
categoryId: "codegen",
summary: "为 Web 源码/生成产物/运行时资产生成确定性清单(含哈希),用于发布核对。",
when: "发布前,`npm run build` 的最后一步会自动调用。",
usage: [{ cmd: "cd <repo>/web && npm run sync-release-manifest", note: "等价于 `python3 ../tools/generate_web_release_manifest.py`。" }],
inputs: ["构建后的 web 资产"],
outputs: ["发布清单 JSON"],
env: [],
notes: ["清单是确定性的:相同输入产生相同字节,可作为发布比对基线。"],
related: ["tool-generate-web-module-registry", "tool-sync-assets"],
}),
/* --- 测试与验收 ------------------------------------------------------ */
chapter({
id: "tool-functional-suite",
title: "web-freecad-functional-suite.mjs — 浏览器功能测试套件",
path: "tools/web-freecad-functional-suite.mjs",
categoryId: "test",
summary: "P0–P4 五层有头浏览器功能套件:壳层隔离、手册章节场景、31 个模块、交叉能力(导出/OPFS/回开/错误恢复/布局)、旧手册 53 例。每次运行产出一个带报告的证据目录。",
when: "改动共享壳层、任务面板、导出或 OPFS 之后做回归;提交前跑对应层。",
usage: [
{ cmd: "cd <repo> && DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --only X-panel-scroll --force", note: "单个用例。" },
{ cmd: "cd <repo> && DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --priority P1 --force", note: "整层(P1 = 29 个章节用例)。" },
{ cmd: "cd <repo> && DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --module PartDesign --headless", note: "按模块筛选,无头运行。" },
{ cmd: "cd <repo> && node tools/web-freecad-functional-suite.mjs --resume", note: "断点续跑。" },
],
params: [
{ flag: "--only <ids>", note: "逗号分隔的用例 id,如 `SHELL-01,X-panel-scroll`。" },
{ flag: "--priority <P0,P1,…>", note: "按层选择。" },
{ flag: "--module <name>", note: "按模块筛选 P2 用例。" },
{ flag: "--resume", note: "从上次断点继续。" },
{ flag: "--force", note: "忽略断点,强制重跑。" },
{ flag: "--headless", note: "无头模式。" },
{ flag: "--slow <ms>", note: "每步慢放,便于人工观察。" },
{ flag: "--highlight", note: "高亮操作目标。" },
{ flag: "--screenshots", note: "每步截图。" },
{ flag: "--jobs <n>", note: "并行度。" },
{ flag: "--out <dir>", note: "自定义输出目录。" },
{ flag: "--prune <n>", note: "只保留最近 n 个 run 目录。" },
{ flag: "--legacy-ids", note: "列出旧套件 53 个 id。" },
{ flag: "--timeout-scale <x>", note: "整体超时倍数。" },
],
outputs: ["`docs/current/web-functional-suite/run-<ISO>/`:`report.md`、`junit.xml`、`index.html`、`results.json`、`gaps.ndjson`、`cases/<id>/result.json`、失败截图"],
env: ["DISPLAY", "FREECAD_CHROME", "HEADLESS"],
notes: ["前置顺序:host/端口 → fixture → 文档对象 → 命令状态 → viewport → 产品断言。前置不满足记为 blocked,不记产品回归。", "没有 `--id-prefix` 参数;按前缀筛选用 `--only` 手列。"],
related: ["tool-functional-cli", "tool-functional-runtime", "tool-functional-report"],
}),
chapter({
id: "tool-functional-cli",
title: "functional-suite/cli.mjs — 套件 CLI 与参数解析",
path: "tools/functional-suite/cli.mjs",
categoryId: "test",
summary: "导出 `USAGE` 与 `parseArgs`,是套件唯一声明参数表的地方;新增参数先改这里。",
when: "给套件加/改参数时。",
usage: [{ cmd: "import { USAGE, parseArgs } from \"./functional-suite/cli.mjs\"", note: "库用法;命令行入口是 `tools/web-freecad-functional-suite.mjs`。" }],
env: [],
notes: ["参数解析与帮助文本同源,避免帮助与实现漂移。"],
related: ["tool-functional-suite"],
}),
chapter({
id: "tool-functional-runtime",
title: "functional-suite/runtime.mjs — 浏览器运行层",
path: "tools/functional-suite/runtime.mjs",
categoryId: "test",
summary: "套件的运行层:启动 Chrome、打开入口、用例间 `resetState` 隔离(回 about:blank、清空 OPFS、重进页面)、错误清零与断言辅助。",
when: "新增用例或排查“上个用例污染下个用例”时。",
usage: [{ cmd: "import { … } from \"./functional-suite/runtime.mjs\"", note: "库用法,被 cases/* 使用。" }],
env: ["DISPLAY", "FREECAD_CHROME"],
notes: ["viewport 固定 1440×1000;系统 Chrome 固定 flags:`--no-sandbox --disable-dev-shm-usage --use-angle=swiftshader --enable-unsafe-swiftshader`。", "静态服务用 `tools/static-host.mjs` 的临时端口(带 COOP/COEP),不要占用固定端口。"],
related: ["tool-functional-suite", "tool-static-host"],
}),
chapter({
id: "tool-functional-report",
title: "functional-suite/report.mjs — 报告与断点",
path: "tools/functional-suite/report.mjs",
categoryId: "test",
summary: "输出 `report.md`、`junit.xml`、`index.html`、`results.json`、`checkpoint.json`,并实现 run 目录创建与 `--prune` 清理。",
when: "接入 CI 或调整证据格式时。",
usage: [{ cmd: "import { newRunDir, persist, finalize, pruneRuns } from \"./functional-suite/report.mjs\"", note: "库用法。" }],
outputs: ["`docs/current/web-functional-suite/run-<ISO>/`"],
env: [],
notes: ["`index.html` 是极简浅色页,仅供跳转;不要与手册页的深色风格混用。"],
related: ["tool-functional-suite"],
}),
chapter({
id: "tool-functional-cases",
title: "functional-suite/cases/index.mjs — 用例注册表",
path: "tools/functional-suite/cases/index.mjs",
categoryId: "test",
summary: "汇总 shell / chapters / handwritten / modules / crosscut 五个用例模块,输出完整用例清单。",
when: "新增用例文件或调整用例排序时。",
usage: [{ cmd: "import { … } from \"./functional-suite/cases/index.mjs\"", note: "库用法。" }],
env: [],
notes: ["P1 章节用例由 `web/manual/scenarios/*.json` 驱动,新增章节先加场景 JSON。", "`X-panel-scroll` 在 `cases/crosscut.mjs`。"],
related: ["tool-functional-suite", "tool-manual-capture"],
}),
chapter({
id: "tool-full-parity-gate",
title: "run_full_parity_gate.py — 全量一致性门禁",
path: "tools/run_full_parity_gate.py",
categoryId: "test",
summary: "聚合 source-backed 的 P6 门禁,只校验覆盖度与一致性,不把 boundary 升级成 parity;详细对象/格式/Python/工作台/视图/文档/质量产物仍是权威。",
when: "发布前或大范围改动后做总门禁。",
usage: [{ cmd: "cd <repo>/web && npm run full-parity:gate", note: "等价于 `python3 ../tools/run_full_parity_gate.py`。" }],
inputs: ["各分项门禁产物"],
outputs: ["汇总结果;非零退出表示不达标"],
env: [],
notes: ["失败时先看它指向的分项产物,不要直接改本脚本。"],
related: ["tool-format-coverage-gate"],
}),
chapter({
id: "tool-format-coverage-gate",
title: "run_p6_format_coverage_gate.mjs — 格式覆盖门禁",
path: "tools/run_p6_format_coverage_gate.mjs",
categoryId: "test",
summary: "以记录级处置关闭格式卡:同一扩展名的两个源码处理器刻意保持为不同 inventory 行。",
when: "调整导入/导出格式支持后。",
usage: [{ cmd: "cd <repo>/web && npm run format:coverage", note: "等价于 `node ../tools/run_p6_format_coverage_gate.mjs`。" }],
env: [],
notes: ["扩展名白名单在 `web/src/export-service.ts` 的 `EXTENSIONS`,新增格式要同时改白名单与门禁数据。"],
related: ["tool-full-parity-gate"],
}),
chapter({
id: "tool-auto-resume-official-case",
title: "auto-resume-official-case.mjs — 官方用例自动续跑",
path: "tools/auto-resume-official-case.mjs",
categoryId: "test",
summary: "读取官方用例账本,挑选下一个可执行的叶子用例续跑;`--json` 输出机器可读结果。",
when: "无人值守推进官方用例时;也作为 `check:official-continuation` 的第一步。",
usage: [{ cmd: "cd <repo>/web && npm run check:official-continuation", note: "先跑本脚本 `--json`,再跑 `check-official-case-continuation.mjs --json`。" }],
env: [],
notes: ["恢复点以账本 `currentCase`/`resumeCase` 为准,不要自行猜测下一个用例。"],
related: ["tool-check-official-continuation"],
}),
chapter({
id: "tool-check-official-continuation",
title: "check-official-case-continuation.mjs — 续跑一致性检查",
path: "tools/check-official-case-continuation.mjs",
categoryId: "test",
summary: "校验官方用例的续跑状态与账本是否一致,`--json` 输出结果。",
when: "每个阶段开始与断流恢复时。",
usage: [{ cmd: "cd <repo> && node tools/check-official-case-continuation.mjs --json", note: "只读检查。" }],
env: [],
notes: ["发现不一致时先修账本/证据,再继续跑用例。"],
related: ["tool-auto-resume-official-case"],
}),
/* --- 浏览器与界面 ---------------------------------------------------- */
chapter({
id: "tool-static-host",
title: "static-host.mjs — 静态服务与 Chrome 发现",
path: "tools/static-host.mjs",
categoryId: "runtime",
summary: "共享静态服务模块,也可直接当 CLI 用。服务构建好的 dist,带 COOP/COEP 隔离头,默认监听临时端口。另导出 `findChrome()` 与 `ISOLATION_HEADERS`。",
when: "任何需要给浏览器提供 web/dist 的脚本或人工核对。",
usage: [
{ cmd: "cd <repo> && node tools/static-host.mjs --root web/dist", note: "打印 `ORIGIN=…` 后常驻,Ctrl-C 退出。" },
{ cmd: "cd <repo> && node tools/static-host.mjs --root web/dist --port 5199 --document workbench.html", note: "固定端口与默认文档。" },
{ cmd: "import { startStaticHost } from \"./tools/static-host.mjs\"; const { origin, close } = await startStaticHost(distRoot);", note: "模块用法:返回 `{ server, origin, root, close }`。" },
],
params: [
{ flag: "--root <dir>", note: "dist 目录,支持相对路径(内部 `path.resolve`)。" },
{ flag: "--port <n>", note: "端口,默认 0(临时端口)。" },
{ flag: "--document <file>", note: "默认文档,默认 `index.html`。" },
],
env: ["FREECAD_CHROME"],
notes: ["`--root` 曾是相对路径陷阱:不 resolve 会让路径守卫对所有请求返回 403;现已修复。", "MIME 表必须显式列出 `.svg` 等类型,否则 Chrome 不渲染图标。", "GLB/GLTF 等二进制以 `application/octet-stream` 提供。"],
related: ["tool-layout-probe", "tool-functional-runtime"],
}),
chapter({
id: "tool-layout-probe",
title: "layout-probe.mjs — 三栏布局与面板滚动探针",
path: "tools/layout-probe.mjs",
categoryId: "browser",
summary: "逐页断言:锁定页整页不可滚动、左右面板都在视口内、每个面板拥有真正可滚动的 `.pane-scroll`、注入内容与滚动画布两侧面板后中央舞台位移 ≤1px。",
when: "改动壳层布局、任务面板、面板 CSS 之后;也可用于人工核对。",
usage: [
{ cmd: "cd <repo> && node tools/layout-probe.mjs", note: "默认 5 页:project、partdesign、Part、Robot、Mesh。" },
{ cmd: "cd <repo> && node tools/layout-probe.mjs --url /partdesign.html --json /tmp/layout.json", note: "单页 + 完整报告。" },
{ cmd: "cd <repo> && node tools/layout-probe.mjs --headed --pause", note: "有头打开并停住,人工拖左右面板滚动条。" },
{ cmd: "cd <repo> && node tools/layout-probe.mjs --origin http://127.0.0.1:PORT", note: "复用已启动的 host。" },
],
params: [
{ flag: "--url <path>", note: "可重复;默认 5 个代表页。" },
{ flag: "--root <dir>", note: "dist 根,默认 `<repo>/web/dist`。" },
{ flag: "--origin <url>", note: "复用已有 host。" },
{ flag: "--wait-for <sel>", note: "就绪选择器,默认 `.layout, .design-layout, .pane-scroll`。" },
{ flag: "--wait-ms <n>", note: "就绪后等待,默认 1500。" },
{ flag: "--viewport <WxH>", note: "默认 1440x1000。" },
{ flag: "--headed / --slow <ms> / --pause", note: "人工观察。" },
{ flag: "--inject <px>", note: "占位块高度,默认 2000;0 关闭。" },
{ flag: "--scroll-test <px>", note: "面板滚动距离,默认 400。" },
{ flag: "--screenshot <path>", note: "每页截图,`{page}` 替换为页名。" },
{ flag: "--json <path>", note: "完整报告输出。" },
{ flag: "--no-assert", note: "永远退出 0。" },
],
outputs: ["每页一行摘要;`--json` 时为完整报告"],
env: ["DISPLAY", "FREECAD_CHROME"],
notes: ["退出码:0 通过,1 有失败,2 前置缺失(无 Chrome 或无 dist)。", "窄屏(<721px)页面本就不锁定,探针会标记 skip/失败,属预期回退。"],
related: ["tool-static-host", "tool-functional-suite"],
}),
chapter({
id: "tool-mcp-browser-session",
title: "mcp/browser-session.mjs — MCP 浏览器会话",
path: "tools/mcp/browser-session.mjs",
categoryId: "browser",
summary: "MCP 服务的浏览器通道:静态 host + Chromium + `mcp.html` 桥接;导出 `McpBrowserSession` 与 `PrerequisiteError`。",
when: "通过 MCP 让外部代理驱动 Web FreeCAD 时。",
usage: [{ cmd: "import { McpBrowserSession, PrerequisiteError, distRoot } from \"./tools/mcp/browser-session.mjs\"", note: "库用法;会话由 MCP 服务创建。" }],
env: ["HEADLESS", "FREECAD_CHROME", "FREECAD_MCP_READY_TIMEOUT_MS", "FREECAD_MCP_CALL_TIMEOUT_MS"],
notes: ["`HEADLESS=0` 切有头。", "就绪/调用超时默认 300000 ms;长构建场景再调大。"],
related: ["tool-static-host", "tool-fcweb-capture"],
}),
chapter({
id: "tool-fcweb-capture",
title: "fcweb/capture.mjs — 浏览器封装与页面检查",
path: "tools/fcweb/capture.mjs",
categoryId: "browser",
summary: "复用型浏览器工具:`launchBrowser`、`openPage`、`screenshot`、`pageCheck`、`writeArtifact`。`pageCheck` 一次断言 HTTP 200、0 pageerror/console error、0 失败请求、0 坏图、0 横向溢出与锚点存在。",
when: "写新的页面检查脚本时优先复用,不要另起 Playwright 封装。",
usage: [
{ cmd: "import { launchBrowser, openPage, pageCheck } from \"./tools/fcweb/capture.mjs\"", note: "库用法。" },
{ cmd: "await pageCheck(browser, url, { viewports: [{ width: 1440, height: 900 }], expect: { anchorIds: [\"overview\"] } })", note: "最小调用示例。" },
],
env: ["DISPLAY", "FREECAD_CHROME"],
notes: ["`--headed` 由调用方传入;默认无头。"],
related: ["tool-tools-manual-check", "tool-ui-capture"],
}),
chapter({
id: "tool-fcweb-ui-capture",
title: "fcweb/ui-capture.mjs — 工作台截图",
path: "tools/fcweb/ui-capture.mjs",
categoryId: "browser",
summary: "为每个工作台抓一张运行中界面截图;截图清单由 inventory 决定,复用 `capture.mjs` 的浏览器启动与截图能力。",
when: "更新界面文档配图时。",
usage: [{ cmd: "cd <repo> && node tools/fcweb/ui-capture.mjs", note: "输出到 `tools/fcweb/out/ui-shots/`,供 `build-ui-doc.mjs` 使用。" }],
outputs: ["`tools/fcweb/out/ui-shots/*.png`"],
env: ["DISPLAY"],
notes: ["必须先构建 dist 并同步 kernel 资产。"],
related: ["tool-fcweb-ui-inventory", "tool-build-ui-doc"],
}),
chapter({
id: "tool-fcweb-ui-inventory",
title: "fcweb/ui-inventory.mjs — 界面清单采集",
path: "tools/fcweb/ui-inventory.mjs",
categoryId: "browser",
summary: "采集工作台、面板、命令等界面结构,输出 `out/ui-inventory.json`,是界面文档与审计的数据源。",
when: "界面结构变化后重建文档前。",
usage: [{ cmd: "cd <repo> && node tools/fcweb/ui-inventory.mjs", note: "输出 `tools/fcweb/out/ui-inventory.json`。" }],
outputs: ["`tools/fcweb/out/ui-inventory.json`"],
env: ["DISPLAY"],
notes: ["采集结果是后续 `build-ui-doc.mjs` 的唯一输入,不要手改 JSON。"],
related: ["tool-fcweb-ui-capture", "tool-build-ui-doc"],
}),
chapter({
id: "tool-ui-surface-audit",
title: "ui-workbench-surface-audit.mjs — 工作台界面审计",
path: "tools/ui-workbench-surface-audit.mjs",
categoryId: "audit",
summary: "逐个工作台抓取模块名并审计界面表面(菜单/工具栏/坞/状态栏),记录数 = 模块数 × viewport 数,不是常数。",
when: "壳层或工作台布局改动后。",
usage: [{ cmd: "cd <repo> && DISPLAY=:1 node tools/ui-workbench-surface-audit.mjs", note: "需要已构建的 dist 与可用的 Chrome。" }],
env: ["DISPLAY", "HEADLESS", "FREECAD_CHROME"],
notes: ["覆盖规则由 `tools/audit64.mjs` 提供,两者配合使用。"],
related: ["tool-audit64"],
}),
/* --- 审计与上下文 ---------------------------------------------------- */
chapter({
id: "tool-audit64",
title: "audit64.mjs — 界面覆盖规则共享模块",
path: "tools/audit64.mjs",
categoryId: "audit",
summary: "工作台界面审计覆盖规则的共享 owner:记录数 = 模块数 × viewport 数,由 `ui-workbench-surface-audit.mjs` 提供模块名。被 60+ 脚本导入。",
when: "修改审计覆盖口径时(只改这一处)。",
usage: [{ cmd: "import { … } from \"./tools/audit64.mjs\"", note: "库用法。" }],
env: [],
notes: ["行数不是常量,不要写死 64。"],
related: ["tool-ui-surface-audit"],
}),
chapter({
id: "tool-parity-extract",
title: "parity/extract-desktop-gui.mjs — 桌面 GUI 元数据提取",
path: "tools/parity/extract-desktop-gui.mjs",
categoryId: "audit",
summary: "从桌面 FreeCAD 提取工作台菜单/工具栏/坞/命令元数据,并与 Web 命令矩阵连接。输出 `web/public/api/desktop-gui-manifest.json` 与 `web/docs/current/desktop-parity-matrix.json`。",
when: "需要刷新桌面基线时(要求本机可运行桌面 FreeCAD)。",
usage: [{ cmd: "cd <repo> && node tools/parity/extract-desktop-gui.mjs", note: "桌面侧提取,生成两份 JSON。" }],
outputs: ["`web/public/api/desktop-gui-manifest.json`", "`web/docs/current/desktop-parity-matrix.json`"],
env: [],
notes: ["产物是其他 parity 脚本的基线;更新后要重跑相关审计。"],
related: ["tool-parity-audit", "tool-parity-mount-inventory"],
}),
chapter({
id: "tool-parity-audit",
title: "parity/audit-web-gui.mjs — 单工作台 GUI 审计",
path: "tools/parity/audit-web-gui.mjs",
categoryId: "audit",
summary: "对单个工作台做 Web GUI 基线审计:菜单/工具栏/坞/状态栏、pageerror 与溢出,并与 `desktop-gui-manifest.json` 对比。",
when: "某工作台界面改动后。",
usage: [{ cmd: "cd <repo> && DISPLAY=:1 node tools/parity/audit-web-gui.mjs <workbench>", note: "工作台名作为位置参数。" }],
env: ["DISPLAY", "FREECAD_CHROME"],
notes: ["依赖桌面清单存在;缺失时先跑 `extract-desktop-gui.mjs`。"],
related: ["tool-parity-extract", "tool-parity-mount-inventory"],
}),
chapter({
id: "tool-parity-mount-inventory",
title: "parity/build-ui-mount-inventory.mjs — 挂载清单",
path: "tools/parity/build-ui-mount-inventory.mjs",
categoryId: "audit",
summary: "把桌面 GUI 清单、Web 命令路由、命令矩阵与已发布壳层的挂载状态连接起来,回答“桌面有 X / Web 实现了什么”。",
when: "生成或刷新 parity 报告前。",
usage: [{ cmd: "cd <repo> && node tools/parity/build-ui-mount-inventory.mjs", note: "输出挂载清单 JSON。" }],
env: [],
notes: ["三个输入必须同批刷新,否则结论会互相矛盾。"],
related: ["tool-parity-extract", "tool-parity-audit"],
}),
chapter({
id: "tool-validate-web-context",
title: "validate_web_context.py — 上下文一致性校验",
path: "tools/validate_web_context.py",
categoryId: "audit",
summary: "校验有界任务上下文与跨文档状态是否一致(continuation、账本、政策文件之间)。",
when: "交接前后、发现文档状态互相矛盾时。",
usage: [{ cmd: "cd <repo> && python3 tools/validate_web_context.py", note: "只读校验,非零退出表示不一致。" }],
env: [],
notes: ["与 `prepare_web_task_context.py` 配对:一个准备上下文,一个校验。"],
related: ["tool-prepare-web-context"],
}),
chapter({
id: "tool-prepare-web-context",
title: "prepare_web_task_context.py — 任务上下文准备",
path: "tools/prepare_web_task_context.py",
categoryId: "audit",
summary: "按任务卡 id 准备有界上下文清单;`task_id` 位置参数缺省为 `active_task`,`--output` 指定清单路径。",
when: "开始一个新任务卡前。",
usage: [{ cmd: "cd <repo> && python3 tools/prepare_web_task_context.py <task_id> --output /tmp/context.json", note: "输出上下文清单。" }],
params: [
{ flag: "<task_id>", note: "可省略,默认 `active_task`。" },
{ flag: "--output <path>", note: "清单输出路径。" },
],
env: [],
notes: ["清单只收录有界窗口,避免把整个仓库读进上下文。"],
related: ["tool-validate-web-context"],
}),
chapter({
id: "tool-check-link-closure",
title: "check_web_link_closure.py — 链接闭合检查",
path: "tools/check_web_link_closure.py",
categoryId: "audit",
summary: "检查构建产物里的链接是否闭合:位置参数 `build_dir` 与 `target`,`--json` 输出机器可读结果。",
when: "发布前、批量改路由或文档后。",
usage: [{ cmd: "cd <repo> && python3 tools/check_web_link_closure.py web/dist index.html --json", note: "检查 dist 的入口链接闭合。" }],
params: [
{ flag: "<build_dir>", note: "构建目录。" },
{ flag: "<target>", note: "入口文件。" },
{ flag: "--json", note: "JSON 输出。" },
],
env: [],
notes: ["必须在构建完成后运行。"],
related: ["tool-build-and-publish"],
}),
/* --- 文档生成 -------------------------------------------------------- */
chapter({
id: "tool-build-manual",
title: "manual/build-manual.mjs — 应用手册构建",
path: "web/tools/manual/build-manual.mjs",
categoryId: "docs",
summary: "把 `web/manual/content/*.md`(带 front matter 的章节)与 `web/manual/data/manual-features.json` 渲染成自包含 HTML:`web/teaching/manual.html` + `manual-assets/`。",
when: "修改手册章节或功能清单后。",
usage: [{ cmd: "cd <repo>/web && npm run build:manual", note: "输出 `web/teaching/manual.html`。" }],
inputs: ["`web/manual/content/*.md`", "`web/manual/data/manual-features.json`", "`web/tools/manual/template.html`"],
outputs: ["`web/teaching/manual.html`", "`web/teaching/manual-assets/`"],
env: [],
notes: ["模板里已有搜索、侧栏 TOC、进度勾选、图片灯箱、打印样式;新文档应复用同一套 CSS 令牌。", "同族构建器:`build-parts-manual.mjs`、`build-reducer-manual.mjs`、`build-fcweb-toolkit.mjs`。"],
related: ["tool-manual-features", "tool-manual-capture", "tool-manual-check"],
}),
chapter({
id: "tool-manual-features",
title: "manual/generate-features.mjs — 手册功能清单生成",
path: "web/tools/manual/generate-features.mjs",
categoryId: "docs",
summary: "生成手册用的功能/清单 JSON:`manual-features.json`、`inventory-snapshot.json`(路径+sha256)、`coverage-audit.json`。",
when: "手册构建的第一步;界面或文档输入变化后。",
usage: [{ cmd: "cd <repo>/web && npm run manual:features", note: "刷新三份 JSON。" }],
outputs: ["`web/manual/data/manual-features.json`", "`web/manual/data/inventory-snapshot.json`", "`web/manual/data/coverage-audit.json`"],
env: [],
notes: ["顺序:本脚本 → `capture.mjs` 截图 → `build-manual.mjs` → `check-page.mjs`。"],
related: ["tool-build-manual", "tool-manual-capture"],
}),
chapter({
id: "tool-manual-capture",
title: "manual/capture.mjs — 手册场景执行与截图",
path: "web/tools/manual/capture.mjs",
categoryId: "docs",
summary: "在真实应用里执行手册场景 JSON(18 种动作),断言界面状态并截图。与功能套件的章节用例共用 `lib/actions.mjs` 动作解释器。",
when: "手册章节或界面变化后重拍截图。",
usage: [
{ cmd: "cd <repo>/web && DISPLAY=:1 node tools/manual/capture.mjs --scenario manual/scenarios/ch01-ui.json --origin <ORIGIN>", note: "指定已启动的 host。" },
{ cmd: "cd <repo>/web && DISPLAY=:1 node tools/manual/capture.mjs --scenario manual/scenarios/ch01-ui.json --headed", note: "有头观察。" },
],
params: [
{ flag: "--scenario <json>", note: "场景文件路径。" },
{ flag: "--origin <url>", note: "静态服务地址,默认 `http://127.0.0.1:5181`。" },
{ flag: "--headed", note: "有头模式。" },
],
outputs: ["场景截图(`shots` 计数见 stdout JSON)"],
env: ["DISPLAY"],
notes: ["`--origin` 可用 `node tools/static-host.mjs --root web/dist` 输出的地址。", "ch01 场景是冒烟基线:应输出 `{\"ok\":true,…,\"shots\":7}`。"],
related: ["tool-static-host", "tool-manual-check", "tool-build-manual"],
}),
chapter({
id: "tool-manual-check",
title: "manual/check-page.mjs — 手册页面检查",
path: "web/tools/manual/check-page.mjs",
categoryId: "docs",
summary: "用 Playwright 在 1440×900 与 390×844 下检查手册页面:0 pageerror、0 坏图、0 横向溢出、章节与锚点数量、搜索命中。",
when: "构建手册之后。",
usage: [{ cmd: "cd <repo>/web && npm run check:manual", note: "检查 `web/teaching/manual.html`。" }],
env: ["DISPLAY", "MANUAL_URL"],
notes: ["同族:`check-parts-manual.mjs`、`check-reducer-manual.mjs`、`check-fcweb-toolkit.mjs`、`check-ui-design-doc.mjs`。"],
related: ["tool-build-manual", "tool-tools-manual-check"],
}),
chapter({
id: "tool-build-ui-doc",
title: "fcweb/build-ui-doc.mjs — 界面文档生成",
path: "tools/fcweb/build-ui-doc.mjs",
categoryId: "docs",
summary: "把 `out/ui-inventory.json` 与手写章节 `docs/current/ui-design/source.html` 渲染成 `docs/current/web-freecad-ui-layout-and-functions.html`。支持 `--seed` 与 `--check`(字节级幂等)。",
when: "界面结构变化、需要刷新界面文档时。",
usage: [
{ cmd: "cd <repo> && node tools/fcweb/build-ui-doc.mjs", note: "生成界面文档。" },
{ cmd: "cd <repo> && node tools/fcweb/build-ui-doc.mjs --check", note: "只校验是否最新,过期则 exit 1。" },
],
params: [
{ flag: "--seed", note: "用清单初始化手写模板骨架。" },
{ flag: "--check", note: "幂等检查。" },
],
inputs: ["`tools/fcweb/out/ui-inventory.json`", "`docs/current/ui-design/source.html`"],
outputs: ["`docs/current/web-freecad-ui-layout-and-functions.html`", "`docs/current/web-freecad-ui-assets/`"],
env: ["DISPLAY"],
notes: ["合并后会从最终 `<h2 id>` 重新生成 TOC;手写 prose 只改 `source.html`。"],
related: ["tool-fcweb-ui-inventory", "tool-fcweb-ui-capture"],
}),
/* --- 调度与性能 ------------------------------------------------------ */
chapter({
id: "tool-scheduler",
title: "run_freecad_web_scheduler.py — 无人值守调度器",
path: "tools/run_freecad_web_scheduler.py",
categoryId: "scheduler",
summary: "无人值守循环:按账本挑下一个任务、交给 Codex 轮次执行,直到收到 TERMINATE。",
when: "长时间无人值守推进时(需用户明确授权)。",
usage: [{ cmd: "cd <repo> && python3 tools/run_freecad_web_scheduler.py --max-cycles 5 --log-dir /tmp/fcweb-logs", note: "先小步试跑。" }],
params: [
{ flag: "--max-cycles <n>", note: "跑 N 轮后停止;0 表示直到 TERMINATE。" },
{ flag: "--idle-delay <s>", note: "无任务时的重试间隔,默认 30。" },
{ flag: "--timeout <s>", note: "单轮上限,默认 1800。" },
{ flag: "--stream-retry-delay <s>", note: "流断开后的退避,默认 20。" },
{ flag: "--model <name>", note: "可选模型覆盖。" },
{ flag: "--log-dir <dir>", note: "日志目录。" },
],
outputs: ["`<log-dir>` 下的轮次日志"],
env: [],
notes: ["启动/断流恢复前先跑 `npm run check:official-continuation`。", "`tools/scheduler-bin/` 提供 git/python/rg 的 PATH 垫片。"],
related: ["tool-scheduler-context", "tool-analyze-scheduler"],
}),
chapter({
id: "tool-scheduler-context",
title: "scheduler_context.py — 调度上下文",
path: "tools/scheduler_context.py",
categoryId: "scheduler",
summary: "为无人值守轮次提供有界、结构化的上下文与源码标识(哈希)。",
when: "调度器内部使用;排查上下文来源时阅读。",
usage: [{ cmd: "import scheduler_context", note: "Python 库用法,无独立 CLI。" }],
env: [],
notes: ["不做全仓库扫描,只读取登记过的文件。"],
related: ["tool-scheduler"],
}),
chapter({
id: "tool-analyze-scheduler",
title: "analyze_scheduler_timings.py — 调度计时分析",
path: "tools/analyze_scheduler_timings.py",
categoryId: "scheduler",
summary: "汇总调度轮次耗时,输出统计与可选的 JSON/Markdown 报告。",
when: "排查“任务变慢/超时”时。",
usage: [{ cmd: "cd <repo> && python3 tools/analyze_scheduler_timings.py --cycles 20 --json", note: "读滚动缓存。" }],
params: [
{ flag: "--cycles <n>", note: "统计轮数,默认 20。" },
{ flag: "--log-dir <dir>", note: "日志目录。" },
{ flag: "--json", note: "JSON 输出。" },
{ flag: "--from-logs", note: "读有界原始轮次日志,而非滚动缓存。" },
{ flag: "--report-prefix <path>", note: "写详细 JSON 与 Markdown 报告。" },
],
env: [],
notes: ["先用 `--from-logs` 核对原始日志,再信缓存统计。"],
related: ["tool-scheduler"],
}),
/* --- 本手册自身 ------------------------------------------------------ */
chapter({
id: "tool-tools-manual",
title: "build-tools-manual.mjs — 本手册生成器",
path: "tools/build-tools-manual.mjs",
categoryId: "docs",
summary: "扫描 `tools/` 与 `web/tools/`,静态提取用途/用法/环境变量,合并 40 个手写章节,生成自包含的 `docs/current/tools-manual/index.html`。不执行任何工具。",
when: "新增/重命名工具,或改了手写章节之后。",
usage: [
{ cmd: "cd <repo> && node tools/build-tools-manual.mjs", note: "重新生成手册。" },
{ cmd: "cd <repo> && node tools/build-tools-manual.mjs --check", note: "只校验是否最新。" },
{ cmd: "cd <repo> && node tools/build-tools-manual.mjs --stats", note: "打印扫描/分类/族统计。" },
{ cmd: "cd <repo> && node tools/build-tools-manual.mjs --verify", note: "路径/锚点/自包含/体积断言。" },
],
params: [
{ flag: "--check", note: "字节级幂等检查,过期 exit 1。" },
{ flag: "--verify", note: "静态完整性断言。" },
{ flag: "--stats", note: "打印统计后退出。" },
{ flag: "--root <dir>", note: "仓库根,默认脚本上两级。" },
{ flag: "--out <path>", note: "输出路径,默认 `docs/current/tools-manual/index.html`。" },
],
outputs: ["`docs/current/tools-manual/index.html`"],
env: [],
notes: ["模块拆分在 `tools/tools-manual/`:config/scan/extract/chapters/render/verify。"],
related: ["tool-tools-manual-check"],
}),
chapter({
id: "tool-tools-manual-check",
title: "check-tools-manual.mjs — 本手册页面检查",
path: "tools/check-tools-manual.mjs",
categoryId: "docs",
summary: "用 Playwright 在桌面与移动视口检查手册页面:0 pageerror、无横向溢出、锚点可跳转、搜索与过滤可用。",
when: "生成手册之后。",
usage: [{ cmd: "cd <repo>/web && DISPLAY=:1 node ../tools/check-tools-manual.mjs", note: "或 `npm run check:tools-manual`。" }],
env: ["DISPLAY", "FREECAD_CHROME"],
notes: ["复用 `tools/fcweb/capture.mjs` 的 `pageCheck`。"],
related: ["tool-tools-manual"],
}),
];
/** The environment contract chapter, rendered before the tool chapters. */
export const CONTRACT_CHAPTERS = [
{
id: "contract-paths",
title: "路径与工作目录",
body: [
"工作区根目录是 `/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD`,含空格:shell 里一律引用绝对路径并整体加双引号,例如 `cd \"/media/mes123456/Elements SE/.../FreeCAD\" && …`。",
"前端相关命令大多要求工作目录 `<repo>/web`(`npm run …`),仓库级脚本要求 `<repo>`。本手册的命令都标明了 `cd` 到哪。",
"脚本自身用 `import.meta.url` / `Path(__file__)` 解析仓库根,因此从别处调用也能找到文件,但 npm 脚本仍按 `web/` 约定编写。",
],
},
{
id: "contract-wasm",
title: "WASM 编译环境(绝对路径)",
body: [
"所有 WASM 编译必须使用项目预置环境,不允许改用系统 Emscripten 或用户级 cache:",
"`EM_CONFIG=<repo>/freecad-source/build-web/emscripten-config.py`",
"`EM_CACHE=<repo>/freecad-source/build-web/emscripten-cache`(bzip2 已编译在内,不得重编)",
"构建目录:`<repo>/freecad-source/build-web/configure`",
"模板:`export EM_CONFIG=… EM_CACHE=…` 后 `cmake --build \"<build dir>\" --target <Target> -j 8`。判定成功看日志里的 `error:` 与退出码,不要用 `| tail` 的返回码。",
],
},
{
id: "contract-browser",
title: "浏览器与显示",
body: [
"浏览器套件用系统 Chrome(`/usr/bin/google-chrome`),`FREECAD_CHROME` 可覆盖;无头为默认,`HEADLESS=0` 切有头。",
"有头运行与截图需要 `DISPLAY=:1`(本机 X 显示)。",
"静态服务一律用 `tools/static-host.mjs` 的临时端口(带 COOP/COEP);5180 可能挂着旧 dev server,勿用它做验证。",
],
},
{
id: "contract-opfs",
title: "OPFS 目录契约",
body: [
"文档与导出只落 OPFS,只有用户点“下载到本地”才触发浏览器下载;任何自动下载都算缺口。",
"FCStd 文档在 `freecad-documents`;几何导出在 `freecad-exports`;参数在 `freecad-parameters`。用例必须按目录分别轮询/回读,禁止跨目录假设。",
"Node 侧教学脚本用 `opfs-store.mjs` 镜像同名目录 `out/opfs/freecad-exports`,按裸文件名寻址。",
],
},
];

View File

@@ -0,0 +1,165 @@
/**
* Static configuration for tools/build-tools-manual.mjs.
*
* Categories are ordered: the first rule whose `test` returns true wins, so
* path-based rules (docs pipeline, compat shims, data) must sit above the
* filename-based ones.
*/
export const REPO_ROOT = new URL("../../", import.meta.url).pathname;
export const SCAN_ROOTS = [
{ relPath: "tools", recursive: true },
{ relPath: "web/tools", recursive: false },
{ relPath: "web/tools/manual", recursive: true },
];
/** Directory names skipped anywhere in the walk. */
export const SKIP_DIRS = new Set(["__pycache__", "node_modules", ".git", "out", "dist", "assets"]);
/** Files skipped by basename pattern. */
export const SKIP_FILE = /(\.pyc$|\.bak$|\.inc\.mjs$|^batch-.*\.json$|\.lock$|^\.)/;
/** Extensions that are read for purpose/usage/env extraction. */
export const READ_EXTS = new Set([".mjs", ".js", ".ts", ".tsx", ".py", ".sh", ".ps1", ".json", ".cmake"]);
/** How many bytes of each file are read. */
export const HEAD_BYTES = 16 * 1024;
/**
* Summary-only directories: one inventory row per directory instead of one per
* file, because they are generated tables/fixtures with no individual CLI.
*/
export const DIRECTORY_SUMMARIES = [
{ relPath: "tools/generated-contracts", label: "生成契约表", category: "data", note: "由生成器产出的模块/路由契约表,供运行时与校验脚本读取,不直接执行。" },
{ relPath: "tools/fixtures", label: "测试夹具", category: "data", note: "IFC 等二进制/文本夹具,被验收脚本读取。" },
{ relPath: "tools/scheduler-bin", label: "调度 PATH 垫片", category: "compat", note: "git/python/rg 的 PATH 垫片,由调度器注入。" },
{ relPath: "tools/emcc-compat-bin", label: "emcc 兼容垫片", category: "compat", note: "emcc/em++ 包装脚本,转发到系统 emcc;每次调用会追加日志。" },
{ relPath: "tools/emscripten-compat", label: "Emscripten 启动钩子", category: "compat", note: "sitecustomize.py,在 Python 解释器启动时自动导入。" },
{ relPath: "web/tools/carrier-course", label: "内容工程:carrier", category: "docs", note: "课程媒体生成脚本与素材。" },
{ relPath: "web/tools/abb120-course", label: "内容工程:abb120", category: "docs", note: "课程媒体生成脚本与素材。" },
{ relPath: "web/tools/delta-course", label: "内容工程:delta", category: "docs", note: "课程媒体生成脚本与素材。" },
{ relPath: "web/tools/line-course", label: "内容工程:生产线", category: "docs", note: "生产线课程媒体生成脚本与素材。" },
{ relPath: "web/tools/reducer-course", label: "内容工程:减速器", category: "docs", note: "减速器课程媒体生成脚本与素材。" },
{ relPath: "web/tools/reducer-parts-course", label: "内容工程:减速器零件", category: "docs", note: "减速器零件课程媒体生成脚本与素材。" },
{ relPath: "web/tools/line-manual", label: "内容工程:生产线手册", category: "docs", note: "生产线手册构建脚本与素材。" },
{ relPath: "web/tools/bim-workshop-video", label: "内容工程:BIM 工作坊视频", category: "docs", note: "BIM 工作坊录屏与合成脚本。" },
{ relPath: "web/tools/carrier-video", label: "内容工程:carrier 视频", category: "docs", note: "carrier 视频合成脚本。" },
{ relPath: "web/tools/cad-ui-rebuild", label: "内容工程:CAD UI 重建", category: "docs", note: "CAD 界面重建截图脚本。" },
{ relPath: "web/tools/reducer-ui-rebuild", label: "内容工程:减速器 UI 重建", category: "docs", note: "减速器界面重建截图脚本。" },
];
/** Ordered category rules. */
export const CATEGORIES = [
{
id: "docs",
label: "文档生成与页面检查",
hint: "手册、界面文档、截图与页面校验",
test: (p, n) => p.startsWith("web/tools/manual/") || p.startsWith("web/tools/line-manual/")
|| /^(build-ui-doc|build-fcweb-toolkit|build-manual|build-parts-manual|build-reducer-manual|generate-gaps-doc|generate-panel-index|generate-features|generate-final-status|check-page|check-ui-design-doc|check-fcweb-toolkit|check-parts-manual|check-reducer-manual)\.mjs$/.test(n),
},
{
id: "compat",
label: "兼容垫片与外部工具",
hint: "emcc、Emscripten、调度 PATH 垫片",
test: (p) => p.startsWith("tools/emcc-compat-bin/") || p.startsWith("tools/emscripten-compat/") || p.startsWith("tools/scheduler-bin/"),
},
{
id: "data",
label: "数据、契约与夹具",
hint: "JSON、生成契约表、二进制夹具",
test: (p, n) => p.endsWith(".json") || p.startsWith("tools/generated-contracts/") || p.startsWith("tools/fixtures/"),
},
{
id: "runtime",
label: "静态宿主与运行环境",
hint: "静态服务、Chrome 发现",
test: (p, n) => /^(static-host|artifact-assets|wasm-probe-runtime)\.mjs$/.test(n),
},
{
id: "cases",
label: "用例与业务场景表",
hint: "可被 smoke/gate 导入的场景数据",
test: (p, n) => /-business-cases/.test(n),
},
{
id: "browser",
label: "浏览器自动化与界面探测",
hint: "Playwright 驱动、UI 一致性、截图、布局探针",
test: (p, n) => /^ui-/.test(n) || /^(capture|ui-capture|ui-inventory|browser-session|page-check|case-replay|probe-run-case|diagnose-bridge|mcp)/.test(n)
|| /probe|-probe|replay-|layout-probe|audit-web-gui|ui-parity-preflight|ui-workbench-surface-audit/.test(n),
},
{
id: "test",
label: "测试与验收",
hint: "冒烟、门禁、功能套件、官方用例续跑",
test: (p, n) => p.startsWith("tools/functional-suite/") || /^run[_-]/.test(n) || /smoke|gate|worker|parity|official-case|functional-suite/.test(n),
},
{
id: "codegen",
label: "同步与代码生成",
hint: "生成注册表、运行时索引、清单",
test: (p, n) => /^generate/.test(n) || /^sync[-_]/.test(n) || /^generate_/.test(n),
},
{
id: "build",
label: "构建与打包",
hint: "前端构建、内核产物、离线包",
test: (p, n) => /^(build[-_]|rebuild)/.test(n) || /^assemble_/.test(n) || n === "build-and-publish.mjs",
},
{
id: "audit",
label: "审计与上下文校验",
hint: "界面覆盖审计、上下文一致性、链接闭合",
test: (p, n) => /^(audit|validate|check)/.test(n) || p.startsWith("tools/parity/"),
},
{
id: "scheduler",
label: "调度与性能",
hint: "无人值守调度器、计时分析、基准",
test: (p, n) => /scheduler|benchmark|analyze_|timing/.test(n),
},
{ id: "other", label: "其他", hint: "未归类的脚本", test: () => true },
];
export const CATEGORY_BY_ID = new Map(CATEGORIES.map((c) => [c.id, c]));
/** Trailing tokens that mark a variant of a family rather than a distinct tool. */
export const VARIANT_TOKENS = new Set([
"smoke", "chrome", "headless", "gate", "probe", "worker", "batch", "summary", "receipt",
"recovery", "persistence", "kernel", "native", "boundary", "runtime", "test", "tests",
"check", "capture", "audit", "build", "v2", "node", "web", "shell", "case", "cases",
]);
/** Known environment variables with Chinese descriptions. */
export const ENV_DOCS = {
HEADLESS: "设为 0 时以有头模式启动浏览器(默认无头)。",
FREECAD_CHROME: "Chrome/Chromium 可执行文件绝对路径,覆盖默认候选。",
FREECAD_BROWSER_ORIGIN: "复用已启动的静态服务地址,跳过自建 host。",
FREECAD_BROWSER_EXECUTABLE: "浏览器可执行文件路径(部分工具用法)。",
FREECAD_PARITY_ENTRY: "桌面/Web 一致性检查的入口页面或数据文件。",
FREECAD_CAM_CASE: "CAM 用例筛选 id。",
FREECAD_BUSINESS_IDS: "业务用例 id 列表(逗号分隔)。",
FREECAD_BUILD_JOBS: "构建并行度(默认取 CPU 数)。",
FREECAD_CCACHE_RAM: "ccache 可用内存上限,用于编译调度。",
FREECAD_MCP_READY_TIMEOUT_MS: "MCP 浏览器会话就绪超时(毫秒)。",
FREECAD_MCP_CALL_TIMEOUT_MS: "MCP 单次调用超时(毫秒)。",
MANUAL_URL: "手册页面地址,供页面检查脚本使用。",
EM_CONFIG: "Emscripten 配置文件绝对路径(WASM 编译铁律)。",
EM_CACHE: "Emscripten 缓存目录绝对路径(WASM 编译铁律)。",
DISPLAY: "X11 显示号;有头浏览与截图需要(如 :1)。",
};
/** Ten commands worth putting on the first screen. */
export const QUICKSTART = [
{ cmd: "npx tsc --noEmit && npx vite build", cwd: "<repo>/web", note: "前端类型检查 + 构建 dist(改过 web/src 后必跑)。" },
{ cmd: "python3 ../tools/build_web_frontend.py", cwd: "<repo>/web", note: "生成式前端交付构建(固定工作目录,不跑测试)。" },
{ cmd: "node ../tools/sync-assets.mjs", cwd: "<repo>/web", note: "同步内核产物到 public/kernel 与 dist/kernel(按 mtime 择新)。" },
{ cmd: "DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --only X-panel-scroll --force", cwd: "<repo>", note: "跑单个功能用例。" },
{ cmd: "DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --priority P1 --force", cwd: "<repo>", note: "跑整层手册章节用例。" },
{ cmd: "node tools/layout-probe.mjs --url /partdesign.html", cwd: "<repo>", note: "检查三栏布局与左右面板独立滚动。" },
{ cmd: "node tools/static-host.mjs --root web/dist", cwd: "<repo>", note: "起一个带 COOP/COEP 的临时静态服务并打印 ORIGIN。" },
{ cmd: "DISPLAY=:1 node tools/manual/capture.mjs --scenario manual/scenarios/ch01-ui.json --origin <ORIGIN>", cwd: "<repo>/web", note: "跑手册场景并截图。" },
{ cmd: "node ../tools/build-tools-manual.mjs --check", cwd: "<repo>/web", note: "校验本手册是否为最新(幂等检查)。" },
{ cmd: "DISPLAY=:1 node ../tools/check-tools-manual.mjs", cwd: "<repo>/web", note: "Playwright 检查本手册页面与交互。" },
];

View File

@@ -0,0 +1,417 @@
/**
* Record extraction for tools/build-tools-manual.mjs.
*
* Turns scanned file heads into inventory records: category, role (CLI /
* library / data), Chinese purpose, usage, environment variables, and the
* family a generated sibling belongs to.
*
* Every extracted text keeps its provenance so the page can show a badge and
* nobody mistakes an inference for a declaration.
*/
import path from "node:path";
import { CATEGORIES, CATEGORY_BY_ID, ENV_DOCS, VARIANT_TOKENS } from "./config.mjs";
const BADGE = {
header: "源码注释",
docstring: "源码注释",
npm: "npm 脚本",
family: "族模板(推断)",
filename: "命名推断",
};
export function escapeText(value) {
return String(value ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function collapse(text) {
return String(text ?? "").replace(/\s+/g, " ").trim();
}
function firstSentences(text, limit) {
const clean = collapse(text);
if (clean.length <= limit) return clean;
const cut = clean.slice(0, limit);
const stop = Math.max(cut.lastIndexOf("。"), cut.lastIndexOf(". "), cut.lastIndexOf(";"), cut.lastIndexOf(";"));
return stop > limit * 0.4 ? `${cut.slice(0, stop + 1)}` : `${cut}…`;
}
function stripCommentDecor(line) {
return line.replace(/^\s*(?:\/\/+|#+|\*+|\/\*+)\s?/, "").replace(/\*\/\s*$/, "").trim();
}
/* --- purpose ------------------------------------------------------------ */
function pythonDocstring(head) {
const start = head.search(/"""/);
if (start < 0 || start > 4000) return null;
const body = head.slice(start + 3);
const end = body.indexOf('"""');
return end < 0 ? null : body.slice(0, end);
}
function jsHeaderComment(head) {
const block = head.match(/^\s*(?:#![^\n]*\n)?\s*\/\*\*?([\s\S]*?)\*\//);
if (block) {
const lines = block[1].split("\n").map(stripCommentDecor).filter(Boolean);
if (lines.length) return lines.join(" ");
}
const lineComments = [];
for (const line of head.split("\n").slice(0, 20)) {
if (/^\s*#!/.test(line)) continue;
if (/^\s*\/\//.test(line)) { lineComments.push(stripCommentDecor(line)); continue; }
if (/^\s*$/.test(line) && lineComments.length === 0) continue;
if (/^\s*$/.test(line) && lineComments.length) break;
if (lineComments.length) break;
}
return lineComments.length ? lineComments.join(" ") : null;
}
function shellHeaderComment(head) {
const lines = [];
for (const line of head.split("\n").slice(0, 15)) {
if (/^\s*#!/.test(line)) continue;
if (/^\s*#/.test(line)) { lines.push(stripCommentDecor(line)); continue; }
if (/^\s*$/.test(line) && lines.length === 0) continue;
break;
}
return lines.length ? lines.join(" ") : null;
}
function extractPurpose(file) {
const explicit = file.head.match(/^\s*(?:\/\/|#|\*)?\s*(?:Purpose|用途)\s*[::]\s*(.+)$/m);
if (explicit) return { text: firstSentences(explicit[1], 320), source: BADGE.header };
const text = file.ext === ".py"
? pythonDocstring(file.head)
: file.ext === ".sh" || file.ext === ".ps1" ? shellHeaderComment(file.head) : jsHeaderComment(file.head);
if (!text) return null;
const cleaned = firstSentences(text, 320);
if (!cleaned || /^copyright|^license|^spdx/i.test(cleaned)) return null;
return { text: cleaned, source: BADGE.docstring };
}
/* --- usage -------------------------------------------------------------- */
const COMMAND_LINE = /^\s*(?:(?:\/\/|#|\*)\s*)?((?:node|npx|python3?|npm|bash|sh|pwsh)\s+[^\n]*)$/gm;
function extractUsage(file) {
const commands = [];
const push = (cmd) => {
const clean = collapse(cmd).replace(/^["']|["']$/g, "");
if (clean && !commands.some((existing) => existing === clean)) commands.push(clean);
};
for (const match of file.head.matchAll(COMMAND_LINE)) push(match[1]);
const usageLine = file.head.match(/^\s*(?:\/\/|#|\*)\s*(?:Usage|用法)\s*[::]\s*(.+)$/m);
if (usageLine) push(usageLine[1]);
const blockUsage = file.head.match(/(?:Usage|用法)\s*[::]\s*\n((?:\s*(?:\/\/|#|\*)\s*\S[^\n]*\n){1,6})/);
if (blockUsage) {
for (const line of blockUsage[1].split("\n")) {
const clean = stripCommentDecor(line);
if (/^(node|npx|python3?|npm|bash|sh|\.\/)/.test(clean)) push(clean);
}
}
return commands.slice(0, 4);
}
/* --- environment -------------------------------------------------------- */
function extractEnv(head) {
const names = new Set();
for (const match of head.matchAll(/process\.env\.([A-Z0-9_]+)/g)) names.add(match[1]);
for (const match of head.matchAll(/process\.env\[\s*["']([A-Z0-9_]+)["']\s*\]/g)) names.add(match[1]);
for (const match of head.matchAll(/os\.environ\[\s*["']([A-Z0-9_]+)["']\s*\]/g)) names.add(match[1]);
for (const match of head.matchAll(/os\.environ\.get\(\s*["']([A-Z0-9_]+)["']/g)) names.add(match[1]);
for (const match of head.matchAll(/os\.getenv\(\s*["']([A-Z0-9_]+)["']/g)) names.add(match[1]);
return [...names].sort();
}
/* --- role --------------------------------------------------------------- */
function detectRole(file, importedBy) {
if (file.ext === ".json" || file.relPath.startsWith("tools/generated-contracts/")) return "data";
const shebang = /^#!/.test(file.head);
const argv = /process\.argv/.test(file.head);
const mainGuard = /__name__\s*==\s*["']__main__["']/.test(file.head);
const argparse = /ArgparseError|ArgumentParser|add_argument\(/.test(file.head);
const hasCliMarkers = shebang || argv || mainGuard || argparse;
const importers = importedBy.get(file.relPath) ?? 0;
if (hasCliMarkers && importers > 0) return "cli-module";
if (hasCliMarkers) return "cli";
if (importers > 0) return "module";
if (/^\s*export\s/m.test(file.head)) return "module";
return "unknown";
}
export const ROLE_LABEL = {
cli: "CLI",
"cli-module": "CLI + 库",
module: "库",
data: "数据",
unknown: "未验证",
};
/* --- classification ----------------------------------------------------- */
export function classify(relPath, name) {
for (const category of CATEGORIES) {
if (category.test(relPath, name)) return category.id;
}
return "other";
}
/* --- families ----------------------------------------------------------- */
function baseName(name) {
return name.replace(/\.(mjs|js|ts|tsx|py|sh|ps1|json|cmake)$/, "");
}
function stripVariantTokens(stem) {
let current = stem;
for (let guard = 0; guard < 5; guard += 1) {
const match = current.match(/^(.*)[-_]([a-z0-9]+)$/);
if (!match || !VARIANT_TOKENS.has(match[2])) break;
current = match[1];
}
return current;
}
const VARIANT_PURPOSE = {
smoke: "冒烟验证:加载 Web 构建并断言核心路径可用。",
gate: "验收门禁:汇总同族结果,非零退出表示不达标。",
chrome: "Chrome 端到端用例:真实浏览器里跑完整交互。",
probe: "探测脚本:采集运行时/界面数据并输出报告。",
worker: "后台 worker 用例:在 worker 环境里校验 Python/原生路由。",
summary: "汇总脚本:把分散的结果聚合成一份摘要。",
receipt: "回执生成:记录一次运行的可核对凭据。",
recovery: "恢复用例:验证失败后的回滚与重试路径。",
persistence: "持久化用例:验证 OPFS/文档存取。",
kernel: "内核用例:直接对 WASM 内核调用断言。",
native: "原生路由用例:校验 C++/Python 原生实现路径。",
boundary: "边界用例:几何与接口的边界条件。",
runtime: "运行时检查:校验生成产物与运行期一致。",
parity: "桌面端与 Web 端一致性检查。",
batch: "批量运行器:按清单跑多个用例。",
cases: "业务场景表:导出用例供 smoke/gate 调用。",
};
function familyOf(relPath, name, stemCounts) {
const base = baseName(name);
const dir = path.posix.dirname(relPath);
let match;
if ((match = base.match(/^run_p6_([a-z0-9]+)_(.+)$/))) {
const [, moduleName, rest] = match;
const variant = rest.replace(/^action\d+_/, "");
return { id: `run_p6.${moduleName}`, title: `run_p6_${moduleName}_*`, variant, module: moduleName, pattern: `run_p6_${moduleName}_<action>_<kind>.mjs` };
}
if (base.includes("-business-cases")) {
const token = base.split("-business-cases")[0];
return { id: `cases.${token}`, title: `${token}-business-cases*`, variant: "cases", module: token, pattern: `${token}-business-cases.mjs` };
}
if ((match = base.match(/^ui-([a-z0-9]+)-(.+)$/))) {
return { id: `ui.${match[1]}`, title: `ui-${match[1]}-*`, variant: "parity", module: match[1], pattern: `ui-${match[1]}-<surface>.mjs` };
}
if (/^build_cam_.*_profile$/.test(base)) {
return { id: "build.cam-profiles", title: "build_cam_*_profile", variant: "build", module: "CAM", pattern: "build_cam_<op>_profile.mjs" };
}
if ((match = base.match(/^build_([a-z0-9]+)_(.+)$/))) {
return { id: `build.${match[1]}`, title: `build_${match[1]}_*`, variant: "build", module: match[1], pattern: `build_${match[1]}_<target>.mjs` };
}
if (/^generate_.*runtime_index$/.test(base)) {
return { id: "codegen.runtime-index", title: "generate_*_runtime_index", variant: "runtime", module: "runtime", pattern: "generate_<family>_runtime_index.py" };
}
if (/^generate_.*adapter_manifest/.test(base)) {
return { id: "codegen.adapter-manifest", title: "generate_*adapter_manifest*", variant: "runtime", module: "adapter", pattern: "generate_<family>_adapter_manifest.py" };
}
// Generic: only group when at least three siblings share the stripped stem.
const stem = stripVariantTokens(base);
if (stem !== base && stem.length >= 4 && (stemCounts.get(stem) ?? 0) >= 3) {
return { id: `stem.${dir}.${stem}`, title: `${stem}_*`, variant: base.slice(stem.length).replace(/^[-_]/, ""), module: stem, pattern: `${stem}_<variant>.mjs` };
}
return null;
}
function pickRepresentative(members) {
const scored = members.map((member) => {
let score = 0;
if (member.purpose && member.purpose.source === BADGE.docstring) score += 10;
if (member.usage.length) score += 5;
if (member.role === "cli") score += 3;
return { member, score };
});
scored.sort((a, b) => b.score - a.score || a.member.name.length - b.member.name.length || (a.member.relPath < b.member.relPath ? -1 : 1));
return scored[0].member;
}
/* --- main --------------------------------------------------------------- */
export function extract({ files, directories, npmScripts, importedBy }) {
const stemCounts = new Map();
for (const file of files) {
const stem = stripVariantTokens(baseName(file.name));
if (stem !== baseName(file.name)) stemCounts.set(stem, (stemCounts.get(stem) ?? 0) + 1);
}
const records = files.map((file) => {
const categoryId = classify(file.relPath, file.name);
const role = detectRole(file, importedBy);
const purpose = extractPurpose(file);
const usage = extractUsage(file);
const env = extractEnv(file.head);
const npm = npmScripts.get(file.relPath) ?? [];
const family = familyOf(file.relPath, file.name, stemCounts);
return {
relPath: file.relPath,
name: file.name,
ext: file.ext,
bytes: file.bytes,
categoryId,
role,
purpose,
usage,
env,
npm,
family,
importedBy: importedBy.get(file.relPath) ?? 0,
};
});
// Purpose fallback chain: npm script > family template > filename.
for (const record of records) {
if (record.purpose) continue;
if (record.npm.length) {
record.purpose = { text: `npm 脚本 \`${record.npm[0]}\` 的入口;具体行为见源码。`, source: BADGE.npm };
continue;
}
if (record.family && VARIANT_PURPOSE[record.family.variant]) {
const moduleName = record.family.module ?? "";
record.purpose = { text: `${moduleName ? `\`${moduleName}\` 的` : ""}${VARIANT_PURPOSE[record.family.variant]}(由文件名推断,未在头部声明用途)`, source: BADGE.family };
continue;
}
if (record.role === "module" || record.role === "cli-module") {
record.purpose = { text: `库模块:被 ${record.importedBy} 个脚本导入,无独立命令行入口。`, source: BADGE.filename };
} else if (record.role === "data") {
record.purpose = { text: "数据文件:由其他脚本读取,不直接执行。", source: BADGE.filename };
} else {
const category = CATEGORY_BY_ID.get(record.categoryId);
record.purpose = { text: `未检测到头部说明;按命名归入「${category?.label ?? "其他"}」。请阅读源码确认。`, source: BADGE.filename };
}
}
// Usage fallback chain.
for (const record of records) {
if (record.usage.length) continue;
const p = record.relPath;
if (record.npm.length) {
record.usage = [`cd web && npm run ${record.npm[0]}`, `${record.ext === ".py" ? "python3" : "node"} ${p}`];
continue;
}
if (record.family && ["smoke", "gate", "chrome", "probe", "worker", "batch"].includes(record.family.variant)) {
const runner = record.ext === ".py" ? "python3" : "node";
record.usage = [`${runner} ${record.family.pattern}`.replace("<action>_<kind>", "<action>_<kind>").replace("<kind>", record.family.variant).replace("<surface>", "<surface>").replace("<target>", "<target>").replace("<op>", "<op>").replace("<family>", "<family>").replace("<variant>", record.family.variant)];
record.usageNote = "将占位符替换为展开列表中的成员名;参数未在头部声明。";
continue;
}
if (record.role === "module" || record.role === "cli-module") {
record.usage = [`import { … } from "${p.replace(/\.(mjs|js|ts)$/, ".mjs")}"`];
record.usageNote = "库用法:导入后调用其导出函数,无独立 CLI 入口。";
continue;
}
if (record.role === "data") {
record.usage = [];
record.usageNote = record.importedBy ? `数据文件:由 ${record.importedBy} 个脚本读取。` : "数据文件:不直接执行。";
continue;
}
const runner = record.ext === ".py" ? "python3" : record.ext === ".sh" ? "bash" : record.ext === ".json" ? null : "node";
record.usage = runner && record.role !== "unknown" ? [`${runner} ${p}`] : runner ? [`${runner} ${p}`] : [];
if (runner) record.usageNote = "参数未在源码头部声明;运行前请阅读文件头部或尝试 --help。";
else record.usageNote = "未在源码中声明用法。";
if (record.role === "unknown") record.usageNote = "未检测到 CLI 标记,也无导入者;可能是一次性脚本或被外部调用。";
}
// Family aggregation.
const groups = new Map();
for (const record of records) {
if (!record.family) continue;
if (!groups.has(record.family.id)) groups.set(record.family.id, []);
groups.get(record.family.id).push(record);
}
const families = [];
for (const [id, members] of groups) {
if (members.length < 2) {
for (const member of members) member.family = null;
continue;
}
const representative = pickRepresentative(members);
const env = new Set();
for (const member of members) for (const name of member.env) env.add(name);
families.push({
id,
title: members[0].family.title,
pattern: members[0].family.pattern,
variant: members[0].family.variant,
module: members[0].family.module,
count: members.length,
representative,
members: members.map((member) => member.relPath).sort(),
categoryId: representative.categoryId,
purpose: representative.purpose,
usage: representative.usage,
usageNote: representative.usageNote,
env: [...env].sort(),
npm: [...new Set(members.flatMap((member) => member.npm))],
role: members.every((member) => member.role === "data") ? "data" : "family",
});
}
families.sort((a, b) => (a.id < b.id ? -1 : 1));
const familyIds = new Set(families.map((family) => family.id));
for (const record of records) {
if (record.family && !familyIds.has(record.family.id)) record.family = null;
if (record.family) record.familyId = record.family.id;
delete record.family;
}
// Per-family bookkeeping is enough for the page: a member row links to its family.
const directoryRecords = directories.map((entry) => ({
relPath: entry.relPath,
name: entry.label,
categoryId: entry.category,
role: "directory",
purpose: { text: entry.note, source: BADGE.header },
usage: [],
usageNote: `目录型记录:共 ${entry.count} 个文件,逐项见展开列表。`,
env: [],
npm: [],
familyId: null,
members: entry.members,
count: entry.count,
importedBy: 0,
}));
const envUsage = new Map();
for (const record of [...records, ...families]) {
for (const name of record.env ?? []) {
if (!envUsage.has(name)) envUsage.set(name, { count: 0, samples: [] });
const entry = envUsage.get(name);
entry.count += record === undefined ? 0 : (record.count ?? 1);
if (entry.samples.length < 4) entry.samples.push(record.relPath ?? record.id);
}
}
const stats = {
files: files.length,
directories: directoryRecords.length,
families: families.length,
singles: records.filter((record) => !record.familyId).length,
rows: families.length + records.filter((record) => !record.familyId).length + directoryRecords.length,
withPurpose: records.filter((record) => record.purpose && record.purpose.source === BADGE.docstring).length,
withUsage: records.filter((record) => record.usage.length && !record.usageNote?.startsWith("参数未在")).length,
};
return { records, families, directories: directoryRecords, envUsage, stats, badges: BADGE };
}
export { ENV_DOCS, BADGE };

View File

@@ -0,0 +1,576 @@
/**
* HTML renderer for tools/build-tools-manual.mjs.
*
* Produces one self-contained page: inline CSS, inline JS, no images, no CDN,
* no external fonts. Output is a pure function of the model, so `--check` can
* compare bytes.
*/
import { escapeText as esc } from "./extract.mjs";
import { CATEGORIES, CATEGORY_BY_ID, ENV_DOCS, QUICKSTART } from "./config.mjs";
import { CHAPTERS, CONTRACT_CHAPTERS } from "./chapters.mjs";
const ROLE_LABEL = {
cli: "CLI",
"cli-module": "CLI + 库",
module: "库",
data: "数据",
directory: "目录",
family: "族",
unknown: "未验证",
};
function slug(value) {
return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "x";
}
function code(text) {
return `<code>${esc(text)}</code>`;
}
function pre(text, label) {
const head = label ? `<div class="pre-label">${esc(label)}</div>` : "";
return `<div class="pre-wrap">${head}<pre><code>${esc(text)}</code></pre></div>`;
}
function badge(source) {
const kind = source.includes("推断") ? "inferred" : "declared";
return `<span class="badge ${kind}">${esc(source)}</span>`;
}
const CSS = `
:root{--bg:#0f1419;--panel:#17212b;--panel2:#1b2733;--line:#2a3a45;--text:#dbe6ee;--muted:#93a6b3;--accent:#73c6d4;--ok:#7fc98b;--warn:#e0b15c;--bad:#e58a8a;color-scheme:dark}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
body{margin:0;background:var(--bg);color:var(--text);font:15px/1.65 system-ui,-apple-system,"Segoe UI","Noto Sans CJK SC","Microsoft YaHei",sans-serif;overflow-wrap:break-word}
a{color:var(--accent);text-decoration:none}
a:hover{text-decoration:underline}
code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
code{background:#0b1117;border:1px solid var(--line);border-radius:4px;padding:.1em .35em;font-size:.9em;overflow-wrap:anywhere}
pre{margin:0;padding:12px 14px;background:#0b1117;border:1px solid var(--line);border-radius:8px;overflow:auto;font-size:13px;line-height:1.55}
.pre-wrap{margin:10px 0}
.pre-label{font-size:12px;color:var(--muted);margin-bottom:4px}
.skip{position:absolute;left:-999px;top:0;background:var(--accent);color:#04161a;padding:8px 12px;border-radius:0 0 8px 0;z-index:60}
.skip:focus{left:0}
header.top{position:sticky;top:0;z-index:40;display:flex;gap:16px;align-items:center;padding:10px 18px;background:rgba(15,20,25,.96);border-bottom:1px solid var(--line);backdrop-filter:blur(6px)}
header.top .brand{font-weight:650;white-space:nowrap}
header.top .brand small{color:var(--muted);font-weight:400;margin-left:8px}
.search-wrap{position:relative;flex:1;max-width:520px;margin-left:auto}
#search{width:100%;padding:7px 12px;border-radius:8px;border:1px solid var(--line);background:#0b1117;color:var(--text);font-size:14px}
#search:focus{outline:2px solid var(--accent);outline-offset:1px}
#search-results{position:absolute;top:calc(100% + 6px);left:0;right:0;max-height:60vh;overflow:auto;background:var(--panel);border:1px solid var(--line);border-radius:8px;box-shadow:0 12px 30px rgba(0,0,0,.45);padding:6px;display:none}
#search-results.open{display:block}
#search-results a{display:block;padding:7px 9px;border-radius:6px;color:var(--text)}
#search-results a:hover,#search-results a:focus{background:var(--panel2);text-decoration:none}
#search-results .r-path{display:block;font-size:12px;color:var(--muted)}
#search-results .empty{padding:8px;color:var(--muted);font-size:13px}
#drawer-toggle{display:none;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:14px}
.shell{display:grid;grid-template-columns:290px minmax(0,1fr);gap:0;max-width:1500px;margin:0 auto}
nav.toc{position:sticky;top:58px;align-self:start;max-height:calc(100vh - 58px);overflow:auto;padding:16px 12px 40px;border-right:1px solid var(--line)}
nav.toc h2{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin:14px 8px 6px}
nav.toc a{display:block;padding:4px 8px;border-radius:6px;color:var(--text);font-size:13.5px}
nav.toc a:hover{background:var(--panel2);text-decoration:none}
nav.toc a.active{background:var(--panel2);color:var(--accent)}
nav.toc details{margin:2px 0}
nav.toc summary{padding:4px 8px;border-radius:6px;cursor:pointer;font-size:13.5px;list-style:none}
nav.toc summary::-webkit-details-marker{display:none}
nav.toc summary:hover{background:var(--panel2)}
main{padding:22px 28px 90px;min-width:0}
h1{font-size:26px;margin:0 0 6px;line-height:1.3}
h2{font-size:20px;margin:38px 0 12px;padding-top:10px;border-top:1px solid var(--line)}
h3{font-size:16px;margin:22px 0 8px}
h4{font-size:14px;margin:16px 0 6px;color:var(--muted)}
p{margin:8px 0}
.lead{color:#c4d5e0;font-size:15.5px}
.muted{color:var(--muted)}
.small{font-size:13px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px 16px;margin:12px 0}
.grid{display:grid;gap:12px}
.grid.two{grid-template-columns:repeat(auto-fit,minmax(280px,1fr))}
.grid.three{grid-template-columns:repeat(auto-fit,minmax(210px,1fr))}
.stat{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:12px 14px}
.stat b{display:block;font-size:22px;color:var(--accent)}
.stat span{color:var(--muted);font-size:13px}
.note{border-left:3px solid var(--accent);background:var(--panel);padding:10px 14px;border-radius:0 8px 8px 0;margin:12px 0}
.warnbox{border-left:3px solid var(--warn);background:var(--panel);padding:10px 14px;border-radius:0 8px 8px 0;margin:12px 0}
.badge{display:inline-block;font-size:11px;padding:1px 7px;border-radius:999px;border:1px solid var(--line);color:var(--muted);vertical-align:middle}
.badge.inferred{border-color:#6b5426;color:var(--warn)}
.pill{display:inline-block;font-size:11.5px;padding:1px 8px;border-radius:999px;background:var(--panel2);border:1px solid var(--line);color:var(--muted);margin-left:6px}
.tool-chapter{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:18px 20px;margin:18px 0}
.tool-chapter h3{margin-top:0;font-size:18px}
.tool-chapter .path{font-size:13px;color:var(--muted);margin-bottom:8px;overflow-wrap:anywhere}
.kv{display:grid;grid-template-columns:110px minmax(0,1fr);gap:6px 14px;margin:12px 0;font-size:14px}
.kv dt{color:var(--muted)}
.kv dd{margin:0;min-width:0}
.table-scroll{overflow:auto;border:1px solid var(--line);border-radius:10px;margin:12px 0}
table{width:100%;border-collapse:collapse;font-size:13.5px}
th,td{text-align:left;vertical-align:top;padding:8px 10px;border-bottom:1px solid var(--line)}
th{position:sticky;top:0;background:var(--panel2);font-weight:600;z-index:1}
tr:last-child td{border-bottom:0}
td.path{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12.5px;overflow-wrap:anywhere}
details summary{cursor:pointer}
details summary::marker{color:var(--muted)}
details ul{margin:6px 0 0;padding-left:22px}
details li{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;color:var(--muted);overflow-wrap:anywhere}
.toolbar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin:10px 0;position:sticky;top:58px;background:var(--bg);padding:8px 0;z-index:5}
.toolbar select,.toolbar input{background:#0b1117;color:var(--text);border:1px solid var(--line);border-radius:8px;padding:6px 9px;font-size:13.5px}
.toolbar label{font-size:13px;color:var(--muted);display:inline-flex;gap:5px;align-items:center}
#visible-count{font-size:13px;color:var(--muted);margin-left:auto}
.pager{display:flex;flex-wrap:wrap;gap:8px;margin:8px 0 16px}
.pager a{font-size:13px;padding:3px 9px;border:1px solid var(--line);border-radius:999px}
footer{border-top:1px solid var(--line);margin-top:48px;padding-top:14px;color:var(--muted);font-size:13px}
.target-flash{animation:flash 1.6s ease-out}
@keyframes flash{0%{background:#20414b}100%{background:transparent}}
@media (max-width:960px){
#drawer-toggle{display:inline-block}
.shell{grid-template-columns:1fr}
nav.toc{position:fixed;left:0;top:57px;bottom:0;width:290px;max-height:none;background:var(--bg);z-index:35;transform:translateX(-100%);transition:transform .18s ease;border-right:1px solid var(--line)}
nav.toc.open{transform:none}
main{padding:18px 16px 80px}
header.top .brand small{display:none}
.toolbar{position:static}
}
@media print{
header.top,nav.toc,.toolbar,#drawer-toggle,.pager{display:none!important}
.shell{display:block}
main{padding:0}
body{background:#fff;color:#111}
.card,.tool-chapter,.stat,.note,.warnbox{border-color:#bbb;background:#fff}
details{display:block}
details>*{display:block!important}
.tool-chapter{break-before:page}
a{color:#0645ad}
}
`;
function sidebar(model) {
const links = [];
const sections = [
["overview", "阅读指南"],
["quickstart", "快速开始"],
["contracts", "环境契约"],
["topology", "工具全景"],
["core", "核心工具详解"],
["inventory", "全量索引"],
["npm", "npm scripts"],
["env", "环境变量字典"],
["troubleshooting", "排错"],
["maintenance", "再生成与校验"],
["appendix", "附录"],
];
links.push(`<h2>章节</h2>${sections.map(([id, title]) => `<a href="#${id}">${esc(title)}</a>`).join("")}`);
const byCategory = new Map();
for (const chapter of model.chapters) {
if (!byCategory.has(chapter.categoryId)) byCategory.set(chapter.categoryId, []);
byCategory.get(chapter.categoryId).push(chapter);
}
const groups = [];
for (const category of CATEGORIES) {
const chapters = byCategory.get(category.id);
if (!chapters) continue;
groups.push(`<details open><summary>${esc(category.label)} <span class="muted">(${chapters.length})</span></summary>${chapters.map((chapter) => `<a href="#${chapter.anchor}">${esc(chapter.shortTitle)}</a>`).join("")}</details>`);
}
links.push(`<h2>核心工具</h2>${groups.join("")}`);
const families = model.families.slice(0, 0); // families stay in the index, not the sidebar
void families;
return `<nav class="toc" id="toc" aria-label="目录">${links.join("")}</nav>`;
}
function renderChapter(chapter, chapterById = new Map()) {
const rows = [];
rows.push(`<p class="lead">${esc(chapter.summary)}</p>`);
rows.push(`<div class="path">位置:${code(chapter.path)}</div>`);
if (chapter.when) rows.push(`<p><strong>何时使用:</strong>${esc(chapter.when)}</p>`);
if (chapter.usage?.length) {
rows.push(`<h4>命令</h4>`);
for (const entry of chapter.usage) {
rows.push(pre(entry.cmd, entry.note ?? undefined));
}
}
if (chapter.params?.length) {
rows.push(`<h4>参数</h4><div class="table-scroll"><table><thead><tr><th>参数</th><th>说明</th></tr></thead><tbody>${chapter.params.map((param) => `<tr><td class="path">${esc(param.flag)}</td><td>${esc(param.note)}</td></tr>`).join("")}</tbody></table></div>`);
}
if (chapter.inputs?.length) rows.push(`<p><strong>输入:</strong>${chapter.inputs.map((item) => code(item)).join("、")}</p>`);
if (chapter.outputs?.length) rows.push(`<p><strong>输出:</strong>${chapter.outputs.map((item) => code(item)).join("、")}</p>`);
if (chapter.env?.length) rows.push(`<p><strong>环境变量:</strong>${chapter.env.map((name) => `<a href="#env-${slug(name)}">${code(name)}</a>`).join("、")}</p>`);
if (chapter.notes?.length) rows.push(`<div class="note"><strong>注意</strong><ul>${chapter.notes.map((note) => `<li>${esc(note)}</li>`).join("")}</ul></div>`);
if (chapter.related?.length) {
const links = chapter.related.map((id) => {
const target = chapterById.get(id);
return target ? `<a href="#${target.anchor}">${esc(target.shortTitle)}</a>` : esc(id);
});
rows.push(`<p class="small muted">相关:${links.join(" · ")}</p>`);
}
return `<section class="tool-chapter" id="${chapter.anchor}"><h3>${esc(chapter.title)}</h3>${rows.join("")}</section>`;
}
/** Member lists are capped: some course directories hold hundreds of media files. */
function memberList(members, cap) {
const shown = members.slice(0, cap);
const extra = members.length - shown.length;
const tail = extra > 0 ? `<li class="muted">…另有 ${extra} 个文件(共 ${members.length} 个)</li>` : "";
return `<ul>${shown.map((member) => `<li>${esc(member)}</li>`).join("")}${tail}</ul>`;
}
function renderRecordRows(model) {
const rows = [];
const corePaths = new Set(model.chapters.map((chapter) => chapter.path));
const categoryOrder = new Map(CATEGORIES.map((category, index) => [category.id, index]));
const sortKey = (entry) => [categoryOrder.get(entry.categoryId) ?? 99, entry.name.toLowerCase()];
const entries = [
...model.families.map((family) => ({
kind: "family",
anchor: family.anchor,
name: family.title,
categoryId: family.categoryId,
role: "family",
purpose: family.purpose,
usage: family.usage,
usageNote: family.usageNote,
count: family.count,
members: family.members,
npm: family.npm,
search: `${family.title} ${family.members.join(" ")}`,
})),
...model.records.filter((record) => !record.familyId).map((record) => ({
kind: "file",
anchor: record.anchor,
name: record.name,
categoryId: record.categoryId,
role: record.role,
purpose: record.purpose,
usage: record.usage,
usageNote: record.usageNote,
path: record.relPath,
npm: record.npm,
search: record.relPath,
})),
...model.directories.map((directory) => ({
kind: "directory",
anchor: directory.anchor,
name: directory.name,
categoryId: directory.categoryId,
role: "directory",
purpose: directory.purpose,
usage: directory.usage,
usageNote: directory.usageNote,
count: directory.count,
members: directory.members,
search: `${directory.relPath} ${directory.members.join(" ")}`,
})),
];
entries.sort((a, b) => {
const [ca, na] = sortKey(a);
const [cb, nb] = sortKey(b);
return ca - cb || (na < nb ? -1 : na > nb ? 1 : 0);
});
for (const entry of entries) {
const label = entry.kind === "family"
? `<details><summary>${code(entry.name)} <span class="pill">${entry.count} 个文件</span></summary>${memberList(entry.members, 120)}</details>`
: entry.kind === "directory"
? `<details><summary>${code(entry.name)} <span class="pill">${entry.count} 个文件</span></summary>${memberList(entry.members, 60)}</details>`
: `${code(entry.name)}<div class="small muted">${esc(entry.path)}</div>`;
const purpose = `${esc(entry.purpose.text)} ${badge(entry.purpose.source)}`;
const usage = entry.usage?.length
? entry.usage.map((cmd) => `<div class="path">${esc(cmd)}</div>`).join("")
: `<span class="muted">—</span>`;
const note = entry.usageNote ? `<div class="small muted">${esc(entry.usageNote)}</div>` : "";
const npm = entry.npm?.length ? `<div class="small muted">npm: ${entry.npm.map((name) => esc(name)).join(", ")}</div>` : "";
const isCore = entry.kind === "file" && corePaths.has(entry.path);
rows.push(`<tr id="${entry.anchor}" data-cat="${esc(entry.categoryId)}" data-role="${esc(entry.role)}"${isCore ? ' data-core="1"' : ""}><td>${label}</td><td>${esc(CATEGORY_BY_ID.get(entry.categoryId)?.label ?? "其他")}</td><td>${esc(ROLE_LABEL[entry.role] ?? entry.role)}</td><td>${purpose}</td><td>${usage}${note}${npm}</td></tr>`);
}
return rows.join("");
}
function renderNpmTable(npmCatalog) {
if (!npmCatalog.length) return `<p class="muted">未找到 package.json 脚本。</p>`;
return `<div class="table-scroll"><table><thead><tr><th>脚本</th><th>位置</th><th>命令</th></tr></thead><tbody>${npmCatalog.map((entry) => `<tr><td class="path">${esc(entry.name)}</td><td class="small muted">${esc(entry.cwd ? `${entry.cwd}/` : "")}package.json</td><td class="path">${esc(entry.command)}</td></tr>`).join("")}</tbody></table></div>`;
}
function renderEnvTable(envUsage) {
const names = [...envUsage.keys()].sort();
if (!names.length) return `<p class="muted">未扫描到环境变量引用。</p>`;
return `<div class="table-scroll"><table><thead><tr><th>变量</th><th>说明</th><th>引用次数</th><th>示例工具</th></tr></thead><tbody>${names.map((name) => {
const entry = envUsage.get(name);
const doc = ENV_DOCS[name];
const desc = doc ? esc(doc) : `<span class="muted">代码引用(用途未注明)</span>`;
return `<tr id="env-${slug(name)}"><td class="path">${esc(name)}</td><td>${desc}</td><td>${entry.count}</td><td class="small">${entry.samples.map((sample) => `<div class="path">${esc(sample)}</div>`).join("")}</td></tr>`;
}).join("")}</tbody></table></div>`;
}
function buildSearchIndex(model) {
const items = [];
const sections = [
["overview", "阅读指南", "说明", "覆盖范围 分组 徽标"],
["quickstart", "快速开始", "说明", "常用命令"],
["contracts", "环境契约", "说明", "路径 WASM 浏览器 OPFS"],
["topology", "工具全景", "说明", "分类 数量 族"],
["core", "核心工具详解", "说明", "详解"],
["inventory", "全量索引", "说明", "全部 工具 搜索"],
["npm", "npm scripts", "说明", "脚本 命令"],
["env", "环境变量字典", "说明", "环境变量"],
["troubleshooting", "排错", "说明", "错误 退出码"],
["maintenance", "再生成与校验", "说明", "生成 check verify"],
["appendix", "附录", "说明", "统计 排除 来源"],
];
for (const [id, title, category, keywords] of sections) items.push([title, `#${id}`, category, keywords]);
for (const chapter of model.chapters) items.push([chapter.shortTitle, `#${chapter.anchor}`, "核心工具", `${chapter.path} ${chapter.summary}`]);
for (const family of model.families) {
items.push([family.title, `#${family.anchor}`, "族", `${family.members.slice(0, 12).join(" ")} ${family.purpose.text}`]);
// Every member stays individually findable even though only the family row is rendered.
for (const member of family.members) items.push([member.split("/").pop(), `#${family.anchor}`, "族成员", member]);
}
for (const record of model.records) {
if (record.familyId) continue;
items.push([record.name, `#${record.anchor}`, "文件", `${record.relPath} ${record.purpose.text}`]);
}
for (const directory of model.directories) items.push([directory.name, `#${directory.anchor}`, "目录", `${directory.relPath} ${directory.members.slice(0, 12).join(" ")}`]);
for (const name of model.envUsage.keys()) items.push([name, `#env-${slug(name)}`, "环境变量", "env 环境变量"]);
return items;
}
const CLIENT_JS = `
(function(){
var INDEX = window.__SEARCH_INDEX__ || [];
var input = document.getElementById("search");
var results = document.getElementById("search-results");
var toc = document.getElementById("toc");
var toggle = document.getElementById("drawer-toggle");
var selected = -1;
function norm(v){ return String(v||"").toLowerCase().replace(/\\s+/g," "); }
function close(){ results.classList.remove("open"); results.innerHTML=""; selected=-1; }
function render(list){
if(!list.length){ results.innerHTML='<div class="empty">没有匹配项</div>'; results.classList.add("open"); return; }
results.innerHTML = list.map(function(item, i){
return '<a href="'+item[1]+'" data-i="'+i+'"><span>'+item[0]+'</span><span class="r-path">'+item[2]+' · '+item[1]+'</span></a>';
}).join("");
results.classList.add("open");
selected=-1;
}
function search(){
var q = norm(input.value);
if(!q){ close(); return; }
var hits = [];
for(var i=0;i<INDEX.length && hits.length<50;i++){
var item = INDEX[i];
var hay = norm(item[0]+" "+item[1]+" "+item[2]+" "+item[3]);
if(hay.indexOf(q)>=0) hits.push(item);
}
render(hits);
}
if(input){
input.addEventListener("input", search);
input.addEventListener("keydown", function(e){
if(e.key==="Escape"){ input.value=""; close(); input.blur(); return; }
var links = results.querySelectorAll("a");
if(!links.length) return;
if(e.key==="ArrowDown"){ e.preventDefault(); selected=(selected+1)%links.length; links[selected].focus(); }
if(e.key==="ArrowUp"){ e.preventDefault(); selected=(selected-1+links.length)%links.length; links[selected].focus(); }
});
results.addEventListener("click", function(){ input.value=""; close(); });
document.addEventListener("click", function(e){ if(!results.contains(e.target) && e.target!==input) close(); });
document.addEventListener("keydown", function(e){
if(e.key==="/" && document.activeElement!==input && !/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName)){ e.preventDefault(); input.focus(); }
});
}
if(toggle && toc){
toggle.addEventListener("click", function(){ toc.classList.toggle("open"); });
toc.addEventListener("click", function(e){ if(e.target.tagName==="A") toc.classList.remove("open"); });
}
var links = [].slice.call(document.querySelectorAll("nav.toc a[href^='#']"));
var targets = links.map(function(a){ return document.getElementById(a.getAttribute("href").slice(1)); });
function spy(){
var best=-1;
for(var i=0;i<targets.length;i++){
var el=targets[i];
if(!el) continue;
if(el.getBoundingClientRect().top <= 120) best=i;
}
links.forEach(function(a,i){ a.classList.toggle("active", i===best); });
}
document.addEventListener("scroll", function(){ requestAnimationFrame(spy); }, {passive:true});
spy();
var cat = document.getElementById("cat-filter");
var coreOnly = document.getElementById("core-only");
var textFilter = document.getElementById("text-filter");
var visible = document.getElementById("visible-count");
var rows = [].slice.call(document.querySelectorAll("#inventory-table tbody tr"));
var rowText = rows.map(function(row){ return norm(row.textContent); });
function apply(){
var c = cat ? cat.value : "";
var t = textFilter ? norm(textFilter.value) : "";
var onlyCore = coreOnly && coreOnly.checked;
var shown=0;
rows.forEach(function(row, i){
var ok = (!c || row.getAttribute("data-cat")===c) && (!t || rowText[i].indexOf(t)>=0) && (!onlyCore || row.hasAttribute("data-core"));
row.hidden = !ok;
if(ok) shown++;
});
if(visible) visible.textContent = shown + " / " + rows.length + " 行";
}
if(cat) cat.addEventListener("change", apply);
if(textFilter) textFilter.addEventListener("input", apply);
if(coreOnly) coreOnly.addEventListener("change", apply);
apply();
if(location.hash){
var el = document.getElementById(location.hash.slice(1));
if(el){ el.classList.add("target-flash"); setTimeout(function(){ el.classList.remove("target-flash"); }, 1800); }
}
})();
`;
export function render(model) {
const stats = model.stats;
const categoryCounts = new Map();
for (const entry of [...model.families, ...model.records.filter((record) => !record.familyId), ...model.directories]) {
categoryCounts.set(entry.categoryId, (categoryCounts.get(entry.categoryId) ?? 0) + 1);
}
const topology = `<div class="grid three">${CATEGORIES.filter((category) => categoryCounts.has(category.id)).map((category) => `<div class="stat"><b>${categoryCounts.get(category.id)}</b><span>${esc(category.label)}<br>${esc(category.hint)}</span></div>`).join("")}</div>`;
const quickstartRows = QUICKSTART.map((entry) => `<tr><td class="path">${esc(entry.cmd)}</td><td class="small muted">${esc(entry.cwd)}</td><td>${esc(entry.note)}</td></tr>`).join("");
const contracts = CONTRACT_CHAPTERS.map((contract) => `<div class="card" id="${contract.id}"><h3>${esc(contract.title)}</h3>${contract.body.map((line) => `<p>${esc(line)}</p>`).join("")}</div>`).join("");
const chapterById = new Map(model.chapters.map((chapter) => [chapter.id, chapter]));
const chapterGroups = [];
for (const category of CATEGORIES) {
const chapters = model.chapters.filter((chapter) => chapter.categoryId === category.id);
if (!chapters.length) continue;
chapterGroups.push(`<h3>${esc(category.label)} <span class="muted small">${chapters.length}</span></h3>${chapters.map((chapter) => renderChapter(chapter, chapterById)).join("")}`);
}
const html = `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web FreeCAD 工具使用手册</title>
<meta name="description" content="项目全部工具脚本的分类索引与核心工具详细用法。由 tools/build-tools-manual.mjs 生成。">
<link rel="icon" href="data:,">
<style>${CSS}</style>
</head>
<body>
<a class="skip" href="#overview">跳到正文</a>
<header class="top">
<div class="brand">Web FreeCAD 工具手册<small>tools · web/tools</small></div>
<button type="button" id="drawer-toggle" aria-label="打开目录">目录</button>
<div class="search-wrap">
<input id="search" type="search" placeholder="搜索工具、路径、环境变量…(按 / 聚焦)" aria-label="搜索工具">
<div id="search-results" role="listbox" aria-label="搜索结果"></div>
</div>
</header>
<div class="shell">
${sidebar(model)}
<main>
<section id="overview">
<h1>Web FreeCAD 工具使用手册</h1>
<p class="lead">本页覆盖 <code>tools/</code> 与 <code>web/tools/</code> 下的全部脚本:每个工具的功能、所在位置与用法。约 ${stats.files} 个源文件归并为 ${stats.families} 个同族条目与 ${stats.singles} 个单列条目,另有 ${stats.directories} 个目录型记录;其中 ${model.chapters.length} 个核心工具有手写详解。</p>
<div class="grid two">
<div class="card"><h3>怎么读</h3><p>先看<strong>快速开始</strong>拿到最常用命令;需要具体工具时用顶部搜索或<strong>全量索引</strong>按分类/角色过滤;核心工具直接看<strong>核心工具详解</strong>。</p></div>
<div class="card"><h3>徽标含义</h3><p><span class="badge declared">源码注释</span> 来自文件头注释、docstring 或严格是 npm 脚本声明;<span class="badge inferred">族模板(推断)</span> / <span class="badge inferred">命名推断</span> 表示源码未声明,只能按同族或命名推断——使用前请读源码确认。</p></div>
</div>
<div class="warnbox"><strong>生成器从不执行任何工具。</strong>所有“用法”都来自静态解析:头注释、argparse、Python docstring、npm scripts。凡标为推断的条目,参数以源码为准。</div>
<p class="small muted">生成器:<code>tools/build-tools-manual.mjs</code>(模块在 <code>tools/tools-manual/</code>)。页面为单文件自包含,可离线打开。</p>
</section>
<section id="quickstart">
<h2>快速开始</h2>
<div class="table-scroll"><table><thead><tr><th>命令</th><th>工作目录</th><th>说明</th></tr></thead><tbody>${quickstartRows}</tbody></table></div>
<div class="note"><code>&lt;repo&gt;</code> = <code>/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD</code>。路径含空格,shell 中必须整体加引号。</div>
</section>
<section id="contracts">
<h2>环境契约</h2>
<p>跨工具共享的前置条件。任何一条不满足时,先补前置,再执行产品断言。</p>
${contracts}
</section>
<section id="topology">
<h2>工具全景</h2>
<p>同一目录里既有 CLI,也有被导入的库和生成的数据表。判定规则:有 shebang / <code>process.argv</code> / <code>__main__</code> / argparse 视为 CLI 候选,再按 import 图区分“CLI + 库”与“纯库”;两者都没有的标为“未验证”。</p>
${topology}
<p class="small muted">族模型:同族脚本只差模块名或变体后缀(smoke/gate/probe/…),索引里折叠为一行,展开可见全部成员。当前 ${stats.families} 个族覆盖 ${model.families.reduce((sum, family) => sum + family.count, 0)} 个文件。</p>
</section>
<section id="core">
<h2>核心工具详解</h2>
<p>每个章节固定回答三件事:<strong>功能</strong>、<strong>位置</strong>、<strong>怎么用</strong>。命令均为可直接复制执行的形式。</p>
${chapterGroups.join("")}
</section>
<section id="inventory">
<h2>全量索引</h2>
<p class="small muted">按分类与名称排序;族与目录型记录可展开查看成员文件。表格只渲染一次,过滤在前端完成。</p>
<div class="toolbar">
<select id="cat-filter" aria-label="按分类过滤">
<option value="">全部分类</option>
${CATEGORIES.map((category) => `<option value="${category.id}">${esc(category.label)}</option>`).join("")}
</select>
<input id="text-filter" type="search" placeholder="按名称/路径/用途过滤" aria-label="按文本过滤">
<label><input id="core-only" type="checkbox"> 只看核心工具(有手写详解的 ${model.chapters.length} 个)</label>
<span id="visible-count" aria-live="polite"></span>
</div>
<div class="table-scroll"><table id="inventory-table"><thead><tr><th>工具 / 族</th><th>分类</th><th>角色</th><th>用途</th><th>用法</th></tr></thead><tbody>${renderRecordRows(model)}</tbody></table></div>
</section>
<section id="npm">
<h2>npm scripts 目录</h2>
<p>仓库里最稳定的命令契约:下列脚本是“可以给人直接输入”的入口,其余工具多为内部调用。</p>
${renderNpmTable(model.npmCatalog)}
</section>
<section id="env">
<h2>环境变量字典</h2>
<p>约 400 个脚本没有任何参数,行为由环境变量决定。已知变量附中文说明;未知变量给出引用次数与样例工具。</p>
${renderEnvTable(model.envUsage)}
</section>
<section id="troubleshooting">
<h2>排错</h2>
<div class="card"><h3>疑似产品失败,其实是前置失败</h3><p>日志小于约 1KB 且含 <code>MODULE_NOT_FOUND</code> / <code>Cannot find module</code> / <code>No such file or directory</code> 时,判为前置失败:检查工作目录、dist 是否构建、kernel 资产是否同步、Chrome 与 <code>DISPLAY</code> 是否可用。</p></div>
<div class="card"><h3>浏览器工具一律超时</h3><p>依次检查:<code>DISPLAY=:1</code> 是否存在;<code>/usr/bin/google-chrome</code> 是否可执行;是否需要 <code>npx vite build</code> 重新生成 dist;<code>web/public/kernel</code> 是否同步。</p></div>
<div class="card"><h3>面板不滚动 / 三维视口被挤出</h3><p>先用 <code>tools/layout-probe.mjs</code> 定位是页面未锁定、缺少 <code>.pane-scroll</code>,还是模块任务面板参与了文档流;再改 <code>web/src/panel-scroll.css</code> 或 <code>workbench-shell.tsx</code> 的 <code>.module-task-dock</code> 包装范围。</p></div>
<div class="card"><h3>导出报 glTF writer is unavailable</h3><p>OCCT 以 <code>USE_RAPIDJSON=OFF</code> 构建过。运行 <code>bash tools/rebuild-occt-rwgltf-rapidjson.sh</code> 恢复,然后重建 dist。</p></div>
<div class="card"><h3>改了 web/src 但测试没变化</h3><p>测试跑的是 <code>web/dist</code>,不是源码。先 <code>cd web &amp;&amp; npx vite build</code>,再跑套件。</p></div>
</section>
<section id="maintenance">
<h2>再生成与校验</h2>
<p>本页由生成器产出,请勿手改。改完工具或手写章节后:</p>
${pre("cd \"<repo>\" && node tools/build-tools-manual.mjs", "重新生成")}
${pre("cd \"<repo>\" && node tools/build-tools-manual.mjs --check", "幂等检查(过期 exit 1)")}
${pre("cd \"<repo>\" && node tools/build-tools-manual.mjs --verify", "路径 / 锚点 / 自包含 / 体积断言")}
${pre("cd \"<repo>/web\" && DISPLAY=:1 npm run check:tools-manual", "Playwright 页面与交互检查")}
<p class="small muted">手写章节在 <code>tools/tools-manual/chapters.mjs</code>;分类与族规则在 <code>config.mjs</code>;提取规则在 <code>extract.mjs</code>。</p>
</section>
<section id="appendix">
<h2>附录</h2>
<h3>统计</h3>
<div class="grid three">
<div class="stat"><b>${stats.files}</b><span>扫描源文件</span></div>
<div class="stat"><b>${stats.rows}</b><span>索引行</span></div>
<div class="stat"><b>${stats.families}</b><span>同族条目</span></div>
<div class="stat"><b>${stats.withPurpose}</b><span>有源码用途声明</span></div>
<div class="stat"><b>${model.chapters.length}</b><span>手写详解章节</span></div>
<div class="stat"><b>${model.envUsage.size}</b><span>扫描到的环境变量</span></div>
</div>
<h3>排除项</h3>
<p class="small">不收录:<code>__pycache__</code>、<code>*.pyc</code>、<code>*.bak</code>、<code>*.inc.mjs</code>(片段)、<code>mcp/batch-*.json</code>(夹具)、<code>node_modules</code>、<code>dist</code>、<code>out</code>,以及以点开头的文件。生成契约、夹具、垫片与课程内容目录折叠为目录型记录。</p>
<h3>来源标记</h3>
<p class="small">用途与用法只来自静态解析,按优先级取第一条命中:显式 <code>Purpose:</code>/<code>Usage:</code> → npm 脚本 → Python docstring → JS/TS 头注释 → shell 头注释 → 族模板 → 命名兜底。推断项永远带徽标。</p>
<footer>生成器不写入时间戳或提交号,保证 <code>--check</code> 字节稳定。手写内容与代码一起评审。</footer>
</section>
</main>
</div>
<script>window.__SEARCH_INDEX__ = ${JSON.stringify(buildSearchIndex(model)).replace(/</g, "\\u003c")};</script>
<script>${CLIENT_JS}</script>
</body>
</html>
`;
return html;
}

158
tools/tools-manual/scan.mjs Normal file
View File

@@ -0,0 +1,158 @@
/**
* Directory scan for tools/build-tools-manual.mjs.
*
* Reads only the first HEAD_BYTES of each source file: the manual documents
* tool Function/Location/Usage, which lives in headers and docstrings, and
* full reads of ~1600 files would be needless I/O.
*
* Never executes anything: several tools write into docs/current/ or append
* logs when invoked (tools/emcc-compat-bin/emcc does exactly that).
*/
import fs from "node:fs";
import path from "node:path";
import { HEAD_BYTES, READ_EXTS, SCAN_ROOTS, SKIP_DIRS, SKIP_FILE, DIRECTORY_SUMMARIES } from "./config.mjs";
function readHead(absPath, bytes) {
const fd = fs.openSync(absPath, "r");
try {
const size = Math.min(bytes, fs.fstatSync(fd).size);
const buffer = Buffer.alloc(size);
fs.readSync(fd, buffer, 0, size, 0);
return buffer.toString("utf8");
} finally {
fs.closeSync(fd);
}
}
function walk(root, relPath, recursive, out) {
const absDir = path.join(root, relPath);
let entries;
try {
entries = fs.readdirSync(absDir, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
for (const entry of entries) {
const rel = `${relPath}/${entry.name}`;
if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
if (!recursive || SKIP_DIRS.has(entry.name)) continue;
if (DIRECTORY_SUMMARIES.some((d) => d.relPath === rel)) continue;
walk(root, rel, recursive, out);
continue;
}
if (!entry.isFile()) continue;
if (SKIP_FILE.test(entry.name)) continue;
const ext = path.extname(entry.name).toLowerCase();
const abs = path.join(root, rel);
let bytes = 0;
try {
bytes = fs.statSync(abs).size;
} catch {
continue;
}
out.push({
relPath: rel,
name: entry.name,
ext,
bytes,
head: READ_EXTS.has(ext) ? readHead(abs, HEAD_BYTES) : "",
});
}
}
function countDirectoryFiles(root, relPath) {
const names = [];
const stack = [relPath];
while (stack.length) {
const current = stack.pop();
let entries = [];
try {
entries = fs.readdirSync(path.join(root, current), { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
if (!SKIP_DIRS.has(entry.name)) stack.push(`${current}/${entry.name}`);
continue;
}
if (SKIP_FILE.test(entry.name)) continue;
names.push(`${current}/${entry.name}`);
}
}
names.sort();
return names;
}
/** Map npm script name -> the tool paths its command mentions. */
function readNpmScripts(root) {
const scripts = new Map(); // relPath -> [scriptName]
const files = ["package.json", "web/package.json"];
for (const rel of files) {
let pkg;
try {
pkg = JSON.parse(fs.readFileSync(path.join(root, rel), "utf8"));
} catch {
continue;
}
for (const [name, command] of Object.entries(pkg.scripts ?? {})) {
const matches = String(command).matchAll(/(?:^|[\s"'=])((?:\.\.\/)?(?:tools|web\/tools)\/[\w./-]+\.(?:mjs|js|ts|py|sh))/g);
for (const match of matches) {
let tool = match[1].replace(/^\.\.\//, "");
if (!tool.startsWith("tools/")) tool = `tools/${tool}`;
if (!scripts.has(tool)) scripts.set(tool, []);
const list = scripts.get(tool);
if (!list.includes(name)) list.push(name);
}
}
}
return scripts;
}
/**
* Build a reverse-import map: module path -> number of files importing it.
* Only relative ESM imports and CommonJS require() are traced; Python local
* imports are left alone (CLI markers are a better signal there).
*/
function buildImportGraph(files) {
const byRel = new Map(files.map((file) => [file.relPath, file]));
const importedBy = new Map();
for (const file of files) {
if (!file.head || !/\.(mjs|js|ts|tsx)$/.test(file.ext)) continue;
const dir = path.posix.dirname(file.relPath);
const specs = new Set();
for (const match of file.head.matchAll(/(?:from\s+|import\s*\(?\s*|require\s*\(\s*)["'](\.{1,2}\/[^"']+)["']/g)) {
specs.add(match[1]);
}
for (const spec of specs) {
const resolved = path.posix.normalize(path.posix.join(dir, spec));
for (const candidate of [resolved, `${resolved}.mjs`, `${resolved}.js`, `${resolved}.ts`, `${resolved}/index.mjs`]) {
if (byRel.has(candidate)) {
importedBy.set(candidate, (importedBy.get(candidate) ?? 0) + 1);
break;
}
}
}
}
return importedBy;
}
export function scan(root) {
const files = [];
for (const scanRoot of SCAN_ROOTS) walk(root, scanRoot.relPath, scanRoot.recursive, files);
// A file can be reached twice (web/tools top level + manual/ recursion).
const unique = [...new Map(files.map((file) => [file.relPath, file])).values()];
unique.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
const directories = DIRECTORY_SUMMARIES.map((entry) => {
const members = countDirectoryFiles(root, entry.relPath);
return { ...entry, members, count: members.length };
}).filter((entry) => entry.count > 0);
const npmScripts = readNpmScripts(root);
const importedBy = buildImportGraph(unique);
return { files: unique, directories, npmScripts, importedBy };
}

View File

@@ -0,0 +1,149 @@
/**
* Post-render assertions for docs/current/tools-manual/index.html.
*
* Everything here is checked against the freshly built model + HTML string, so
* `--check` (byte compare) and `--verify` (semantic) stay independent: a stale
* file passes --verify and fails --check, which is the intended split.
*/
import fs from "node:fs";
import path from "node:path";
import { CATEGORIES } from "./config.mjs";
const SIZE_FAIL = 3 * 1024 * 1024;
const SIZE_WARN = 1.5 * 1024 * 1024;
function collectIds(html) {
const ids = [];
for (const match of html.matchAll(/\sid="([^"]+)"/g)) ids.push(match[1]);
return ids;
}
function readPackageScripts(root, rel) {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(root, rel), "utf8"));
return pkg.scripts ?? {};
} catch {
return {};
}
}
/** Extract `window.__SEARCH_INDEX__ = [ ... ];` without eval. */
function readSearchIndex(html) {
const marker = "window.__SEARCH_INDEX__ = ";
const start = html.indexOf(marker);
if (start < 0) return null;
const end = html.indexOf(";</script>", start);
if (end < 0) return null;
try {
return JSON.parse(html.slice(start + marker.length, end));
} catch {
return null;
}
}
export function verify({ root, html, model }) {
const errors = [];
const warnings = [];
const fail = (message) => errors.push(message);
const warn = (message) => warnings.push(message);
// 1. Every documented path must exist on disk.
for (const chapter of model.chapters) {
if (!fs.existsSync(path.join(root, chapter.path))) fail(`章节路径不存在:${chapter.path}`);
}
for (const directory of model.directories) {
if (!fs.existsSync(path.join(root, directory.relPath))) fail(`目录记录不存在:${directory.relPath}`);
}
// 2. Anchors: present, unique, and reachable from the search index.
const ids = collectIds(html);
const idSet = new Set(ids);
const duplicates = [...new Set(ids.filter((id, index) => ids.indexOf(id) !== index))];
if (duplicates.length) fail(`锚点重复:${duplicates.slice(0, 8).join(", ")}`);
const expectedAnchors = [
...model.chapters.map((chapter) => chapter.anchor),
...model.families.map((family) => family.anchor),
...model.records.filter((record) => !record.familyId).map((record) => record.anchor),
...model.directories.map((directory) => directory.anchor),
];
const missing = expectedAnchors.filter((anchor) => !idSet.has(anchor));
if (missing.length) fail(`缺少锚点 ${missing.length} 个,例如:${missing.slice(0, 8).join(", ")}`);
for (const section of ["overview", "quickstart", "contracts", "topology", "core", "inventory", "npm", "env", "troubleshooting", "maintenance", "appendix"]) {
if (!idSet.has(section)) fail(`缺少章节锚点:#${section}`);
}
// 3. Counts must agree between scan, model and markup.
const rowCount = (html.match(/data-cat="/g) ?? []).length;
if (rowCount !== model.stats.rows) fail(`索引行数 ${rowCount} 与模型统计 ${model.stats.rows} 不一致`);
if (model.chapters.length < 30) fail(`手写章节仅 ${model.chapters.length} 个,低于计划下限 30`);
if (model.stats.files < 1000) warn(`扫描文件数仅 ${model.stats.files},检查 SCAN_ROOTS 是否漏目录`);
for (const category of CATEGORIES) {
const declared = model.stats.byCategory?.[category.id] ?? 0;
if (!declared) continue;
const rendered = (html.match(new RegExp(`data-cat="${category.id}"`, "g")) ?? []).length;
if (rendered !== declared) fail(`分类 ${category.id} 行数 ${rendered} 与统计 ${declared} 不一致`);
}
// 4. Search index coverage: every file name must be findable by substring.
const index = readSearchIndex(html);
if (!index) {
fail("未找到或无法解析 window.__SEARCH_INDEX__");
} else {
const minimum = model.chapters.length + model.families.length
+ model.records.filter((record) => !record.familyId).length + model.directories.length;
if (index.length < minimum) fail(`搜索索引 ${index.length} 条,少于应有 ${minimum} 条`);
const hrefs = new Set(index.map((entry) => String(entry[1]).slice(1)));
const unreachable = model.chapters.filter((chapter) => !hrefs.has(chapter.anchor));
if (unreachable.length) fail(`章节未进入搜索索引:${unreachable.slice(0, 5).map((c) => c.id).join(", ")}`);
for (const entry of index) {
if (!Array.isArray(entry) || entry.length < 3) {
fail("搜索索引条目结构异常(应为 [标题, 链接, 分类, 关键词])");
break;
}
}
}
// 5. Self-containment: no external or linked assets.
for (const [pattern, label] of [
[/<script[^>]+\ssrc=/i, "外部 <script src>"],
[/<link[^>]+rel=["']?stylesheet/i, "外部样式表 <link rel=stylesheet>"],
[/@import/i, "CSS @import"],
[/https?:\/\/(?!(?:localhost|127\.0\.0\.1)\b)/i, "http(s):// 外部引用"],
[/<img\b/i, "图片引用"],
]) {
if (pattern.test(html)) fail(`页面不是自包含:含${label}`);
}
// 6. Template leakage.
for (const [pattern, label] of [
[/\[object Object\]/, "[object Object]"],
[/\bundefined\b/, "undefined"],
[/\bNaN\b/, "NaN"],
[/\$\{/, "未替换的模板占位符 ${"],
]) {
if (pattern.test(html)) fail(`输出含模板泄漏:${label}`);
}
// 7. npm table rows must exist in a real package.json.
const rootScripts = readPackageScripts(root, "package.json");
const webScripts = readPackageScripts(root, "web/package.json");
for (const entry of model.npmCatalog) {
const table = entry.cwd === "web" ? webScripts : rootScripts;
if (!Object.prototype.hasOwnProperty.call(table, entry.name)) fail(`npm 脚本不存在:${entry.cwd}/package.json → ${entry.name}`);
}
// 8. Size budget.
const bytes = Buffer.byteLength(html);
if (bytes > SIZE_FAIL) fail(`页面体积 ${(bytes / 1048576).toFixed(2)} MB,超过 3 MB 上限`);
else if (bytes > SIZE_WARN) warn(`页面体积 ${(bytes / 1048576).toFixed(2)} MB,超过 1.5 MB 建议值`);
// 9. Environment dictionary sanity: every known variable should be described.
for (const name of model.envUsage.keys()) {
if (!/^[A-Z][A-Z0-9_]*$/.test(name)) warn(`环境变量名可疑:${name}`);
}
return { ok: errors.length === 0, errors, warnings, bytes, rows: rowCount, searchEntries: index?.length ?? 0 };
}