Files
linuxcncWebWASM/web/app/axis-operation-controller.mjs

49 lines
2.2 KiB
JavaScript

import { AXIS_COMMANDS, XYZAC_GATE_ACTIONS, axisGate, xyzacGate } from "./axis-contract.mjs";
export const COMMAND_ACTIONS = Object.freeze({ ...Object.fromEntries(Object.entries(AXIS_COMMANDS).map(([action, command]) => [command, action])), VISUAL_CLEAR: "vismachClear" });
export class AxisGateError extends Error {
constructor(result) {
super(result.reason);
this.name = "AxisGateError";
this.code = result.reason;
this.gate = result;
}
}
export class AxisOperationController {
constructor(client) {
if (!client || typeof client.send !== "function") throw new Error("axis_operation_client_required");
this.client = client;
this.counter = 0;
this.trace = [];
}
nextOperationId(kind) {
this.counter += 1;
return `axis-${String(kind).toLowerCase().replace(/[^a-z0-9]+/g, "-")}-${String(this.counter).padStart(6, "0")}`;
}
async execute(kind, payload = {}, { state = {}, action = COMMAND_ACTIONS[kind] ?? null, gate = true } = {}) {
const operationId = this.nextOperationId(kind);
const gateResult = action ? (XYZAC_GATE_ACTIONS.includes(action) ? xyzacGate(action, state) : axisGate(action, state)) : { action: null, enabled: true, reason: "axis_unrestricted_internal_command" };
const authoritativeGate = action && state?.gates?.[action];
const effectiveGate = authoritativeGate ?? gateResult;
if (gate && !effectiveGate.enabled) {
this.trace.push(Object.freeze({ operation_id: operationId, kind, action, phase: "blocked", reason: effectiveGate.reason }));
throw new AxisGateError(effectiveGate);
}
this.trace.push(Object.freeze({ operation_id: operationId, kind, action, phase: "pending", reason: effectiveGate.reason }));
try {
const response = await this.client.send(kind, payload, operationId);
this.trace.push(Object.freeze({ operation_id: operationId, kind, action, phase: "result", response_kind: response?.kind ?? null }));
return Object.freeze({ operationId, response, gate: effectiveGate });
} catch (error) {
this.trace.push(Object.freeze({ operation_id: operationId, kind, action, phase: "error", reason: error?.message ?? String(error) }));
throw error;
}
}
exportTrace() { return structuredClone(this.trace); }
}