Files
FreeCADWasmDev/tools/carrier/create-part.mjs
wangdequan 87b2a6cb8a feat(carrier): 航空母舰 PartDesign 有头创建工具包与初学者教学
- 新数据链 web/teaching/cases/carrier-partdesign:20 件零件(spec.json 唯一来源)、
  内核建造器 parts/*.mjs、traces/FCStd/replay 全量产物;装配 20 插入 + 19 关节。
- 工具包 tools/carrier:catalog / preflight / create-part / create-assembly /
  create-all / list / self-test / README,按零件与装配拆分为独立工具。
- 共享驱动扩展 web/tools/cad-ui-rebuild:Loft/Pipe/Hole/Fillet/Chamfer/Mirrored/
  LinearPattern 交互,Reversed 复选框补齐;装配 saveAssemblyBundle 先 Accept 再保存。
- 教学:lessons.mjs 新增 carrier 组(环境课 + 20 件 + 装配),suite-runner 增加
  carrier-part/carrier-assembly,生成 carrier-toolkit.html 并接入 index 与控制台证据。

验证:20 件 210 步全部有头通过(P05 修复后 39640 m³;P06 回归 8/8);
装配 20/20 插入、19/19 关节、20 组件 0 畸形、0 mismatch;check:carrier、
check:reducer、check-console --live 全绿。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 18:46:27 +08:00

202 lines
8.2 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/carrier/create-part.mjs P02
* node tools/carrier/create-part.mjs CarrierIsland --slow
* node tools/carrier/create-part.mjs P01 --dry # 只检查前置与步骤
* node tools/carrier/create-part.mjs P02 --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 } 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/carrier/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/carrier/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/carrier-partdesign-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);
// Only this part's steps/record matter here; the rest of the catalog is the
// `create-all` / `self-test` concern.
const report = await preflight({ part });
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)");
// A caller that named an output directory (the teaching console always
// does) gets a report even from a dry run, so the job folds on structured
// data instead of having to parse the log text for a verdict.
if (options.out) {
fs.mkdirSync(options.out, { recursive: true });
fs.writeFileSync(path.join(options.out, "report.json"), JSON.stringify({
schema: "freecad-web/carrier-toolkit/part/v1",
part: {
id: part.id, document: part.document, title: part.title,
system: part.system, systemLabel: part.systemLabel, featureTypes: part.featureTypes,
},
dry: true,
steps: part.steps,
stepsTotal: part.steps,
expectedVolume: part.volume,
checks: report.checks,
seconds: 0,
verdict: report.ok ? "pass" : "precondition_fail",
finishedAt: new Date().toISOString(),
}, null, 2));
}
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/cad-ui-rebuild/build-steps.mjs --project web/tools/carrier-partdesign-course ${part.id}`);
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/carrier-toolkit/part/v1",
part: {
id: part.id, document: part.document, title: part.title,
system: part.system, systemLabel: part.systemLabel, featureTypes: part.featureTypes,
},
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);
});