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>
This commit is contained in:
91
tools/carrier/README.md
Normal file
91
tools/carrier/README.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# 航空母舰 PartDesign 创建工具包
|
||||
|
||||
按「一件零件一个工具、装配一个工具」拆分的有头创建工具。工具本身只做编排与判定,
|
||||
真正的界面点击、步骤数据与体积比对全部复用既有实现:
|
||||
|
||||
- `web/tools/cad-ui-rebuild/drive.mjs` —— 在真实界面里逐步重建一个零件(本工具包的引擎)
|
||||
- `web/tools/cad-ui-rebuild/assemble.mjs` + `lib/assembly.mjs` —— 装配插入与位置校验
|
||||
- `web/teaching/cases/carrier-partdesign/` —— 20 件零件的构建记录与回放
|
||||
(`spec.json` 是零件唯一来源)
|
||||
- `web/tools/carrier-partdesign-course/` —— 界面步骤、界面运行报告与逐步截图
|
||||
|
||||
## 工具一览
|
||||
|
||||
| 工具 | 作用 |
|
||||
| --- | --- |
|
||||
| `list.mjs` | 列出零件(按系统分组)、步数、体积与特征类型 |
|
||||
| `self-test.mjs` | 无浏览器的数据契约自测(spec/project/分组/解析/ui-steps↔replay) |
|
||||
| `preflight.mjs` | 八项前置检查(dist、kernel、chrome、display、playwright、engine、parts、app) |
|
||||
| `create-part.mjs` | 重建**一个**零件:前置检查 → 调用引擎 → 归一化报告 |
|
||||
| `create-all.mjs` | 串行重建多个零件(按分组、列表或全部)并汇总 |
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
# 清单与自测(无浏览器)
|
||||
node tools/carrier/list.mjs
|
||||
node tools/carrier/list.mjs --group flight-deck
|
||||
node tools/carrier/self-test.mjs --json
|
||||
|
||||
# 单件:先 dry 看前置,再有头重建
|
||||
node tools/carrier/create-part.mjs P02 --dry
|
||||
node tools/carrier/create-part.mjs P02 --headed
|
||||
node tools/carrier/create-part.mjs CarrierDeck --slow --out /tmp/p02
|
||||
|
||||
# 批量
|
||||
node tools/carrier/create-all.mjs --parts P02,P03 --keep-going
|
||||
node tools/carrier/create-all.mjs --group flight-deck
|
||||
node tools/carrier/create-all.mjs --all --keep-going
|
||||
```
|
||||
|
||||
零件标识接受 id(`P02`)、Document(`CarrierDeck`),大小写不敏感;非法输入以
|
||||
`E_PART` 拒绝(退出码 2)。
|
||||
|
||||
## 退出码
|
||||
|
||||
- `0` 通过:界面步数齐全,且界面 tip 体积与构建记录一致(相对误差 < 1e-6)
|
||||
- `1` 产品失败:界面上建出的体积与记录不一致,或某一步在界面上失败
|
||||
- `2` 前置缺失 / 运行未产出报告 / 参数错误
|
||||
|
||||
**前置失败不是产品失败。** 前置不满足时不会启动浏览器,先按 `--dry` 的 `fix`
|
||||
列补缺项(常见:`npx vite build` 重建 dist、`node web/tools/cad-ui-rebuild/build-steps.mjs
|
||||
--project web/tools/carrier-partdesign-course P02` 生成界面步骤)。
|
||||
|
||||
## 一次单件运行做了什么
|
||||
|
||||
1. `preflight({ part })` 只校验**该零件**的界面步骤与构建记录;目录级检查
|
||||
(20 件是否都可重建)留给 `create-all` / `self-test`。
|
||||
2. 复用或派生静态服务入口(`project.json` 的 `appOrigin`,默认 5183)。
|
||||
3. `spawn drive.mjs --project web/tools/carrier-partdesign-course <P02>`,
|
||||
由共享驱动逐步操作界面,每步截图并读取 tip 体积。
|
||||
4. 读取 `out/ui-run/<Document>.json`,写 `docs/current/carrier-partdesign-toolkit/runs/<时间戳>-<id>/report.json`
|
||||
(schema `freecad-web/carrier-toolkit/part/v1`)。
|
||||
|
||||
界面对象名由工作台自取(`Sketch1`、`Pad1`、`Chamfer1`…),驱动逐步记录「内核名 → 界面名」
|
||||
的映射;任何引用的名字找不到就失败,不做「取最后一个选项」的兜底。
|
||||
|
||||
重特征(例如 180 条边的甲板倒角)在界面上要算几十秒;驱动在创建后等待
|
||||
「计算中…」消失且模型树多出一行,再记录新对象名。
|
||||
|
||||
## 数据位置
|
||||
|
||||
| 内容 | 位置 |
|
||||
| --- | --- |
|
||||
| 零件唯一来源 | `web/teaching/cases/carrier-partdesign/spec.json` |
|
||||
| 构建记录(replay) | `web/teaching/cases/carrier-partdesign/out/replay/<Document>.json` |
|
||||
| 界面步骤 | `web/tools/carrier-partdesign-course/out/ui-steps/<Document>.json` |
|
||||
| 界面运行报告 | `web/tools/carrier-partdesign-course/out/ui-run/<Document>.json` |
|
||||
| 逐步截图 | `web/tools/carrier-partdesign-course/ui-stills/<Pxx>/` |
|
||||
| 工具报告 | `docs/current/carrier-partdesign-toolkit/runs/` |
|
||||
|
||||
所有导出遵循 OPFS 铁律:文档与导出只落 OPFS(`freecad-exports`),只有用户显式
|
||||
「下载到本地」才写本地文件;`out/` 下的副本只是证据快照。
|
||||
|
||||
## 加一个新零件
|
||||
|
||||
1. 在 `web/teaching/cases/carrier-partdesign/parts/` 写构建器,并在 `spec.json` 登记
|
||||
(id、Document、中文名、system、dimensions、featureTypes)。
|
||||
2. `node web/teaching/cases/carrier-partdesign/build.mjs <Pxx>` 生成 FCStd、trace 与 replay。
|
||||
3. `node web/tools/cad-ui-rebuild/build-steps.mjs --project web/tools/carrier-partdesign-course <Pxx>`
|
||||
生成界面步骤。
|
||||
4. `node tools/carrier/create-part.mjs <Pxx> --headed` 重建;通过后 `self-test.mjs` 应保持全绿。
|
||||
133
tools/carrier/catalog.mjs
Normal file
133
tools/carrier/catalog.mjs
Normal file
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Canonical catalog of the 20 carrier PartDesign parts.
|
||||
*
|
||||
* Like tools/reducer/catalog.mjs, this module owns no part list of its own. The
|
||||
* single source is the case spec (one inventory for builders, toolkit and
|
||||
* teaching), joined with the three evidence trees on disk:
|
||||
* - web/teaching/cases/carrier-partdesign/out/replay/<Document>.json (build record)
|
||||
* - web/tools/carrier-partdesign-course/out/ui-steps/<Document>.json (UI steps)
|
||||
* - web/tools/carrier-partdesign-course/out/ui-run/<Document>.json (last headed run)
|
||||
*
|
||||
* A part is only offered when both replay and ui-steps exist, so `create-part`
|
||||
* can never start a browser for a part that has nothing to replay.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const REPO_ROOT = path.resolve(HERE, "../..");
|
||||
export const CASE_DIR = path.join(REPO_ROOT, "web/teaching/cases/carrier-partdesign");
|
||||
export const SPEC_FILE = path.join(CASE_DIR, "spec.json");
|
||||
export const REPLAY_DIR = path.join(CASE_DIR, "out/replay");
|
||||
export const PROJECT_DIR = path.join(REPO_ROOT, "web/tools/carrier-partdesign-course");
|
||||
export const PROJECT_FILE = path.join(PROJECT_DIR, "project.json");
|
||||
const STEPS_DIR = path.join(PROJECT_DIR, "out/ui-steps");
|
||||
const RUN_DIR = path.join(PROJECT_DIR, "out/ui-run");
|
||||
const STILLS_DIR = path.join(PROJECT_DIR, "ui-stills");
|
||||
|
||||
function readJson(file) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function spec() {
|
||||
const payload = readJson(SPEC_FILE);
|
||||
if (!payload) throw new Error(`缺少案例清单:${SPEC_FILE}`);
|
||||
return payload;
|
||||
}
|
||||
|
||||
export function projectManifest() {
|
||||
const manifest = readJson(PROJECT_FILE);
|
||||
if (!manifest) throw new Error(`缺少项目清单:${PROJECT_FILE}`);
|
||||
return manifest;
|
||||
}
|
||||
|
||||
function stepsOf(document) {
|
||||
const payload = readJson(path.join(STEPS_DIR, `${document}.json`));
|
||||
return Array.isArray(payload?.steps) ? payload.steps : null;
|
||||
}
|
||||
|
||||
function replayOf(document) {
|
||||
return readJson(path.join(REPLAY_DIR, `${document}.json`));
|
||||
}
|
||||
|
||||
function finalVolume(steps) {
|
||||
const volumes = (steps ?? []).map(step => step.volume).filter(volume => typeof volume === "number" && volume > 0);
|
||||
return volumes.length ? volumes.at(-1) : null;
|
||||
}
|
||||
|
||||
/** All parts, in spec order, enriched with step counts and recorded volume. */
|
||||
export function parts() {
|
||||
const manifest = spec();
|
||||
const systems = manifest.systems ?? {};
|
||||
return (manifest.parts ?? []).map(entry => {
|
||||
const steps = stepsOf(entry.document);
|
||||
const replay = replayOf(entry.document);
|
||||
return {
|
||||
id: entry.id,
|
||||
document: entry.document,
|
||||
title: entry.title,
|
||||
system: entry.system,
|
||||
systemLabel: systems[entry.system] ?? entry.system,
|
||||
module: entry.module,
|
||||
featureTypes: entry.featureTypes ?? [],
|
||||
placement: entry.placement ?? null,
|
||||
steps: steps?.length ?? 0,
|
||||
volume: finalVolume(replay?.steps),
|
||||
reconstructable: Boolean(steps && steps.length && replay?.steps?.length),
|
||||
stepsFile: path.relative(REPO_ROOT, path.join(STEPS_DIR, `${entry.document}.json`)),
|
||||
runFile: path.relative(REPO_ROOT, path.join(RUN_DIR, `${entry.document}.json`)),
|
||||
stillsDir: path.relative(REPO_ROOT, path.join(STILLS_DIR, entry.id)),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function groups() {
|
||||
const systems = spec().systems ?? {};
|
||||
const all = parts();
|
||||
return Object.entries(systems)
|
||||
.map(([id, label]) => {
|
||||
const members = all.filter(part => part.system === id);
|
||||
return { id, label, count: members.length, ids: members.map(part => part.id) };
|
||||
})
|
||||
.filter(group => group.count > 0);
|
||||
}
|
||||
|
||||
const ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
||||
|
||||
/**
|
||||
* Resolve "P06", "p06" or "CarrierElevators" to a part.
|
||||
* Rejects anything that is not a plain token so a shell fragment can never be
|
||||
* forwarded to the driver.
|
||||
*/
|
||||
export function find(key) {
|
||||
if (typeof key !== "string" || !ID_PATTERN.test(key)) {
|
||||
const error = new Error(`非法零件标识:${String(key).slice(0, 40)}`);
|
||||
error.code = "E_PART";
|
||||
throw error;
|
||||
}
|
||||
const wanted = key.toLowerCase();
|
||||
const all = parts();
|
||||
const match = all.find(part => part.id.toLowerCase() === wanted)
|
||||
?? all.find(part => part.document.toLowerCase() === wanted);
|
||||
if (!match) {
|
||||
const error = new Error(`没有该零件:${key}`);
|
||||
error.code = "E_PART";
|
||||
throw error;
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
export function stats() {
|
||||
const all = parts();
|
||||
return {
|
||||
parts: all.length,
|
||||
steps: all.reduce((sum, part) => sum + part.steps, 0),
|
||||
reconstructable: all.filter(part => part.reconstructable).length,
|
||||
volume: all.reduce((sum, part) => sum + (part.volume ?? 0), 0),
|
||||
};
|
||||
}
|
||||
150
tools/carrier/create-all.mjs
Normal file
150
tools/carrier/create-all.mjs
Normal file
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Purpose: 按系统分组或零件列表串行重建航空母舰的多个零件。
|
||||
*
|
||||
* 每个零件仍是一次独立运行:逐件调用 tools/carrier/create-part.mjs,
|
||||
* 判定、报告格式与退出码完全一致,这里只做编排与汇总。
|
||||
* 默认遇错即停;--keep-going 继续并在末尾给出汇总。
|
||||
*
|
||||
* Usage:
|
||||
* node tools/carrier/create-all.mjs --group flight-deck --dry
|
||||
* node tools/carrier/create-all.mjs --parts P02,P03
|
||||
* node tools/carrier/create-all.mjs --all --keep-going --slow
|
||||
*
|
||||
* Exit: 0 全部通过 / 1 至少一件产品失败 / 2 前置缺失、未执行或参数错误
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { REPO_ROOT, find, groups, parts } from "./catalog.mjs";
|
||||
|
||||
const CREATE_PART = path.join(REPO_ROOT, "tools/carrier/create-part.mjs");
|
||||
|
||||
function usage() {
|
||||
console.log("node tools/carrier/create-all.mjs [--parts P01,P02 | --group <id> | --all] [--keep-going] [--dry] [--slow] [--headless] [--out <dir>]");
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = { keys: [], group: null, all: false, keepGoing: false, dry: false, slow: false, headed: true, out: null };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--parts") options.keys = String(argv[++index] ?? "").split(",").map(item => item.trim()).filter(Boolean);
|
||||
else if (arg === "--group") options.group = argv[++index] ?? null;
|
||||
else if (arg === "--all") options.all = true;
|
||||
else if (arg === "--keep-going") options.keepGoing = true;
|
||||
else if (arg === "--dry") options.dry = true;
|
||||
else if (arg === "--slow") options.slow = true;
|
||||
else if (arg === "--headed") options.headed = true;
|
||||
else if (arg === "--headless") options.headed = false;
|
||||
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? "");
|
||||
else if (arg === "--help" || arg === "-h") {
|
||||
usage();
|
||||
process.exit(0);
|
||||
} else {
|
||||
console.error(`未知参数:${arg}`);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
if (!options.keys.length && !options.group && !options.all) {
|
||||
usage();
|
||||
console.error("必须给出 --parts / --group / --all(分组见 node tools/carrier/list.mjs)");
|
||||
process.exit(2);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function selection(options) {
|
||||
if (options.keys.length) return options.keys.map(key => find(key));
|
||||
if (options.group) {
|
||||
const group = groups().find(item => item.id === options.group);
|
||||
if (!group) {
|
||||
console.error(`没有该分组:${options.group}(可用:${groups().map(item => item.id).join(", ")})`);
|
||||
process.exit(2);
|
||||
}
|
||||
return group.ids.map(key => find(key));
|
||||
}
|
||||
return parts();
|
||||
}
|
||||
|
||||
function runPart(part, options) {
|
||||
const argv = [process.execPath, CREATE_PART, part.id];
|
||||
if (options.dry) argv.push("--dry");
|
||||
if (options.slow) argv.push("--slow");
|
||||
if (!options.headed) argv.push("--headless");
|
||||
if (options.out) argv.push("--out", path.join(options.out, part.id));
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, stdio: "inherit" });
|
||||
child.on("error", () => resolve(2));
|
||||
child.on("close", code => resolve(code ?? 1));
|
||||
});
|
||||
}
|
||||
|
||||
function readReport(dir, part) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(path.join(dir, part.id, "report.json"), "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const selected = selection(options);
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const summary = {
|
||||
schema: "freecad-web/carrier-toolkit/batch/v1",
|
||||
startedAt: new Date().toISOString(),
|
||||
items: [],
|
||||
};
|
||||
|
||||
for (const part of selected) {
|
||||
console.log(`\n=== ${part.id} ${part.document}(${part.title},${part.steps} 步,体积 ${part.volume ?? "—"})===`);
|
||||
const code = await runPart(part, options);
|
||||
const item = { id: part.id, document: part.document, title: part.title, system: part.system, exitCode: code };
|
||||
if (!options.dry) {
|
||||
const report = readReport(options.out ?? "", part);
|
||||
if (report) {
|
||||
item.verdict = report.verdict;
|
||||
item.steps = report.steps;
|
||||
item.stepsTotal = report.stepsTotal;
|
||||
item.volume = report.volume;
|
||||
item.expectedVolume = report.expectedVolume;
|
||||
item.relativeError = report.relativeError;
|
||||
item.seconds = report.seconds;
|
||||
}
|
||||
}
|
||||
summary.items.push(item);
|
||||
|
||||
if (code === 2) {
|
||||
console.error(`前置缺失,停止:${part.id}(前置失败不是产品失败)`);
|
||||
break;
|
||||
}
|
||||
if (code !== 0 && !options.keepGoing) {
|
||||
console.error(`零件 ${part.id} 未通过(exit ${code}),停止。用 --keep-going 可继续。`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
summary.finishedAt = new Date().toISOString();
|
||||
summary.passed = summary.items.filter(item => item.exitCode === 0).length;
|
||||
summary.failed = summary.items.filter(item => item.exitCode === 1).length;
|
||||
summary.blocked = summary.items.filter(item => item.exitCode === 2).length;
|
||||
summary.skipped = selected.length - summary.items.length;
|
||||
summary.seconds = Math.round((Date.parse(summary.finishedAt) - Date.parse(summary.startedAt)) / 1000);
|
||||
|
||||
const dir = options.out ?? path.join(REPO_ROOT, "docs/current/carrier-partdesign-toolkit/runs", `${stamp}-batch`);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
||||
|
||||
console.log(`\n合计:通过 ${summary.passed} / 失败 ${summary.failed} / 前置 ${summary.blocked} / 未执行 ${summary.skipped}(${summary.seconds}s)`);
|
||||
console.log(`汇总:${path.relative(REPO_ROOT, path.join(dir, "summary.json"))}`);
|
||||
|
||||
if (summary.failed > 0) process.exit(1);
|
||||
if (summary.blocked > 0 || summary.skipped > 0) process.exit(2);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`失败:${error?.message ?? error}`);
|
||||
process.exit(error?.code === "E_PART" ? 2 : 1);
|
||||
});
|
||||
175
tools/carrier/create-assembly.mjs
Normal file
175
tools/carrier/create-assembly.mjs
Normal file
@@ -0,0 +1,175 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Purpose: 在真实界面里装配整艘航空母舰(20 个零件 + 19 个固定关节 + 求解)。
|
||||
*
|
||||
* 本工具只做编排:装配回放由 web/teaching/cases/carrier-partdesign/build-assembly-replay.mjs
|
||||
* 从 assembly-spec.json 生成,插入、关节与求解全部由既有引擎
|
||||
* web/tools/cad-ui-rebuild/assemble.mjs 在界面上完成(插入用 Insert Link 面板,
|
||||
* 关节与求解走工作台命令面板,与 E18 课相同)。这里读取引擎报告并归一化。
|
||||
*
|
||||
* Usage:
|
||||
* node tools/carrier/create-assembly.mjs --dry
|
||||
* node tools/carrier/create-assembly.mjs --headed
|
||||
* node tools/carrier/create-assembly.mjs --out /tmp/carrier-assembly
|
||||
*
|
||||
* Exit: 0 通过 / 1 产品失败(插入/关节/求解与回放不符)/ 2 前置缺失
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { REPO_ROOT } from "./catalog.mjs";
|
||||
import { ensureOrigin, preflight } from "./preflight.mjs";
|
||||
|
||||
const ASSEMBLE = path.join(REPO_ROOT, "web/tools/cad-ui-rebuild/assemble.mjs");
|
||||
const PROJECT_DIR = path.join(REPO_ROOT, "web/tools/carrier-partdesign-course");
|
||||
const SPEC_DIR = path.join(REPO_ROOT, "web/teaching/cases/carrier-partdesign");
|
||||
const SPEC_FILE = path.join(SPEC_DIR, "assembly-spec.json");
|
||||
const GENERATOR = path.join(SPEC_DIR, "build-assembly-replay.mjs");
|
||||
const REPLAY_FILE = path.join(SPEC_DIR, "out/replay/CarrierAssembly.json");
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = { headed: true, dry: false, serve: true, out: null, json: false, regenerate: 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 === "--regenerate") options.regenerate = true;
|
||||
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-assembly.mjs [--headed|--headless] [--dry] [--regenerate] [--no-serve] [--out <dir>] [--json]");
|
||||
process.exit(0);
|
||||
} else {
|
||||
console.error(`未知参数:${arg}`);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function readSpec() {
|
||||
if (!fs.existsSync(SPEC_FILE)) throw new Error(`缺少装配清单 ${SPEC_FILE}`);
|
||||
return JSON.parse(fs.readFileSync(SPEC_FILE, "utf8"));
|
||||
}
|
||||
|
||||
/** The replay is generated data: regenerate when missing or older than its spec. */
|
||||
function ensureReplay(spec, regenerate) {
|
||||
const stale = !fs.existsSync(REPLAY_FILE)
|
||||
|| fs.statSync(REPLAY_FILE).mtimeMs < Math.max(fs.statSync(SPEC_FILE).mtimeMs, fs.statSync(GENERATOR).mtimeMs);
|
||||
if (!stale && !regenerate) return { generated: false, file: REPLAY_FILE };
|
||||
const code = spawn(process.execPath, [GENERATOR], { cwd: SPEC_DIR, stdio: "inherit" });
|
||||
return new Promise(resolve => code.on("close", exit => {
|
||||
if (exit !== 0) throw new Error(`装配回放生成失败(exit ${exit})`);
|
||||
resolve({ generated: true, file: REPLAY_FILE, spec });
|
||||
}));
|
||||
}
|
||||
|
||||
function assemblyChecks(spec) {
|
||||
const checks = [];
|
||||
const add = (id, ok, detail, fix = "") => checks.push({ id, ok, detail, fix });
|
||||
add("spec", Boolean(spec.inserts?.length && spec.joints?.length),
|
||||
`装配清单:${spec.inserts?.length ?? 0} 次插入 / ${spec.joints?.length ?? 0} 个关节 / 接地 ${spec.groundDocument}`);
|
||||
add("replay", fs.existsSync(REPLAY_FILE), REPLAY_FILE, "node web/teaching/cases/carrier-partdesign/build-assembly-replay.mjs");
|
||||
const samples = path.join(REPO_ROOT, "web/teaching/cases/carrier-partdesign/out/FCStd");
|
||||
const missing = spec.inserts.map(item => item.sourceDocument).filter(document => !fs.existsSync(path.join(samples, `${document}.FCStd`)));
|
||||
add("samples", missing.length === 0, missing.length ? `缺少源文档:${missing.join(", ")}` : `${spec.inserts.length} 份源文档齐全`, "先运行 web/teaching/cases/carrier-partdesign/build.mjs --all");
|
||||
add("engine", fs.existsSync(ASSEMBLE), ASSEMBLE);
|
||||
return checks;
|
||||
}
|
||||
|
||||
function readRunReport() {
|
||||
const file = path.join(PROJECT_DIR, "out/ui-run", "CarrierAssembly-assembly.json");
|
||||
try {
|
||||
return { file, report: JSON.parse(fs.readFileSync(file, "utf8")) };
|
||||
} catch {
|
||||
return { file, report: null };
|
||||
}
|
||||
}
|
||||
|
||||
function runEngine(options) {
|
||||
const argv = [process.execPath, ASSEMBLE, "--project", PROJECT_DIR];
|
||||
if (options.headed) argv.push("--headed");
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, stdio: "inherit" });
|
||||
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 spec = readSpec();
|
||||
|
||||
const generic = await preflight();
|
||||
const checks = [...generic.checks.filter(check => check.id !== "parts"), ...assemblyChecks(spec)];
|
||||
const ok = checks.every(check => check.ok);
|
||||
if (options.dry) {
|
||||
for (const check of checks) console.log(` ${check.ok ? "✓" : "✗"} ${check.id}: ${check.detail}`);
|
||||
console.log(ok ? "前置全部满足(dry run,未启动浏览器)" : "前置未满足(dry run)");
|
||||
process.exit(ok ? 0 : 2);
|
||||
}
|
||||
if (!ok) {
|
||||
for (const check of checks.filter(item => !item.ok)) console.error(`前置缺失 ${check.id}: ${check.detail} → ${check.fix}`);
|
||||
console.error("未启动浏览器(前置失败不是产品失败)。");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
await ensureReplay(spec, options.regenerate);
|
||||
|
||||
let origin = null;
|
||||
if (options.serve) {
|
||||
origin = await ensureOrigin();
|
||||
console.log(origin.started ? `已为 ${origin.origin} 启动静态服务` : `复用已在运行的应用入口 ${origin.origin}`);
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
let result;
|
||||
try {
|
||||
result = await runEngine(options);
|
||||
} finally {
|
||||
await origin?.close();
|
||||
}
|
||||
|
||||
const { file: runFile, report } = readRunReport();
|
||||
const dir = options.out ?? path.join(REPO_ROOT, "docs/current/carrier-partdesign-toolkit/runs",
|
||||
`${new Date().toISOString().replace(/[:.]/g, "-")}-assembly`);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
const lastSolve = report?.solves?.at(-1) ?? null;
|
||||
const summary = {
|
||||
schema: "freecad-web/carrier-toolkit/assembly/v1",
|
||||
document: spec.document,
|
||||
label: spec.label,
|
||||
expected: { inserts: spec.inserts.length, joints: spec.joints.length, solves: 2 },
|
||||
inserted: report?.inserted ?? 0,
|
||||
joints: report?.joints?.length ?? 0,
|
||||
components: lastSolve?.components ?? 0,
|
||||
malformedComponents: lastSolve?.malformed ?? null,
|
||||
mismatches: report?.mismatches ?? [],
|
||||
fatal: report?.fatal ?? null,
|
||||
seconds: Math.round(report?.seconds ?? (Date.now() - startedAt) / 1000),
|
||||
engineExitCode: result.code,
|
||||
engineReport: path.relative(REPO_ROOT, runFile),
|
||||
verdict: !report ? "run_fail"
|
||||
: report.fatal || (report.mismatches ?? []).length ? "product_fail"
|
||||
: report.inserted !== spec.inserts.length || (report.joints ?? []).length !== spec.joints.length
|
||||
|| lastSolve?.malformed ? "product_fail"
|
||||
: "pass",
|
||||
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(`装配 ${spec.document}: ${summary.verdict}(插入 ${summary.inserted}/${spec.inserts.length},关节 ${summary.joints}/${spec.joints.length},求解组件 ${summary.components},畸形 ${summary.malformedComponents},${summary.seconds}s)`);
|
||||
console.log(`报告:${path.relative(REPO_ROOT, path.join(dir, "report.json"))}`);
|
||||
}
|
||||
process.exit(summary.verdict === "pass" ? 0 : summary.verdict === "run_fail" ? 2 : 1);
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`失败:${error?.message ?? error}`);
|
||||
process.exit(2);
|
||||
});
|
||||
201
tools/carrier/create-part.mjs
Normal file
201
tools/carrier/create-part.mjs
Normal file
@@ -0,0 +1,201 @@
|
||||
#!/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);
|
||||
});
|
||||
48
tools/carrier/list.mjs
Normal file
48
tools/carrier/list.mjs
Normal file
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Purpose: 列出航空母舰的 20 个零件与系统分组(供人看,也供脚本读)。
|
||||
*
|
||||
* Usage:
|
||||
* node tools/carrier/list.mjs
|
||||
* node tools/carrier/list.mjs --group flight-deck
|
||||
* node tools/carrier/list.mjs --json
|
||||
*
|
||||
* Exit: 0
|
||||
*/
|
||||
import { groups, parts, stats } from "./catalog.mjs";
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
if (argv.includes("--help") || argv.includes("-h")) {
|
||||
console.log("node tools/carrier/list.mjs [--group <id>] [--json]");
|
||||
process.exit(0);
|
||||
}
|
||||
const groupFilter = argv.includes("--group") ? argv[argv.indexOf("--group") + 1] : null;
|
||||
const asJson = argv.includes("--json");
|
||||
|
||||
const all = parts();
|
||||
const selected = groupFilter ? all.filter(part => part.system === groupFilter) : all;
|
||||
const summary = stats();
|
||||
|
||||
if (asJson) {
|
||||
console.log(JSON.stringify({
|
||||
schema: "freecad-web/carrier-toolkit/catalog/v1",
|
||||
stats: summary,
|
||||
groups: groups(),
|
||||
parts: selected.map(({ id, document, title, system, systemLabel, featureTypes, steps, volume, reconstructable }) => ({
|
||||
id, document, title, system, systemLabel, featureTypes, steps, volume, reconstructable,
|
||||
})),
|
||||
}, null, 2));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
for (const group of groups()) {
|
||||
const members = selected.filter(part => part.system === group.id);
|
||||
if (!members.length) continue;
|
||||
console.log(`\n${group.label}(${group.id})`);
|
||||
for (const part of members) {
|
||||
const volume = part.volume == null ? "—" : part.volume.toFixed(1);
|
||||
const features = part.featureTypes.join("+");
|
||||
console.log(` ${part.id} ${part.document.padEnd(26)} ${part.title.padEnd(14)} ${String(part.steps).padStart(2)} 步 体积 ${volume.padStart(10)} m³ ${features}${part.reconstructable ? "" : " (不可界面重建)"}`);
|
||||
}
|
||||
}
|
||||
console.log(`\n合计 ${summary.parts} 件 / ${summary.steps} 步 / 可界面重建 ${summary.reconstructable} 件 / 体积合计 ${summary.volume.toFixed(0)} m³`);
|
||||
180
tools/carrier/preflight.mjs
Normal file
180
tools/carrier/preflight.mjs
Normal file
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* Prerequisites for a headed carrier rebuild.
|
||||
*
|
||||
* Iron law: a missing dist, kernel, Chrome, DISPLAY, playwright, engine or UI
|
||||
* step list is a prerequisite failure, never a product failure. `create-*`
|
||||
* exits 2 for these and only ever exits 1 after the browser actually ran.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { REPO_ROOT, PROJECT_DIR, parts, projectManifest, stats } from "./catalog.mjs";
|
||||
import { findChrome, startStaticHost } from "../static-host.mjs";
|
||||
|
||||
const require = createRequire(path.join(REPO_ROOT, "web/package.json"));
|
||||
|
||||
function originPort(origin) {
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
return Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function originReachable(origin, timeoutMs = 1500) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const response = await fetch(`${origin}/index.html`, { signal: controller.signal, cache: "no-store" });
|
||||
return response.ok;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
const BUILD_STEPS = "node web/tools/cad-ui-rebuild/build-steps.mjs --project web/tools/carrier-partdesign-course";
|
||||
const REPLAY_GEN = "node web/tools/cad-ui-rebuild/capture-replay.mjs --trace-dir web/teaching/cases/carrier-partdesign/out/traces --sample-dir web/teaching/cases/carrier-partdesign/out/FCStd --out-dir web/teaching/cases/carrier-partdesign/out/replay --source-prefix web/teaching/cases/carrier-partdesign/out/FCStd";
|
||||
|
||||
/**
|
||||
* @param {{ part?: object | null }} [options]
|
||||
* `part` narrows the catalog check to that one part: `create-part` only needs
|
||||
* its own ui-steps and build record, so the other 19 parts must not block it.
|
||||
* Without it (create-all, self-test) the check is the whole catalog.
|
||||
*/
|
||||
export async function preflight(options = {}) {
|
||||
const part = options.part ?? null;
|
||||
const checks = [];
|
||||
const add = (id, ok, detail, fix) => checks.push({ id, ok, detail, fix });
|
||||
|
||||
const manifest = projectManifest();
|
||||
const origin = manifest.appOrigin;
|
||||
|
||||
const distIndex = path.join(REPO_ROOT, "web/dist/index.html");
|
||||
add("dist", fs.existsSync(distIndex), fs.existsSync(distIndex) ? "web/dist/index.html 已就绪" : "web/dist/index.html 不存在",
|
||||
"cd web && npx vite build");
|
||||
|
||||
const wasm = ["web/dist/kernel", "web/public/kernel"].flatMap(rel => {
|
||||
try {
|
||||
return fs.readdirSync(path.join(REPO_ROOT, rel)).filter(name => name.endsWith(".wasm"));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
add("kernel", wasm.length > 0, wasm.length ? `内核产物 ${wasm.length} 个 .wasm` : "未找到内核 .wasm 产物",
|
||||
"cd web && node ../tools/sync-assets.mjs");
|
||||
|
||||
let chrome = null;
|
||||
try {
|
||||
chrome = findChrome();
|
||||
} catch {
|
||||
chrome = null;
|
||||
}
|
||||
add("chrome", Boolean(chrome), chrome || "未找到 Chrome/Chromium", "export FREECAD_CHROME=/usr/bin/google-chrome");
|
||||
|
||||
const display = process.env.DISPLAY || "";
|
||||
add("display", Boolean(display), display ? `DISPLAY=${display}` : "DISPLAY 未设置(有头运行需要)",
|
||||
"DISPLAY=:1 node tools/carrier/create-part.mjs P02");
|
||||
|
||||
let playwright = null;
|
||||
try {
|
||||
playwright = require.resolve("playwright");
|
||||
} catch {
|
||||
playwright = null;
|
||||
}
|
||||
add("playwright", Boolean(playwright), playwright ? "web/node_modules 可解析 playwright" : "web/node_modules 中找不到 playwright",
|
||||
"cd web && npm install");
|
||||
|
||||
const engine = [
|
||||
"web/tools/cad-ui-rebuild/drive.mjs",
|
||||
"web/tools/cad-ui-rebuild/assemble.mjs",
|
||||
"web/tools/cad-ui-rebuild/manifest.mjs",
|
||||
"web/tools/cad-ui-rebuild/build-steps.mjs",
|
||||
];
|
||||
const missingEngine = engine.filter(rel => !fs.existsSync(path.join(REPO_ROOT, rel)));
|
||||
add("engine", missingEngine.length === 0, missingEngine.length ? `缺少共享引擎:${missingEngine.join(", ")}` : "界面重建引擎完整",
|
||||
"git status web/tools/cad-ui-rebuild");
|
||||
|
||||
const summary = stats();
|
||||
const withoutReplay = parts().filter(item => item.volume == null).map(item => item.id);
|
||||
const withoutSteps = parts().filter(item => item.steps === 0).map(item => item.id);
|
||||
if (part) {
|
||||
add("parts", Boolean(part.reconstructable),
|
||||
part.reconstructable
|
||||
? `${part.id} ${part.document}:${part.steps} 步,构建记录体积 ${part.volume ?? "—"}`
|
||||
+ `(目录共 ${summary.reconstructable}/${summary.parts} 件具备步骤)`
|
||||
: `${part.id} ${part.document} 缺少界面步骤或构建记录(该件 ${part.steps} 步,体积 ${part.volume ?? "—"})`,
|
||||
`node web/tools/cad-ui-rebuild/build-steps.mjs --project web/tools/carrier-partdesign-course ${part.id} # 若缺构建记录:${REPLAY_GEN}`);
|
||||
} else {
|
||||
add("parts", summary.reconstructable === summary.parts,
|
||||
`${summary.reconstructable}/${summary.parts} 件具备界面步骤与构建记录(共 ${summary.steps} 步)`
|
||||
+ (withoutSteps.length ? `;缺界面步骤:${withoutSteps.join(",")}` : "")
|
||||
+ (withoutReplay.length ? `;缺构建记录:${withoutReplay.join(",")}` : ""),
|
||||
`${BUILD_STEPS} # 或先生成 replay:${REPLAY_GEN}`);
|
||||
}
|
||||
|
||||
const originOk = await originReachable(origin);
|
||||
add("app", originOk, originOk ? `应用入口可达:${origin}` : `应用入口不可达:${origin}(create-part 会自动起静态服务)`,
|
||||
`cd web && npx vite build && node ../tools/static-host.mjs --root dist --port ${originPort(origin) || 5183}`);
|
||||
|
||||
return {
|
||||
ok: checks.every(check => check.ok || check.id === "app"),
|
||||
checks,
|
||||
origin,
|
||||
projectDir: PROJECT_DIR,
|
||||
stats: summary,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a one-off project manifest that keeps the real paths but points at a
|
||||
* different app origin. The driver reads appOrigin from project.json only, so
|
||||
* this is the least invasive way to run it without touching the checked-in
|
||||
* manifest.
|
||||
*/
|
||||
function derivedProject(originMW) {
|
||||
const raw = projectManifest();
|
||||
const base = {
|
||||
...raw,
|
||||
appOrigin: originMW,
|
||||
paths: Object.fromEntries(Object.entries(raw.paths ?? {}).map(([key, value]) => [key, path.resolve(PROJECT_DIR, value)])),
|
||||
};
|
||||
const dir = path.join(REPO_ROOT, "docs/current/carrier-partdesign-toolkit/runtimes", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "project.json"), `${JSON.stringify(base, null, 2)}\n`);
|
||||
return dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure something serves the built app, reusing tools/static-host.mjs.
|
||||
*
|
||||
* Returns the project directory the driver should use: the checked-in one when
|
||||
* its appOrigin already serves the app, otherwise a derived manifest in the run
|
||||
* evidence tree that points at the ephemeral host we just started.
|
||||
*/
|
||||
export async function ensureOrigin(origin = projectManifest().appOrigin) {
|
||||
if (await originReachable(origin)) return { origin, started: false, projectDir: PROJECT_DIR, close: async () => {} };
|
||||
|
||||
const dist = path.join(REPO_ROOT, "web/dist");
|
||||
if (!fs.existsSync(path.join(dist, "index.html"))) {
|
||||
throw Object.assign(new Error(`web/dist/index.html 不存在,无法为 ${origin} 起服务`), { code: "E_PREFLIGHT" });
|
||||
}
|
||||
|
||||
const port = originPort(origin) || 5183;
|
||||
try {
|
||||
const host = await startStaticHost(dist, "index.html", port);
|
||||
if (host.origin === origin) {
|
||||
return { origin: host.origin, started: true, projectDir: PROJECT_DIR, close: () => host.close() };
|
||||
}
|
||||
await host.close();
|
||||
} catch {
|
||||
/* port busy (or refused) — fall through to an ephemeral host */
|
||||
}
|
||||
|
||||
const host = await startStaticHost(dist, "index.html", 0);
|
||||
return { origin: host.origin, started: true, projectDir: derivedProject(host.origin), close: () => host.close() };
|
||||
}
|
||||
|
||||
export { parts };
|
||||
145
tools/carrier/self-test.mjs
Normal file
145
tools/carrier/self-test.mjs
Normal file
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Purpose: 无浏览器自测航空母舰工具包的数据契约。
|
||||
*
|
||||
* 只检查磁盘上的清单与证据是否自洽:spec 是唯一零件来源、project.json 与
|
||||
* spec 一致、分组完整、标识解析严格、ui-steps 与 replay 步数对应、体积
|
||||
* 正数且与目录一致。真正的界面重建由 create-part / create-all 负责。
|
||||
*
|
||||
* Usage: node tools/carrier/self-test.mjs [--json]
|
||||
* Exit: 0 全部通过 / 1 有失败
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { REPO_ROOT, SPEC_FILE, PROJECT_FILE, find, groups, parts, projectManifest, spec, stats } from "./catalog.mjs";
|
||||
|
||||
const asJson = process.argv.includes("--json");
|
||||
const results = [];
|
||||
let failures = 0;
|
||||
|
||||
function check(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
results.push({ name, ok: true });
|
||||
if (!asJson) console.log(`ok ${name}`);
|
||||
} catch (error) {
|
||||
failures += 1;
|
||||
const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
|
||||
results.push({ name, ok: false, message });
|
||||
if (!asJson) console.error(`FAIL ${name}\n ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function throwsCode(fn, code) {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
assert.equal(error.code, code, `expected ${code}, got ${error.code ?? error.message}`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`expected ${code}, nothing thrown`);
|
||||
}
|
||||
|
||||
const readJson = file => JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
|
||||
check("spec 是唯一零件来源且格式完整", () => {
|
||||
const manifest = spec();
|
||||
assert.ok(fs.existsSync(SPEC_FILE));
|
||||
assert.equal(manifest.parts.length, 20, `expected 20 parts, got ${manifest.parts.length}`);
|
||||
const ids = manifest.parts.map(part => part.id);
|
||||
const documents = manifest.parts.map(part => part.document);
|
||||
assert.equal(new Set(ids).size, ids.length, "duplicate part ids");
|
||||
assert.equal(new Set(documents).size, documents.length, "duplicate documents");
|
||||
ids.forEach(id => assert.match(id, /^P\d{2}$/, `bad id ${id}`));
|
||||
for (const part of manifest.parts) {
|
||||
assert.ok(part.title && part.system && Array.isArray(part.featureTypes) && part.featureTypes.length,
|
||||
`${part.id} 缺少 title/system/featureTypes`);
|
||||
assert.ok(Object.hasOwn(manifest.systems ?? {}, part.system), `${part.id} 的 system ${part.system} 不在 systems 里`);
|
||||
}
|
||||
});
|
||||
|
||||
check("project.json 与 spec 一致", () => {
|
||||
const manifest = projectManifest();
|
||||
const wanted = spec().parts.map(part => `${part.id}:${part.document}`).sort();
|
||||
const got = manifest.parts.map(part => `${part.id}:${part.document}`).sort();
|
||||
assert.deepEqual(got, wanted);
|
||||
for (const key of ["replayDir", "sampleDir", "outDir", "stillsDir"]) {
|
||||
assert.ok(typeof manifest.paths?.[key] === "string" && manifest.paths[key], `paths.${key} 缺失`);
|
||||
}
|
||||
assert.match(manifest.appOrigin, /^http:\/\/127\.0\.0\.1:\d+$/);
|
||||
assert.ok(fs.existsSync(PROJECT_FILE));
|
||||
});
|
||||
|
||||
check("分组覆盖全部零件且不重复", () => {
|
||||
const all = parts();
|
||||
const grouped = groups().flatMap(group => group.ids);
|
||||
assert.equal(grouped.length, all.length);
|
||||
assert.deepEqual([...grouped].sort(), all.map(part => part.id).sort());
|
||||
for (const group of groups()) assert.ok(group.label && group.count > 0, `分组 ${group.id} 无标签或为空`);
|
||||
});
|
||||
|
||||
check("目录统计与零件列表一致", () => {
|
||||
const summary = stats();
|
||||
const all = parts();
|
||||
assert.equal(summary.parts, all.length);
|
||||
assert.equal(summary.steps, all.reduce((sum, part) => sum + part.steps, 0));
|
||||
assert.equal(summary.reconstructable, all.filter(part => part.reconstructable).length);
|
||||
});
|
||||
|
||||
check("标识解析:id / Document 大小写不敏感,非法输入拒绝", () => {
|
||||
const first = parts()[0];
|
||||
assert.equal(find(first.id).id, first.id);
|
||||
assert.equal(find(first.id.toLowerCase()).id, first.id);
|
||||
assert.equal(find(first.document).id, first.id);
|
||||
throwsCode(() => find("P999"), "E_PART");
|
||||
throwsCode(() => find("P02; rm -rf /"), "E_PART");
|
||||
throwsCode(() => find(""), "E_PART");
|
||||
throwsCode(() => find(undefined), "E_PART");
|
||||
});
|
||||
|
||||
check("有界面步骤的零件必须有对应构建记录,且步数一致", () => {
|
||||
for (const part of parts()) {
|
||||
if (!part.steps) continue;
|
||||
assert.ok(fs.existsSync(path.join(REPO_ROOT, part.stepsFile)), `${part.id} 缺 ${part.stepsFile}`);
|
||||
const steps = readJson(path.join(REPO_ROOT, part.stepsFile)).steps;
|
||||
assert.equal(steps.length, part.steps, `${part.id} steps 字段与文件不一致`);
|
||||
assert.ok(part.reconstructable, `${part.id} 有界面步骤但目录判为不可重建`);
|
||||
assert.ok(part.volume > 0, `${part.id} 没有正的构建记录体积`);
|
||||
}
|
||||
});
|
||||
|
||||
check("ui-steps 与 replay 逐步对应(步数、顺序、种类)", () => {
|
||||
const KIND = new Set(["sketch", "feature", "dressup", "transform", "primitive"]);
|
||||
for (const part of parts().filter(item => item.reconstructable)) {
|
||||
const uiSteps = readJson(path.join(REPO_ROOT, part.stepsFile)).steps;
|
||||
const replay = readJson(path.join(REPO_ROOT, "web/teaching/cases/carrier-partdesign/out/replay", `${part.document}.json`));
|
||||
assert.ok(Array.isArray(replay?.steps), `${part.document} replay 缺 steps`);
|
||||
assert.equal(uiSteps.length, replay.steps.length, `${part.document} 步数不等`);
|
||||
uiSteps.forEach((step, index) => {
|
||||
assert.ok(KIND.has(step.kind), `${part.document}#${index + 1} 未知 kind ${step.kind}`);
|
||||
assert.equal(step.step, index + 1, `${part.document} 步骤序号不连续`);
|
||||
assert.ok(step.command, `${part.document}#${step.step} 缺 command`);
|
||||
});
|
||||
const kinds = new Set(uiSteps.map(step => step.kind));
|
||||
for (const featureType of part.featureTypes) {
|
||||
const mapped = featureType === "Pad" || featureType === "Pocket" || featureType === "Loft" || featureType === "Pipe"
|
||||
|| featureType === "Hole" || featureType === "Revolution"
|
||||
? kinds.has("feature")
|
||||
: featureType === "Fillet" || featureType === "Chamfer"
|
||||
? kinds.has("dressup")
|
||||
: featureType === "Mirrored" || featureType === "LinearPattern" || featureType === "PolarPattern"
|
||||
? kinds.has("transform")
|
||||
: true;
|
||||
assert.ok(mapped, `${part.document} 宣称 ${featureType} 但界面步骤里没有对应动作`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (asJson) {
|
||||
console.log(JSON.stringify({ schema: "freecad-web/carrier-toolkit/self-test/v1", ok: failures === 0, checks: results }, null, 2));
|
||||
} else {
|
||||
const summary = stats();
|
||||
console.log(`\n${failures === 0 ? "全部通过" : `${failures} 项失败`}:${summary.parts} 件 / ${summary.steps} 步 / 可界面重建 ${summary.reconstructable} 件 / 体积合计 ${summary.volume.toFixed(0)} m³`);
|
||||
}
|
||||
process.exit(failures === 0 ? 0 : 1);
|
||||
Reference in New Issue
Block a user