Files
FreeCADWasmDev/tools/reducer/create-part.mjs
wangdequan b876ad5742 feat(reducer): 二级减速器有头创建工具包与初学者教学
- tools/reducer:目录/前置/单件/批量/装配/自测,复用 cad-ui-rebuild 引擎
- 教学控制台新增「二级减速器」分组:23 件逐件课 + 装配课 + 环境课(job kind reducer-part / reducer-assembly)
- web/teaching/reducer-toolkit.html 初学者配套页(生成物)+ Playwright 双视口门禁
- 首页补工具入口;工具手册随 npm 脚本变更重生成

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 07:31:24 +08:00

175 lines
7.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* Purpose: 在真实界面里重建二级减速器的一个零件(有头 Chrome)。
*
* 本工具只做三件事:校验前置、定位该零件的界面步骤、调用既有引擎
* web/tools/cad-ui-rebuild/drive.mjs 逐步点击,最后把结果归一化成一份报告。
* 步骤数据、点击逻辑与体积比对全部复用已有实现,这里不复制。
*
* Usage:
* node tools/reducer/create-part.mjs P06
* node tools/reducer/create-part.mjs Bearing6206_Inner --slow
* node tools/reducer/create-part.mjs P21 --dry # 只检查前置与步骤
* node tools/reducer/create-part.mjs P06 --out <dir> # 报告目录
*
* Exit: 0 通过 / 1 界面上建出的体积与构建记录不一致(产品问题)/ 2 前置缺失
*/
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { REPO_ROOT, PROJECT_DIR, find, parts } from "./catalog.mjs";
import { ensureOrigin, preflight } from "./preflight.mjs";
const DRIVE = path.join(REPO_ROOT, "web/tools/cad-ui-rebuild/drive.mjs");
const RUN_FILE = (document) => path.join(PROJECT_DIR, "out/ui-run", `${document}.json`);
function parseArgs(argv) {
const options = { key: null, headed: true, slow: false, dry: false, serve: true, out: null, json: false };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--headed") options.headed = true;
else if (arg === "--headless") options.headed = false;
else if (arg === "--slow") options.slow = true;
else if (arg === "--dry") options.dry = true;
else if (arg === "--no-serve") options.serve = false;
else if (arg === "--json") options.json = true;
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? "");
else if (arg === "--help" || arg === "-h") {
console.log("node tools/reducer/create-part.mjs <P01|Document> [--headed|--headless] [--slow] [--dry] [--no-serve] [--out <dir>] [--json]");
process.exit(0);
} else if (arg.startsWith("--")) {
console.error(`未知参数:${arg}`);
process.exit(2);
} else if (!options.key) options.key = arg;
else {
console.error(`多余的参数:${arg}`);
process.exit(2);
}
}
if (!options.key) {
console.error("用法:node tools/reducer/create-part.mjs <P01|Document> [--slow] [--dry]");
process.exit(2);
}
return options;
}
function runDir(options, part) {
const root = options.out ?? path.join(REPO_ROOT, "docs/current/reducer-toolkit/runs");
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
return path.join(root, `${stamp}-${part.id}`);
}
function line(text) {
process.stdout.write(`${text}\n`);
}
/** Spawn the shared driver and forward its stdout/stderr unchanged. */
function drive(part, options, projectDir) {
const argv = [process.execPath, DRIVE, "--project", projectDir, part.id];
if (options.headed) argv.push("--headed");
if (options.slow) argv.push("--slow");
return new Promise((resolve) => {
const child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, stdio: ["ignore", "pipe", "pipe"] });
child.stdout.on("data", (chunk) => process.stdout.write(chunk));
child.stderr.on("data", (chunk) => process.stderr.write(chunk));
child.on("error", (error) => resolve({ code: -1, error }));
child.on("close", (code) => resolve({ code: code ?? -1 }));
});
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const part = find(options.key);
const report = await preflight();
if (options.dry) {
line(`零件 ${part.id} ${part.document}(${part.title}):${part.steps} 步,记录体积 ${part.volume ?? "—"}`);
for (const check of report.checks) line(` ${check.ok ? "✓" : "✗"} ${check.id}: ${check.detail}`);
line(report.ok ? "前置全部满足(dry run,未启动浏览器)" : "前置未满足(dry run)");
process.exit(report.ok ? 0 : 2);
}
if (!report.ok) {
for (const check of report.checks.filter((item) => !item.ok && item.id !== "app")) {
console.error(`前置缺失 ${check.id}: ${check.detail} → ${check.fix}`);
}
console.error("未启动浏览器(前置失败不是产品失败)。可先跑 --dry 查看全部检查。");
process.exit(2);
}
if (!part.reconstructable) {
console.error(`前置缺失:${part.document} 缺少界面步骤或构建记录,先运行 node web/tools/reducer-parts-course/build-ui-steps.mjs`);
process.exit(2);
}
line(`零件 ${part.id} ${part.document}(${part.title}):${part.steps} 步,记录体积 ${part.volume ?? "—"}`);
let origin = null;
if (options.serve) {
try {
origin = await ensureOrigin(report.origin);
line(origin.started ? `已为 ${origin.origin} 启动静态服务` : `复用已在运行的应用入口 ${origin.origin}`);
} catch (error) {
console.error(`前置缺失:${error.message}`);
process.exit(2);
}
}
const startedAt = Date.now();
let result;
try {
result = await drive(part, options, origin?.projectDir ?? PROJECT_DIR);
} finally {
await origin?.close();
}
const uiRun = (() => {
try {
return JSON.parse(fs.readFileSync(RUN_FILE(part.document), "utf8"));
} catch {
return null;
}
})();
const dir = options.out ?? runDir(options, part);
fs.mkdirSync(dir, { recursive: true });
const verdict = !uiRun ? "run_fail"
: uiRun.failed > 0 || uiRun.volumeMatches === false ? "product_fail"
: "pass";
const summary = {
schema: "freecad-web/reducer-toolkit/part/v1",
part: { id: part.id, document: part.document, title: part.title, group: part.group },
steps: uiRun?.steps ?? part.steps,
stepsTotal: uiRun?.stepsTotal ?? part.steps,
failed: uiRun?.failed ?? null,
volume: uiRun?.volume ?? null,
expectedVolume: uiRun?.expected ?? part.volume,
relativeError: uiRun?.relativeError ?? null,
volumeMatches: uiRun?.volumeMatches ?? null,
seconds: uiRun?.seconds ?? Math.round((Date.now() - startedAt) / 1000),
pageErrors: uiRun?.pageErrors ?? [],
stillsDir: part.stillsDir,
driverExitCode: result.code,
verdict,
finishedAt: new Date().toISOString(),
};
fs.writeFileSync(path.join(dir, "report.json"), JSON.stringify(summary, null, 2));
if (options.json) line(JSON.stringify(summary));
else {
line(`零件 ${part.id}: ${verdict}(${summary.steps}/${summary.stepsTotal} 步,体积 ${summary.volume ?? "—"},${summary.seconds}s)`);
line(`报告:${path.relative(REPO_ROOT, path.join(dir, "report.json"))}`);
if (summary.stillsDir) line(`截图:${summary.stillsDir}`);
}
if (verdict === "pass") process.exit(0);
if (verdict === "product_fail") {
console.error(`体积不一致:界面 ${summary.volume} / 记录 ${summary.expectedVolume}(相对误差 ${summary.relativeError})`);
process.exit(1);
}
console.error("驱动未产出界面运行报告,按前置/运行失败处理。");
process.exit(2);
}
main().catch((error) => {
console.error(`失败:${error?.message ?? error}`);
process.exit(error?.code === "E_PART" ? 2 : 1);
});