// Assembly client: create an Assembly::AssemblyObject, insert linked // components, solve, export. // // Served by `FreeCADWebAssemblyProbe` -- AssemblyRuntimeProbe.cpp compiles into // that executable (CMakeLists.txt:798); the artifact name does not match the // source file name. // // Two dispatch families: // assembly.createRecompute { documentName, objectName, objectType, label } // assembly.pythonFamily { tier, records:[{apiId, args}] } // // The insertion flow is native and headless (AssemblyInsertLink.h): // open -- stage each source FCStd into the kernel FS (/tmp/assembly-links) // begin -- start an insertion session on the target assembly // insert -- one component at a time, with position + quaternion // accept -- commit the session // Desktop refuses to link into an unsaved document, so the target gets a // staging path up front; that is what keeps App::Link relative paths sane. import fs from "node:fs"; import path from "node:path"; import { STEM_ASSEMBLY, KernelError, openKernel, dispatch, } from "./kernel.mjs"; import { storeBytes } from "./opfs.mjs"; export const ASSEMBLY_OBJECT_TYPE = "Assembly::AssemblyObject"; const ASSEMBLY_SCHEMA = "freecad-web-assembly/create-recompute/v1"; function requireString(value, what) { if (typeof value !== "string" || !value.trim()) { throw new KernelError(`${what} is required`, { code: "bad_request" }); } return value; } function quaternion(value, fallback = [0, 0, 0, 1], what = "rotation") { if (value == null) return fallback; if (!Array.isArray(value) || value.length !== 4 || value.some(item => typeof item !== "number" || !Number.isFinite(item))) { throw new KernelError(`${what} must be a 4-number quaternion (got ${JSON.stringify(value)})`, { code: "bad_vector" }); } return value; } function position3(value, fallback = [0, 0, 0], what = "position") { if (value == null) return fallback; if (!Array.isArray(value) || value.length !== 3 || value.some(item => typeof item !== "number" || !Number.isFinite(item))) { throw new KernelError(`${what} must be a 3-number array (got ${JSON.stringify(value)})`, { code: "bad_vector" }); } return value; } export class AssemblySession { constructor(handle, { document, assembly, label }) { this.handle = handle; this.kernel = handle.kernel; this.document = document; this.assembly = assembly; this.label = label; this.timings = []; this.events = []; this.lastResult = null; } /** Raw call, unwrapping the pythonFamily envelope for record-shaped replies. */ dispatch(cmd, args) { const reply = dispatch(this.handle, cmd, args); if (!reply || reply.ok === false) { throw new KernelError(`${this.document} ${cmd}: ${reply?.error ?? "kernel rejected the call"}`, { code: reply?.code ?? null, action: cmd, reply }); } return reply; } /** Send one `Assembly:desktop:*` command through assembly.pythonFamily. */ command(apiId, args = {}, { tier = "tier-1-readonly" } = {}) { const reply = this.dispatch("assembly.pythonFamily", { tier, records: [{ apiId: `Assembly:desktop:${apiId}`, name: apiId, family: "assembly", args }], }); const record = (reply.records ?? []).find(item => item?.apiId === `Assembly:desktop:${apiId}`) ?? reply.records?.[0]; if (!record) throw new KernelError(`${apiId}: no record in reply`, { code: "bad_reply", action: apiId, reply }); if (record.status !== "exposed") { throw new KernelError(`${apiId}: ${record.message ?? record.status}`, { code: record.code ?? record.status, action: apiId, reply, }); } this.lastResult = record.result ?? null; return this.lastResult; } create() { const reply = this.dispatch("assembly.createRecompute", { documentName: this.document, objectName: this.assembly, objectType: ASSEMBLY_OBJECT_TYPE, label: this.label, }); if (reply.ok === false) { throw new KernelError(`${this.document} create assembly: ${reply.error ?? "failed"}`, { code: reply.code ?? null, reply }); } this.lastResult = reply; return reply; } componentCount() { return this.lastResult?.object?.componentCount ?? null; } /** * Insert components. Each item is * { file: ".FCStd", sourceDocument, sourceObject, position, rotation, rigid } * and `file` must be readable on the host; its bytes are staged into the * kernel before the session opens, because the native flow reads them from * /tmp/assembly-links. */ insertLinks(items, { groundFirst = true } = {}) { if (!Array.isArray(items) || items.length === 0) { throw new KernelError("insertLinks requires a non-empty items array", { code: "bad_request" }); } const files = new Map(); for (const item of items) { requireString(item.file, "item.file"); requireString(item.sourceDocument, "item.sourceDocument"); requireString(item.sourceObject, "item.sourceObject"); const key = path.basename(item.file); if (!files.has(key)) { const bytes = fs.readFileSync(item.file); files.set(key, { fileName: key, contentBase64: bytes.toString("base64") }); } } const base = { documentId: this.document, assembly: this.assembly }; // 1. Stage the source documents inside the kernel FS. this.command("Assembly_InsertLink", { ...base, action: "open", files: [...files.values()] }); // 2. Start the insertion session. this.command("Assembly_InsertLink", { ...base, action: "begin" }); // 3. Insert one component at a time. const inserted = []; for (const [index, item] of items.entries()) { const result = this.command("Assembly_InsertLink", { ...base, action: "insert", sourceDocument: item.sourceDocument, sourceObject: item.sourceObject, position: position3(item.position), rotation: quaternion(item.rotation), rigid: item.rigid !== false, groundFirst: groundFirst && index === 0, }); inserted.push({ file: path.basename(item.file), sourceDocument: item.sourceDocument, sourceObject: item.sourceObject, position: position3(item.position), rotation: quaternion(item.rotation), result, }); } // 4. Commit. const accepted = this.command("Assembly_InsertLink", { ...base, action: "accept" }); return { inserted, accepted }; } solve() { return this.command("Assembly_SolveAssembly", { documentId: this.document, assembly: this.assembly }); } exportASMT({ name } = {}) { const result = this.command("Assembly_ExportASMT", { documentId: this.document, assembly: this.assembly }); const encoded = result?.content ?? result?.base64 ?? null; if (!encoded) return { ...result, bytes: 0, stored: null }; const bytes = Buffer.from(String(encoded), "base64"); return { ...result, bytes: bytes.byteLength, stored: storeBytes(name ?? `${this.document}.asmt`, bytes) }; } bom() { return this.command("Assembly_CreateBom", { documentId: this.document, assembly: this.assembly }); } trace() { return { schema: "freecad-web-process-trace/v1", document: this.document, builder: "assembly", totals: { steps: this.events.length, timings: this.timings }, events: this.events, }; } } export async function openAssembly({ document, assembly = "Assembly", label = "Assembly", kernelDirs, print, printErr } = {}) { requireString(document, "document"); const handle = await openKernel({ stem: STEM_ASSEMBLY, dirs: kernelDirs, print, printErr }); const session = new AssemblySession(handle, { document, assembly, label }); session.dispose = () => handle.close(); return session; }