Files
FreeCADWasmDev/tools/run_p6_sandbox_ax2_xdir_method_gate.mjs
wangdequan 9a7c4f0335 Save FreeCAD Web workspace sources and user validation evidence
IFC native binding remains incomplete; preserve accurate test results.
2026-09-15 22:01:58 +08:00

90 lines
9.3 KiB
JavaScript

#!/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 { execFileSync } from "node:child_process";
import { Worker } from "node:worker_threads";
import { pathToFileURL } from "node:url";
const root = "/home/mes123456/FreeCADWasmDev/working/FreeCAD";
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-sandbox-ax2-"));
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",
...["facade-envelope.ts", "sandbox-python-family-facade.ts", "sandbox-python-facade.ts", "python-api-runtime.ts", "python-family-dispatcher.ts", "module-router.ts", "api-method-bridge.ts"].map((name) => path.join(root, "web/src", name)),
], { cwd: root, stdio: "inherit" });
globalThis.__dirname = `${build}${path.sep}`;
globalThis.require = createRequire(import.meta.url);
const loader = await import(pathToFileURL(path.join(build, "FreeCADWebSandboxRuntimeProbe.js")));
const kernel = await loader.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebSandboxRuntimeProbe.wasm")), locateFile: (file) => path.join(build, file), print: () => {}, printErr: () => {} });
const facade = await import(pathToFileURL(path.join(out, "sandbox-python-family-facade.js")));
const envelope = await import(pathToFileURL(path.join(out, "facade-envelope.js")));
const bridgeModule = await import(pathToFileURL(path.join(out, "api-method-bridge.js")));
const apiId = "py:Sandbox:function:ax2_xdir";
const record = { apiId, name: "ax2_xdir", family: "pure-function", sourcePath: "src/Mod/Sandbox/exportDRAWEXE.py", disposition: "not_implemented", args: { normal: { x: 1, y: 2, z: 3 } } };
const makeRequest = (requestId, value = record) => facade.createSandboxPythonFamilyRequest(requestId, [value], "tier-2-pure");
const queue = new envelope.FacadeSerialQueue();
const dispatch = (request, source = kernel) => facade.dispatchSandboxPythonFamily(queue, request, source);
const success = await dispatch(makeRequest("sandbox-ax2-success"));
const repeat = await dispatch(makeRequest("sandbox-ax2-repeat"));
const invalid = await dispatch(makeRequest("sandbox-ax2-invalid", { ...record, args: { normal: { x: "bad", y: 2, z: 3 } } }));
const cross = await dispatch(makeRequest("sandbox-ax2-cross", { ...record, apiId: "py:BIM:function:ax2_xdir" }));
const cancelRequest = makeRequest("sandbox-family-cancel-1");
const cancelledPromise = dispatch(cancelRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25)));
const cancelAccepted = queue.cancel(envelope.createCancel("sandbox-ax2-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: facade.SANDBOX_PYTHON_FAMILY_COMMAND, args: { tier: "tier-2-pure", records: [record] } });
const unsupported = invoke({ cmd: "sandbox.unknown", args: {} });
const runtimeIndex = JSON.parse(fs.readFileSync(path.join(root, "web/public/api/python-api-index.json"), "utf8"));
const router = { request: async (_module, _command, payload) => envelope.createSuccess("sandbox-ax2-router", await facade.handleSandboxPythonFamily(payload, new AbortController().signal, kernel)) };
const bridge = new bridgeModule.ApiMethodBridge(router, runtimeIndex);
const bridgeSuccess = await bridge.call({ apiId, args: [1, 2, 3] });
const bridgeInvalid = await bridge.call({ apiId, args: ["bad", 2, 3] });
const worker = new Worker(path.join(root, "tools/sandbox-python-family-facade-smoke-worker.mjs"), { workerData: { buildDirectory: build, facadePath: pathToFileURL(path.join(out, "sandbox-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", onError); resolve(value); }; const onError = (error) => { worker.off("message", onMessage); reject(error); }; worker.once("message", onMessage); worker.once("error", onError); });
const ready = await receive();
worker.postMessage(makeRequest("sandbox-ax2-worker")); const workerSuccess = await receive();
worker.postMessage(makeRequest("sandbox-ax2-worker")); const workerDuplicate = await receive();
await worker.terminate();
const trace = { success, repeat, invalid, cross, cancelled, direct, unsupported, bridgeSuccess, bridgeInvalid, worker: { ready, workerSuccess, workerDuplicate } };
if (success.kind !== "result" || success.result.records[0]?.status !== "exposed" || success.result.records[0]?.result?.x !== 0 || success.result.records[0]?.result?.y !== 3 || success.result.records[0]?.result?.z !== -2 || success.result.resourcesReleased !== true) throw new Error(`Sandbox.ax2_xdir native result failed: ${JSON.stringify(trace)}`);
if (repeat.kind !== "result" || JSON.stringify(success.result) !== JSON.stringify(repeat.result)) throw new Error("Sandbox.ax2_xdir replay changed");
if (invalid.kind !== "result" || invalid.result.records[0]?.status !== "not_implemented" || invalid.result.records[0]?.code !== "source_error") throw new Error("Sandbox.ax2_xdir invalid arguments were accepted");
if (cross.kind !== "result" || cross.result.records[0]?.code !== "unmatched_source_record") throw new Error("Sandbox.ax2_xdir cross-module boundary failed");
if (!cancelAccepted || cancelled.kind !== "error" || cancelled.error.code !== "cancelled") throw new Error("Sandbox.ax2_xdir cancellation failed");
if (direct.ok !== true || direct.records[0]?.result?.x !== 0 || direct.records[0]?.result?.y !== 3 || unsupported.ok !== false || unsupported.code !== "unsupported_command") throw new Error("Sandbox.ax2_xdir dispatcher boundary failed");
if (bridgeSuccess.kind !== "result" || bridgeSuccess.result.records?.[0]?.result?.x !== 0 || bridgeInvalid.kind !== "error" || bridgeInvalid.error.code !== "invalid_arguments") throw new Error("Sandbox.ax2_xdir API bridge failed");
if (ready.kind !== "ready" || workerSuccess.kind !== "result" || workerSuccess.result.records[0]?.result?.x !== 0 || workerDuplicate.kind !== "error" || workerDuplicate.error.code !== "duplicate_request") throw new Error("Sandbox.ax2_xdir Worker sequencing failed");
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 === apiId);
if (!row) throw new Error("Sandbox.ax2_xdir is missing from python-api-manifest.json");
row.disposition = "exposed";
row.dispositionEvidence = ["docs/p6/sandbox-ax2-xdir-method-runtime.json"];
row.dispositionReason = "official Sandbox exportDRAWEXE.py:ax2_xdir source replay through fc_web_dispatch_json";
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
execFileSync("python3", [path.join(root, "tools/generate_python_api_runtime_index.py")], { cwd: root, stdio: "inherit" });
const report = {
schema: "freecad-web-p6-sandbox-ax2-xdir-method-runtime/v1", taskId: "FW-P6-FPA-Y", module: "Sandbox", tier: "tier-2-pure", apiId, status: "pass",
source: { entry: "src/Mod/Sandbox/exportDRAWEXE.py", function: "ax2_xdir", revision: success.result.records[0].sourceRevision },
route: { command: facade.SANDBOX_PYTHON_FAMILY_COMMAND, worker: "web/src/sandbox-python.worker.ts", facade: "web/src/sandbox-python-family-facade.ts", apiBridge: "web/src/api-method-bridge.ts", native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/SandboxRuntimeProbe.cpp:fc_web_dispatch_json" },
request: makeRequest("sandbox-ax2-success"), requestSha256: hash(makeRequest("sandbox-ax2-success")), trace, traceSha256: hash(trace), replay: { equal: true, resultSha256: hash(repeat.result) }, resources: { resourcesReleased: true, documentMutation: false },
artifacts: { wasm: { path: "web/public/kernel/FreeCADWebSandboxRuntimeProbe.wasm", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebSandboxRuntimeProbe.wasm")) }, loader: { path: "web/public/kernel/FreeCADWebSandboxRuntimeProbe.js", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebSandboxRuntimeProbe.js")) } },
boundaries: ["Malformed numeric components remain source_error from the official function path.", "Cross-module IDs remain unmatched_source_record.", "All values derive from compiled FreeCAD source through fc_web_dispatch_json; JavaScript only carries the typed envelope."]
};
fs.writeFileSync(path.join(root, "docs/p6/sandbox-ax2-xdir-method-runtime.json"), `${JSON.stringify(report, null, 2)}\n`);
fs.writeFileSync(path.join(root, "docs/freecad-p6-sandbox-ax2-xdir-method-gate.log"), `${JSON.stringify({ status: report.status, apiId: report.apiId, result: success.result.records[0].result, traceSha256: report.traceSha256 })}\n`);
console.log(JSON.stringify({ status: report.status, apiId: report.apiId, result: success.result.records[0].result, traceSha256: report.traceSha256 }));
process.exit(0);