#!/usr/bin/env node // fcweb toolkit self-check. // // No fixtures, no browser, no teaching case. Every number below is either an // analytic volume or a cross-probe agreement, so this is a gate on the kernel // contract rather than a smoke test: if a probe renames an argument key or // changes a return shape, a check here fails instead of a case script quietly // producing a different model. // // node tools/fcweb/selftest.mjs // node tools/fcweb/selftest.mjs --json import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { openPart } from "./part.mjs"; import { openPartDesign } from "./partdesign.mjs"; import { openAssembly } from "./assembly.mjs"; import { configureOpfs, storeRoot, storeBytes, readExportFile, hasExportFile, listExportFiles, safeName } from "./opfs.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const outDir = path.join(here, "out"); const TOL = 1e-6; const results = []; function check(name, expected, actual, { tolerance = TOL, note = null } = {}) { const ok = typeof expected === "number" && typeof actual === "number" ? Math.abs(expected - actual) <= tolerance : actual === expected; results.push({ name, expected, actual, tolerance, ok, note }); console.log(`${ok ? "PASS" : "FAIL"} ${name} expected=${expected} actual=${actual}`); if (!ok) throw new Error(`selftest failed: ${name} (expected ${expected}, got ${actual})`); return ok; } function checkTrue(name, value, note = null) { const ok = Boolean(value); results.push({ name, expected: true, actual: Boolean(value), tolerance: null, ok, note }); console.log(`${ok ? "PASS" : "FAIL"} ${name}`); if (!ok) throw new Error(`selftest failed: ${name} ${note ?? ""}`); } const CY15 = Math.PI * 25; // area of a r=5 circle, the recurring term // ---------------------------------------------------------------- Part ---- async function partChecks() { // Box 20x30x10 -> exact volume; also the reference for the cross-probe check. const part = await openPart("SelfTestPart"); let boxVolume; try { part.create(); part.box("B1", { length: 20, width: 30, height: 10 }); boxVolume = part.volumeOf("B1"); check("part.box volume 20x30x10", 6000, boxVolume, { tolerance: 1e-6 }); // Fuse with a disjoint cylinder: avoids OCCT's touching-face ambiguity. // Default axis is +Z, so no rotation is involved and the volume is exact. part.primitive("C1", { kind: "Cylinder", parameters: { Radius: 5, Height: 10, Angle: 360, FirstAngle: 0, SecondAngle: 0 }, placement: { position: [40, 10, 0] }, }); part.fuse({ object: "Fused", base: "B1", tool: "C1" }); check("part.fuse volume", 6000 + CY15 * 10, part.volumeOf("Fused"), { tolerance: 1e-6 }); // Cut a full cylinder out of a 20-cube. The cylinder sits wholly inside // (centred at x=y=10, spanning the full height), so the removed volume is // exactly pi*r^2*h -- no partial-quadrant guesswork. part.box("Cube", { length: 20, width: 20, height: 20 }); part.primitive("C2", { kind: "Cylinder", parameters: { Radius: 5, Height: 20, Angle: 360, FirstAngle: 0, SecondAngle: 0 }, placement: { position: [10, 10, 0] }, }); part.cut({ object: "CutResult", base: "Cube", tool: "C2" }); check("part.cut volume", 8000 - CY15 * 20, part.volumeOf("CutResult"), { tolerance: 1e-6 }); // Common of two cubes offset by 10 in X -> 10 x 20 x 20. part.box("K1", { length: 20, width: 20, height: 20 }); part.box("K2", { length: 20, width: 20, height: 20, position: [10, 0, 0] }); part.common({ object: "CommonResult", base: "K1", tool: "K2" }); check("part.common volume", 4000, part.volumeOf("CommonResult"), { tolerance: 1e-6 }); // Mesh projection: a box is 12 triangles. const mesh = part.meshOf("B1"); check("part.mesh triangleCount", 12, mesh.triangleCount, { tolerance: 0 }); check("part.mesh positions length", 108, mesh.positions.length, { tolerance: 0 }); checkTrue("part.mesh normals match positions", mesh.normals.length === mesh.positions.length); // Export -> import round trip. const exported = part.exportObject("B1", "brep"); checkTrue("part.export produced bytes", exported.bytes > 0 && exported.sha256.length === 64); } finally { try { part.close(); } catch { /* document may already be closed */ } part.dispose(); } const second = await openPart("SelfTestPartImport"); try { second.create(); const staged = second.stageFile("B1.brep", fs.readFileSync(path.join(storeRoot(), "SelfTestPart-B1.brep"))); const imported = second.importPath(staged, { object: "Imported" }); checkTrue("part.import found a solid", imported.solid !== null, JSON.stringify(imported.objects?.map(o => o.name))); check("part.import preserves volume", 6000, imported.solid?.volume, { tolerance: 1e-6 }); // An imported Part::Feature carries volume but no B-rep counters, so the // geometry is confirmed through the mesh: a 20x30x10 box is 12 triangles, // and the bounding box must match the source. const measured = second.objectOf(imported.solid.name); check("part.import volume via snapshot", 6000, measured?.volume, { tolerance: 1e-6 }); const mesh = second.meshOf(imported.solid.name); check("part.import preserves mesh triangles", 12, mesh.triangleCount, { tolerance: 0 }); checkTrue("part.import preserves bounds", JSON.stringify(mesh.bounds) === JSON.stringify([0, 0, 0, 20, 30, 10]), JSON.stringify(mesh.bounds)); } finally { try { second.close(); } catch { /* closed by save */ } second.dispose(); } return boxVolume; } // ---------------------------------------------------------- PartDesign ---- async function partDesignChecks(partBoxVolume) { const part = await openPartDesign("SelfTestPartDesign"); let gearVolume; try { // Rectangle 40x25 padded 8 -> 8000 exactly. part.sketch("Plate", { profileType: "Rectangle", parameters: { Width: 40, Height: 25 }, position: [0, 0, 0] }); part.pad("PlatePad", { profile: "Plate", length: 8 }); check("partdesign.pad volume", 8000, part.volumeOf("PlatePad"), { tolerance: 1e-6 }); // Circle r=5 pocketed through a mid-plane of the 8 mm plate: removes 2 mm. part.sketch("Bore", { profileType: "Circle", parameters: { Radius: 5 }, position: [0, 0, 0] }); part.pocket("BorePocket", { profile: "Bore", length: 28, midplane: true }); check("partdesign.pocket volume", 8000 - CY15 * 2, part.volumeOf("BorePocket"), { tolerance: 1e-6 }); // Body primitive must agree with the Part box of the same size. const other = await openPartDesign("SelfTestPartDesignPrim"); try { other.primitive("PrimBox", { primitiveType: "AdditiveBox", parameters: { Length: 20, Width: 30, Height: 10 } }); check("cross-probe box volume agrees", partBoxVolume, other.volumeOf("PrimBox"), { tolerance: 1e-6 }); } finally { try { other.close(); } catch { /* closed */ } other.dispose(); } } finally { try { part.close(); } catch { /* closed */ } part.dispose(); } // Involute gear: two independently built documents must agree exactly, and // the gear must be a real solid. Neither document carries any other feature, // so the compared volume is the gear alone -- a Pad reports the accumulated // shape of the whole body, which is why the plate document above cannot be // the reference. gearVolume = await buildGear("SelfTestGearA"); const gearAgain = await buildGear("SelfTestGearB"); check("partdesign.gear deterministic", gearVolume.volume, gearAgain.volume, { tolerance: 1e-9 }); checkTrue("partdesign.gear volume is positive", gearVolume.volume > 0, `volume=${gearVolume.volume}`); checkTrue("partdesign.gear has faces", gearVolume.faceCount > 0, `faces=${gearVolume.faceCount}`); } /** Build one stand-alone 20-tooth gear and report its measured shape. */ async function buildGear(document) { const part = await openPartDesign(document); try { part.gear("GearProfile", { gearParameters: { NumberOfTeeth: 20, Modules: 2, PressureAngle: 20, AddendumCoefficient: 1, DedendumCoefficient: 1.25, RootFilletCoefficient: 0.38, ProfileShiftCoefficient: 0, HighPrecision: false, ExternalGear: true, }, }); part.pad("GearPad", { profile: "GearProfile", length: 20 }); const object = part.objectOf("GearPad"); return { volume: object?.volume ?? 0, faceCount: object?.faceCount ?? 0 }; } finally { try { part.close(); } catch { /* closed */ } part.dispose(); } } // ------------------------------------------------------------ Assembly ---- async function assemblyChecks() { // Two source parts, each saved as its own FCStd. for (const [document, name] of [["SelfTestSrcA", "BlockA"], ["SelfTestSrcB", "BlockB"]]) { const part = await openPart(document); try { part.create(); part.box(name, { length: 40, width: 30, height: 10 }); part.saveDocument(); } finally { try { part.close(); } catch { /* closed */ } part.dispose(); } } const assembly = await openAssembly({ document: "SelfTestAsm", assembly: "Assembly", label: "自检装配" }); try { const created = assembly.create(); check("assembly.componentCount before insert", 0, created.object?.componentCount, { tolerance: 0 }); const { inserted, accepted } = assembly.insertLinks([ { file: path.join(storeRoot(), "SelfTestSrcA.FCStd"), sourceDocument: "SelfTestSrcA", sourceObject: "BlockA", position: [0, 0, 0] }, { file: path.join(storeRoot(), "SelfTestSrcB.FCStd"), sourceDocument: "SelfTestSrcB", sourceObject: "BlockB", position: [60, 0, 0], rotation: [0, 0, 0, 1] }, ]); check("assembly.insertLinks count", 2, inserted.length, { tolerance: 0 }); checkTrue("assembly.accept returned a session", Boolean(accepted), JSON.stringify(Object.keys(accepted ?? {})).slice(0, 200)); const solved = assembly.solve(); checkTrue("assembly.solve returned a result", solved !== null && typeof solved === "object"); } finally { assembly.dispose(); } } // ----------------------------------------------------------- lifecycle ---- async function lifecycleChecks() { // Same handle: create -> close document -> create again must work. const part = await openPart("SelfTestLifecycle"); try { part.create(); part.box("L1", { length: 10, width: 10, height: 10 }); check("lifecycle first document", 1000, part.volumeOf("L1"), { tolerance: 1e-6 }); part.close(); part.create(); part.box("L2", { length: 5, width: 5, height: 5 }); check("lifecycle second document", 125, part.volumeOf("L2"), { tolerance: 1e-6 }); } finally { try { part.close(); } catch { /* closed */ } part.dispose(); } } // ---------------------------------------------------------------- OPFS ---- async function opfsChecks() { const bytes = new TextEncoder().encode("fcweb selftest payload"); const stored = storeBytes("selftest-payload.txt", bytes); checkTrue("opfs storeBytes wrote a file", stored.bytes === bytes.byteLength && stored.sha256.length === 64); checkTrue("opfs hasExportFile", hasExportFile("selftest-payload.txt")); check("opfs readExportFile round-trips", bytes.byteLength, readExportFile("selftest-payload.txt").length, { tolerance: 0 }); checkTrue("opfs listExportFiles includes the payload", listExportFiles().includes("selftest-payload.txt")); for (const bad of ["../x.brep", "a/b.brep", "noext"]) { let rejected = false; try { safeName(bad); } catch { rejected = true; } checkTrue(`opfs safeName rejects ${JSON.stringify(bad)}`, rejected); } } // ----------------------------------------------------------------- run ---- const started = Date.now(); try { configureOpfs({ root: path.join(outDir, "opfs", "freecad-exports") }); const boxVolume = await partChecks(); await partDesignChecks(boxVolume); await assemblyChecks(); await lifecycleChecks(); await opfsChecks(); const report = { schema: "freecad-web/fcweb-selftest/v1", ok: results.every(item => item.ok), checks: results.length, seconds: Number(((Date.now() - started) / 1000).toFixed(2)), results, }; fs.mkdirSync(outDir, { recursive: true }); fs.writeFileSync(path.join(outDir, "selftest.json"), JSON.stringify(report, null, 2)); console.log(`\n${report.checks} checks passed in ${report.seconds}s`); const jsonArg = process.argv.indexOf("--json"); if (jsonArg >= 0 && process.argv[jsonArg + 1]) { fs.writeFileSync(path.resolve(process.argv[jsonArg + 1]), JSON.stringify(report, null, 2)); } process.exit(0); } catch (error) { console.error(`\nselftest aborted: ${error?.message ?? error}`); const report = { schema: "freecad-web/fcweb-selftest/v1", ok: false, checks: results.length, error: String(error?.message ?? error), results }; fs.mkdirSync(outDir, { recursive: true }); fs.writeFileSync(path.join(outDir, "selftest.json"), JSON.stringify(report, null, 2)); process.exit(1); }