#!/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
]
*
* 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 ]");
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);
});