#!/usr/bin/env node
/**
* Purpose: 在真实界面里把 23 个零件装配成二级减速器(有头 Chrome)。
*
* 复用 web/tools/cad-ui-rebuild/assemble.mjs:新建装配文档、逐个插入链接、
* 按构建记录的位置与旋转落位。本工具只补前置检查与归一化报告。
*
* Usage:
* node tools/reducer/create-assembly.mjs --dry
* node tools/reducer/create-assembly.mjs
* node tools/reducer/create-assembly.mjs --out
*
* 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, projectManifest } from "./catalog.mjs";
import { ensureOrigin, preflight } from "./preflight.mjs";
const ASSEMBLE = path.join(REPO_ROOT, "web/tools/cad-ui-rebuild/assemble.mjs");
function parseArgs(argv) {
const options = { headed: true, 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 === "--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-assembly.mjs [--headed|--headless] [--dry] [--no-serve] [--out ] [--json]");
process.exit(0);
} else {
console.error(`未知参数:${arg}`);
process.exit(2);
}
}
return options;
}
function stamp() {
return new Date().toISOString().replace(/[:.]/g, "-");
}
function runAssembly(options, projectDir) {
const argv = [process.execPath, ASSEMBLE, "--project", projectDir];
if (options.headed) argv.push("--headed");
if (options.dry) argv.push("--dry");
return new Promise((resolve) => {
const child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, stdio: ["ignore", "pipe", "pipe"] });
let tail = "";
child.stdout.on("data", (chunk) => { process.stdout.write(chunk); tail = (tail + chunk.toString("utf8")).slice(-4000); });
child.stderr.on("data", (chunk) => process.stderr.write(chunk));
child.on("error", (error) => resolve({ code: -1, error, tail }));
child.on("close", (code) => resolve({ code: code ?? -1, tail }));
});
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const manifest = projectManifest();
const report = await preflight();
if (options.dry) {
const assembly = manifest.assembly ?? {};
console.log(`装配:${assembly.document ?? "SecondaryReducer"}(接地 ${assembly.groundDocument ?? "—"})`);
for (const check of report.checks) console.log(` ${check.ok ? "✓" : "✗"} ${check.id}: ${check.detail}`);
console.log(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("未启动浏览器(前置失败不是产品失败)。");
process.exit(2);
}
let origin = null;
if (options.serve) {
try {
origin = await ensureOrigin(report.origin);
console.log(origin.started ? `已为 ${origin.origin} 启动静态服务` : `复用已在运行的应用入口 ${origin.origin}`);
} catch (error) {
console.error(`前置缺失:${error.message}`);
process.exit(2);
}
}
const startedAt = Date.now();
let result;
try {
result = await runAssembly(options, origin?.projectDir ?? PROJECT_DIR);
} finally {
await origin?.close();
}
const document = manifest.assembly?.document ?? "SecondaryReducer";
const uiReportFile = path.join(PROJECT_DIR, "out/ui-run", `${document}-assembly.json`);
const uiReport = (() => {
try {
return JSON.parse(fs.readFileSync(uiReportFile, "utf8"));
} catch {
return null;
}
})();
const verdict = !uiReport ? "run_fail"
: uiReport.fatal || uiReport.mismatches?.length ? "product_fail"
: uiReport.inserted < (uiReport.expected?.inserts ?? Infinity) ? "product_fail"
: "pass";
const dir = options.out ?? path.join(REPO_ROOT, "docs/current/reducer-toolkit/runs", `${stamp()}-assembly`);
fs.mkdirSync(dir, { recursive: true });
const summary = {
schema: "freecad-web/reducer-toolkit/assembly/v1",
document,
groundDocument: uiReport?.groundDocument ?? manifest.assembly?.groundDocument ?? null,
expected: uiReport?.expected ?? null,
inserted: uiReport?.inserted ?? null,
rotated: uiReport?.rotated ?? null,
mismatches: uiReport?.mismatches?.length ?? null,
seconds: uiReport?.seconds ?? Math.round((Date.now() - startedAt) / 1000),
fatal: uiReport?.fatal ?? null,
pageErrors: uiReport?.pageErrors ?? [],
driverExitCode: result.code,
verdict,
finishedAt: new Date().toISOString(),
};
fs.writeFileSync(path.join(dir, "report.json"), JSON.stringify(summary, null, 2));
if (options.json) console.log(JSON.stringify(summary));
else {
console.log(`装配 ${document}: ${verdict}(插入 ${summary.inserted}/${summary.expected?.inserts ?? "?"},失配 ${summary.mismatches ?? "—"},${summary.seconds}s)`);
console.log(`报告:${path.relative(REPO_ROOT, path.join(dir, "report.json"))}`);
}
process.exit(verdict === "pass" ? 0 : verdict === "product_fail" ? 1 : 2);
}
main().catch((error) => {
console.error(`失败:${error?.message ?? error}`);
process.exit(1);
});