#!/usr/bin/env node import crypto from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { createRequire } from "node:module"; import { Worker } from "node:worker_threads"; import { fileURLToPath, pathToFileURL } from "node:url"; import { execFileSync } from "node:child_process"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const build = path.resolve(process.argv[2] ?? path.join(root, "freecad-source/build-web/configure/bin")); const out = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-p6-material-string2tuple-")); const hash = (value) => crypto.createHash("sha256").update(typeof value === "string" ? value : JSON.stringify(value)).digest("hex"); const fileHash = (file) => hash(fs.readFileSync(file)); execFileSync(path.join(root, "web/node_modules/.bin/tsc"), ["--target", "ES2022", "--module", "ESNext", "--moduleResolution", "Bundler", "--strict", "--skipLibCheck", "--outDir", out, "--declaration", "false", "--noEmit", "false", "web/src/facade-envelope.ts", "web/src/material-python-family-facade.ts"], { cwd: root, stdio: "inherit" }); globalThis.__dirname = `${build}${path.sep}`; globalThis.require = createRequire(import.meta.url); const loader = await import(pathToFileURL(path.join(build, "FreeCADWebMaterialKernelProbe.js"))); const kernel = await loader.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebMaterialKernelProbe.wasm")), locateFile: (file) => path.join(build, file), print: () => {}, printErr: () => {} }); const facade = await import(pathToFileURL(path.join(out, "material-python-family-facade.js"))); const envelope = await import(pathToFileURL(path.join(out, "facade-envelope.js"))); const record = { apiId: "py:Material:function:string2tuple", name: "string2tuple", family: "pure-function", kind: "function", sourcePath: "src/Mod/Material/MaterialEditor.py", disposition: "not_implemented", args: { value: "(0.1,0.2,0.3,1.0)" } }; const request = facade.createMaterialPythonFamilyRequest("material-string2tuple-success", [record], "tier-2-pure"); const queue = new envelope.FacadeSerialQueue(); const success = await facade.dispatchMaterialPythonFamily(queue, request, kernel); const repeat = await facade.dispatchMaterialPythonFamily(queue, facade.createMaterialPythonFamilyRequest("material-string2tuple-repeat", [record], "tier-2-pure"), kernel); const malformed = await facade.dispatchMaterialPythonFamily(queue, { ...request, requestId: "material-string2tuple-malformed", payload: { ...request.payload, tier: "tier-unsupported" } }, kernel); const invalidRequest = facade.createMaterialPythonFamilyRequest("material-string2tuple-invalid", [{ ...record, args: { value: "(0.1,0.2)" } }], "tier-2-pure"); const invalid = await facade.dispatchMaterialPythonFamily(queue, invalidRequest, kernel); const duplicateRequest = facade.createMaterialPythonFamilyRequest("material-string2tuple-duplicate", [record], "tier-2-pure"); const delayed = facade.dispatchMaterialPythonFamily(queue, duplicateRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25))); const duplicate = await facade.dispatchMaterialPythonFamily(queue, duplicateRequest, kernel); const duplicateResult = await delayed; const cancelRequest = facade.createMaterialPythonFamilyRequest("material-string2tuple-cancel", [record], "tier-2-pure"); const cancelledPromise = facade.dispatchMaterialPythonFamily(queue, cancelRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25))); const cancelAccepted = queue.cancel(envelope.createCancel("material-string2tuple-cancel-control", cancelRequest.requestId)); const cancelled = await cancelledPromise; const invoke = (value) => JSON.parse(String(kernel.ccall("fc_web_dispatch_json", "string", ["string"], [JSON.stringify(value)]))); const direct = invoke({ cmd: "material.pythonFamilyBatch", args: { tier: "tier-2-pure", records: [record] } }); const directRepeat = invoke({ cmd: "material.pythonFamilyBatch", args: { tier: "tier-2-pure", records: [record] } }); const crossModule = invoke({ cmd: "material.pythonFamilyBatch", args: { tier: "tier-2-pure", records: [{ ...record, apiId: "py:Part:function:string2tuple" }] } }); const unsupported = invoke({ cmd: "material.unknown", args: {} }); if (success.kind !== "result" || success.result.records[0]?.status !== "exposed" || JSON.stringify(success.result.records[0]?.result) !== JSON.stringify([25, 51, 76, 255]) || success.result.resourcesReleased !== true) throw new Error(`native Material string2tuple method failed: ${JSON.stringify(success)}`); if (repeat.kind !== "result" || JSON.stringify(success.result) !== JSON.stringify(repeat.result)) throw new Error("Material string2tuple replay changed"); if (malformed.kind !== "error" || malformed.error.code !== "invalid_request") throw new Error(`invalid Material string2tuple envelope was accepted: ${JSON.stringify(malformed)}`); if (invalid.kind !== "result" || invalid.result.records[0]?.status !== "not_implemented" || invalid.result.records[0]?.code !== "source_error") throw new Error(`invalid Material string2tuple source fixture was not rejected: ${JSON.stringify(invalid)}`); if (duplicate.kind !== "error" || duplicate.error.code !== "duplicate_request" || duplicateResult.kind !== "result") throw new Error(`Material string2tuple duplicate sequencing failed: ${JSON.stringify({ duplicate, duplicateResult })}`); if (!cancelAccepted || cancelled.kind !== "error" || cancelled.error.code !== "cancelled") throw new Error(`Material string2tuple cancellation failed: ${JSON.stringify(cancelled)}`); if (direct.ok !== true || direct.records[0]?.status !== "exposed" || JSON.stringify(direct.records[0]?.result) !== JSON.stringify([25, 51, 76, 255]) || JSON.stringify(direct) !== JSON.stringify(directRepeat)) throw new Error(`direct Material string2tuple dispatch failed: ${JSON.stringify({ direct, directRepeat })}`); if (crossModule.ok !== true || crossModule.records?.[0]?.status !== "not_implemented" || crossModule.records?.[0]?.code !== "unmatched_source_record" || unsupported.ok !== false || unsupported.code !== "unsupported_command") throw new Error(`Material string2tuple boundaries failed: ${JSON.stringify({ crossModule, unsupported })}`); const worker = new Worker(path.join(root, "tools/material-python-family-facade-smoke-worker.mjs"), { workerData: { buildDirectory: build, facadePath: pathToFileURL(path.join(out, "material-python-family-facade.js")).href, envelopePath: pathToFileURL(path.join(out, "facade-envelope.js")).href } }); const receive = () => new Promise((resolve, reject) => { const onMessage = (value) => { worker.off("error", reject); resolve(value); }; worker.once("message", onMessage); worker.once("error", reject); }); const ready = await receive(); worker.postMessage(request); const workerSuccess = await receive(); worker.postMessage(request); const workerDuplicate = await receive(); const workerCancel = facade.createMaterialPythonFamilyRequest("material-string2tuple-worker-cancel", [record], "tier-2-pure"); const workerCancelledPromise = new Promise((resolve, reject) => { const onMessage = (value) => { if (value.requestId === workerCancel.requestId) { worker.off("error", reject); resolve(value); } }; worker.on("message", onMessage); worker.once("error", reject); }); worker.postMessage(workerCancel); worker.postMessage(envelope.createCancel("material-string2tuple-worker-cancel-control", workerCancel.requestId)); const workerCancelled = await workerCancelledPromise; worker.postMessage({ kind: "reset", requestId: "material-string2tuple-worker-reset" }); const reset = await receive(); await worker.terminate(); if (ready.kind !== "ready" || workerSuccess.kind !== "result" || workerSuccess.result.records[0]?.status !== "exposed" || workerDuplicate.kind !== "error" || workerDuplicate.error.code !== "duplicate_request" || workerCancelled.kind !== "error" || workerCancelled.error.code !== "cancelled" || reset.requestId !== "material-string2tuple-worker-reset") throw new Error(`Material string2tuple Worker sequencing failed: ${JSON.stringify({ ready, workerSuccess, workerDuplicate, workerCancelled, reset })}`); const trace = { success, repeat, malformed, invalid, duplicate, duplicateResult, cancelled, direct, directRepeat, crossModule, unsupported }; const workerTrace = { ready, success: workerSuccess, duplicate: workerDuplicate, cancelled: workerCancelled, reset }; const report = { schema: "freecad-web-p6-material-string2tuple-method-runtime/v1", taskId: "FW-P6-FPA-Y", module: "Material", tier: "tier-2-pure", apiId: record.apiId, status: "pass", route: { command: facade.MATERIAL_PYTHON_FAMILY_COMMAND, worker: "web/src/material.worker.ts", facade: "web/src/material-python-family-facade.ts", native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/MaterialKernelProbe.cpp:fc_web_dispatch_json" }, source: { entry: "src/Mod/Material/MaterialEditor.py", line: 948, revision: success.result.records[0].sourceRevision, function: "string2tuple", guiImportBoundary: "the official function definition is extracted without executing MaterialEditor GUI imports" }, request, requestSha256: hash(request), trace, traceSha256: hash(trace), worker: { trace: workerTrace, traceSha256: hash(workerTrace), sequencing: { duplicate: true, cancelAccepted: true, resetAccepted: true, maxActive: 1 } }, replay: { equal: true, resultSha256: hash(repeat.result) }, resources: { resourcesReleased: true, documentMutation: false }, artifacts: { wasm: { path: "web/public/kernel/FreeCADWebMaterialKernelProbe.wasm", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebMaterialKernelProbe.wasm")) }, loader: { path: "web/public/kernel/FreeCADWebMaterialKernelProbe.js", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebMaterialKernelProbe.js")) } }, commands: ["ninja -C freecad-source/build-web/configure FreeCADWebMaterialKernelProbe -j8", "cp FreeCADWebMaterialKernelProbe.js/.wasm web/public/kernel/", "node tools/run_p6_material_string2tuple_method_gate.mjs freecad-source/build-web/configure/bin"], boundaries: ["MaterialEditor top-level Qt/FreeCADGui imports and editor UI remain headless boundaries; only the official pure function definition is executed.", "All result fields and statuses derive from compiled FreeCAD through fc_web_dispatch_json; no JavaScript API result is substituted."] }; const manifestPath = path.join(root, "docs/p6/python-api-manifest.json"); const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); const row = manifest.records.find((entry) => entry.id === record.apiId); if (!row) throw new Error("Material string2tuple is missing from python-api-manifest.json"); row.disposition = "exposed"; row.dispositionEvidence = ["docs/p6/material-string2tuple-method-runtime.json"]; row.dispositionReason = "official MaterialEditor.string2tuple source replay through fc_web_dispatch_json"; fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); report.resultSha256 = hash({ trace, worker: report.worker, source: report.source, resources: report.resources }); fs.writeFileSync(path.join(root, "docs/p6/material-string2tuple-method-runtime.json"), `${JSON.stringify(report, null, 2)}\n`); fs.writeFileSync(path.join(root, "docs/freecad-p6-material-string2tuple-method.log"), `${JSON.stringify({ status: report.status, apiId: report.apiId, result: direct.records[0].result, resourcesReleased: report.resources.resourcesReleased, traceSha256: report.traceSha256, workerTraceSha256: report.worker.traceSha256, resultSha256: report.resultSha256 })}\n`); console.log(JSON.stringify({ status: report.status, apiId: report.apiId, result: direct.records[0].result, workerCancel: workerCancelled.error.code, resultSha256: report.resultSha256 })); process.exit(0);