- 新数据链 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>
177 lines
8.7 KiB
JavaScript
177 lines
8.7 KiB
JavaScript
#!/usr/bin/env node
|
|
// Build a project's assembly through the real UI.
|
|
//
|
|
// Everything a learner can click goes through the UI: create the assembly,
|
|
// load each part document, insert it at a position and rotation, accept. Joints
|
|
// and the solve still go through the workbench forms, in the order proven in
|
|
// tools/line-manual/ui-assemble.mjs.
|
|
//
|
|
// Input: the project's assembly replay, which records every insertion as
|
|
// {sourceDocument, sourceObject, position, rotation}. Nothing is invented: the
|
|
// same replay the videos are cut from supplies the placement numbers.
|
|
//
|
|
// Usage: node assemble.mjs --project <dir> [--headed] [--dry]
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { createRequire } from "node:module";
|
|
import { fileURLToPath } from "node:url";
|
|
import { loadProject, projectFromArgv, readJson, replayPath } from "./manifest.mjs";
|
|
import { createAssembly, createJoints, executeCommand, insertAll, insertedLinkCount, saveAssemblyBundle, solveAssembly, writeAssemblyReport, seedSources } from "./lib/assembly.mjs";
|
|
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const webRoot = path.resolve(here, "../..");
|
|
const require = createRequire(path.join(webRoot, "package.json"));
|
|
const { chromium } = require("playwright");
|
|
|
|
const projectDir = projectFromArgv();
|
|
const project = loadProject(projectDir, { requireAssembly: true });
|
|
const args = process.argv.slice(2);
|
|
const headed = args.includes("--headed");
|
|
const dry = args.includes("--dry");
|
|
|
|
// The assembly replay lives beside the part replays and is identified by the
|
|
// assembly document name, so a project needs no extra path setting.
|
|
const replayFile = replayPath(project, project.assembly.document, { assembly: true });
|
|
if (!fs.existsSync(replayFile)) throw new Error(`no assembly replay at ${replayFile}`);
|
|
const replay = JSON.parse(fs.readFileSync(replayFile, "utf8"));
|
|
const inserts = replay.steps.filter(step => step.insert).map(step => step.insert);
|
|
if (!inserts.length) throw new Error(`assembly replay has no insertions: ${replayFile}`);
|
|
|
|
const rotated = inserts.filter(item => (item.rotation ?? [0, 0, 0, 1]).some((value, index) => index < 3 && value !== 0));
|
|
const groundDocument = project.assembly.groundDocument ?? inserts[0]?.sourceDocument;
|
|
|
|
if (dry) {
|
|
console.log(JSON.stringify({
|
|
project: project.name, document: project.assembly.document,
|
|
inserts: inserts.length, rotated: rotated.length, ground: groundDocument,
|
|
sourceDocuments: [...new Set(inserts.map(item => item.sourceDocument))].length,
|
|
}, null, 2));
|
|
process.exit(0);
|
|
}
|
|
|
|
const browser = await chromium.launch({
|
|
executablePath: "/usr/bin/google-chrome", headless: !headed,
|
|
args: ["--no-sandbox", "--disable-dev-shm-usage", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"],
|
|
});
|
|
const page = await browser.newPage({ viewport: { width: 1600, height: 900 } });
|
|
const errors = [];
|
|
page.on("pageerror", error => errors.push(String(error).slice(0, 300)));
|
|
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 300)); });
|
|
|
|
const started = Date.now();
|
|
let done = [];
|
|
let fatal = null;
|
|
let joints = [];
|
|
let solves = [];
|
|
// Joints and the solve are optional replay content: a project that only inserts
|
|
// links keeps the old report shape, and one that records joints gets them run
|
|
// in replay order after the insertion session is committed.
|
|
const jointSteps = replay.steps.filter(step => typeof step.action === "string" && step.action.startsWith("Assembly_CreateJoint"));
|
|
const solveSteps = replay.steps.filter(step => step.action === "Assembly_SolveAssembly");
|
|
// Saving is opt-in per project (`assembly.saveBundle`): it opens the BOM task
|
|
// and clicks its own "Save FCStd" button, which stores to OPFS only.
|
|
const bomSteps = project.assembly.saveBundle
|
|
? replay.steps.filter(step => step.action === "Assembly_CreateBom") : [];
|
|
let saved = null;
|
|
try {
|
|
// The Insert Link task only sees documents in the browser's OPFS, so the
|
|
// sample FCStd files have to be staged there before any source can be loaded.
|
|
if (!project.paths.sampleDir) throw new Error("project.json needs paths.sampleDir for UI-driven assembly");
|
|
const sources = [];
|
|
for (const document of [...new Set(inserts.map(item => item.sourceDocument))]) {
|
|
const file = path.join(project.paths.sampleDir, `${document}.FCStd`);
|
|
if (!fs.existsSync(file)) throw new Error(`missing source document ${file}`);
|
|
sources.push({ name: `${document}.FCStd`, base64: fs.readFileSync(file).toString("base64") });
|
|
}
|
|
await page.goto(`${project.appOrigin}/`, { waitUntil: "domcontentloaded", timeout: 180000 });
|
|
await seedSources(page, sources);
|
|
|
|
await createAssembly(page, {
|
|
appOrigin: project.appOrigin,
|
|
pagePath: project.pages.assembly,
|
|
document: project.assembly.document,
|
|
label: project.assembly.label ?? project.assembly.document,
|
|
});
|
|
done = await insertAll(page, inserts, { groundDocument });
|
|
const reported = await insertedLinkCount(page);
|
|
// Every insert must be reflected in the task's own list before we call it good.
|
|
if (reported && reported !== done.length) {
|
|
throw new Error(`task lists ${reported} links but ${done.length} were inserted`);
|
|
}
|
|
if (jointSteps.length) {
|
|
joints = await createJoints(page, jointSteps);
|
|
if (joints.length !== jointSteps.length) {
|
|
throw new Error(`${joints.length} joints created, replay records ${jointSteps.length}`);
|
|
}
|
|
}
|
|
for (const step of solveSteps) solves.push(await solveAssembly(page, step));
|
|
if (bomSteps.length) {
|
|
// The BOM command opens the task panel; its own Save FCStd button then
|
|
// writes the bundle to OPFS (documents + manifest), never to disk.
|
|
for (const step of bomSteps) await executeCommand(page, step.action, step.args);
|
|
saved = await saveAssemblyBundle(page, { document: project.assembly.document });
|
|
}
|
|
} catch (error) {
|
|
fatal = String(error).slice(0, 800);
|
|
} finally {
|
|
await browser.close();
|
|
}
|
|
|
|
// Compare what the UI did against the replay, value by value: an insert that
|
|
// silently dropped its rotation would still "succeed" and only show up as a
|
|
// mis-assembled model much later.
|
|
const mismatches = [];
|
|
for (const [index, expected] of inserts.entries()) {
|
|
const actual = done[index];
|
|
if (!actual) { mismatches.push(`${expected.sourceDocument}: not inserted`); continue; }
|
|
if (actual.sourceDocument !== expected.sourceDocument) mismatches.push(`#${index + 1} document ${actual.sourceDocument} != ${expected.sourceDocument}`);
|
|
const quaternion = actual.rotation ?? [0, 0, 0, 1];
|
|
const wanted = expected.rotation ?? [0, 0, 0, 1];
|
|
if (quaternion.some((value, at) => Math.abs(value - wanted[at]) > 1e-6))
|
|
mismatches.push(`${expected.sourceDocument}: rotation ${quaternion.join(",")} != ${wanted.join(",")}`);
|
|
const position = actual.position ?? [0, 0, 0];
|
|
const target = expected.position ?? [0, 0, 0];
|
|
if (position.some((value, at) => Math.abs(value - target[at]) > 1e-6))
|
|
mismatches.push(`${expected.sourceDocument}: position ${position.join(",")} != ${target.join(",")}`);
|
|
}
|
|
// A save that silently stored nothing is a persistence gap, not a detail.
|
|
// Only the manifest is asserted here: the document store already holds the
|
|
// staged source files, so its count says nothing about this save.
|
|
if (bomSteps.length && !saved?.manifestStored) {
|
|
mismatches.push(`OPFS 未存储装配清单 ${project.assembly.document}.assembly.json`);
|
|
}
|
|
|
|
const report = {
|
|
schema: "freecad-web-cad-ui-rebuild/assembly/v1",
|
|
generatedAt: new Date().toISOString(),
|
|
project: project.name,
|
|
document: project.assembly.document,
|
|
groundDocument,
|
|
expected: { inserts: inserts.length, rotated: rotated.length, joints: jointSteps.length, solves: solveSteps.length },
|
|
inserted: done.length,
|
|
joints,
|
|
solves: solves.map(solve => ({
|
|
label: solve.label, components: solve.components.length,
|
|
malformed: solve.components.filter(component => !Array.isArray(component.position) || component.position.length !== 3
|
|
|| !component.position.every(Number.isFinite)
|
|
|| !Array.isArray(component.rotation) || component.rotation.length !== 4
|
|
|| !component.rotation.every(Number.isFinite)).length,
|
|
diagnostics: solve.diagnostics,
|
|
})),
|
|
components: solves.at(-1)?.components ?? [],
|
|
saved,
|
|
rotated: done.filter(item => (item.rotation ?? [0, 0, 0, 1]).some((value, index) => index < 3 && value !== 0)).length,
|
|
mismatches,
|
|
seconds: (Date.now() - started) / 1000,
|
|
fatal,
|
|
pageErrors: errors.slice(-10),
|
|
links: done,
|
|
};
|
|
const file = writeAssemblyReport(project.paths.runDir, project.assembly.document, report);
|
|
console.log(JSON.stringify({
|
|
document: project.assembly.document, inserted: report.inserted, rotated: report.rotated,
|
|
expected: report.expected, mismatches: mismatches.length, fatal,
|
|
seconds: Math.round(report.seconds), report: file,
|
|
}));
|
|
process.exitCode = fatal || mismatches.length ? 1 : 0;
|