41 lines
2.0 KiB
TypeScript
41 lines
2.0 KiB
TypeScript
import type { MessageEnvelope } from "./protocol";
|
|
|
|
const STORAGE_KEY = "linuxcnc-web-wasm:xyzac-power-off-checkpoint";
|
|
|
|
function payloadOf(message: MessageEnvelope): Record<string, unknown> {
|
|
return message.payload && typeof message.payload === "object" ? message.payload as Record<string, unknown> : {};
|
|
}
|
|
|
|
export function persistPowerOffCheckpoint(message: MessageEnvelope): { status: string; storage: string; reason?: string } | null {
|
|
const payload = payloadOf(message);
|
|
const checkpoint = payload.recovery_checkpoint;
|
|
if (message.kind !== "COMMAND_RESULT" || payload.status !== "verified" || payload.command !== "POWER" || payload.active !== false || !checkpoint || typeof checkpoint !== "object") return null;
|
|
try {
|
|
if (!globalThis.localStorage) return { status: "blocked", storage: "browser_local_storage", reason: "local_storage_unavailable" };
|
|
globalThis.localStorage.setItem(STORAGE_KEY, JSON.stringify(checkpoint));
|
|
return { status: "verified", storage: "browser_local_storage" };
|
|
} catch (error) {
|
|
return { status: "blocked", storage: "browser_local_storage", reason: error instanceof Error ? error.message : String(error) };
|
|
}
|
|
}
|
|
|
|
export function attachPersistedPowerOffCheckpoint(payload: unknown): unknown {
|
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
|
|
try {
|
|
const raw = globalThis.localStorage?.getItem(STORAGE_KEY);
|
|
if (!raw) return payload;
|
|
const checkpoint = JSON.parse(raw);
|
|
return { ...(payload as Record<string, unknown>), recovery_checkpoint: checkpoint };
|
|
} catch {
|
|
return payload;
|
|
}
|
|
}
|
|
|
|
export function clearPersistedPowerOffCheckpoint(message: MessageEnvelope): void {
|
|
const payload = payloadOf(message);
|
|
if (message.kind !== "COMMAND_RESULT" || payload.status !== "verified" || payload.command !== "POWER" || payload.active !== true) return;
|
|
try { globalThis.localStorage?.removeItem(STORAGE_KEY); } catch { /* storage cleanup is best effort */ }
|
|
}
|
|
|
|
export { STORAGE_KEY };
|