/** * Client-side dev console log for the minigame developer dock. * * A module-level ring buffer (newest last, capped at MAX_ENTRIES) shared by * every panel in the dock: game panels push entries when they send actions, * the dock itself pushes snapshot-received entries, and the Log tab renders * the buffer live. Optional console mirroring writes each entry to * `console.debug` as well so a devtools console tells the same story. */ export type DevLogKind = "info" | "action" | "state" | "error"; export interface DevLogEntry { readonly id: number; /** ISO instant the entry was recorded. */ readonly at: string; readonly kind: DevLogKind; readonly text: string; } const MAX_ENTRIES = 200; const MIRROR_KEY = "ptf.dev.consoleMirror"; let entries: DevLogEntry[] = []; let nextId = 1; const listeners = new Set<() => void>(); function readMirrorFlag(): boolean { if (typeof window === "undefined") return false; try { return window.localStorage.getItem(MIRROR_KEY) === "1"; } catch { return false; } } let mirror = readMirrorFlag(); function emit(): void { for (const listener of listeners) listener(); } /** Append an entry, dropping the oldest when the buffer is full. */ export function pushDevLog(kind: DevLogKind, text: string): void { const entry: DevLogEntry = { id: nextId++, at: new Date().toISOString(), kind, text }; entries = [...entries, entry].slice(-MAX_ENTRIES); if (mirror) console.debug(`[dev-console] ${kind}: ${text}`); emit(); } export function clearDevLog(): void { if (entries.length === 0) return; entries = []; emit(); } /** Stable snapshot reference for useSyncExternalStore (replaced on every push). */ export function getDevLogEntries(): readonly DevLogEntry[] { return entries; } export function subscribeDevLog(listener: () => void): () => void { listeners.add(listener); return () => listeners.delete(listener); } export function isDevLogMirrored(): boolean { return mirror; } export function setDevLogMirror(on: boolean): void { mirror = on; if (typeof window !== "undefined") { try { window.localStorage.setItem(MIRROR_KEY, on ? "1" : "0"); } catch { // Storage unavailable (private mode): the flag just stays session-only. } } emit(); } /** Plain-text dump of the whole buffer, newest last. */ export function formatDevLog(entriesToFormat: readonly DevLogEntry[] = entries): string { return entriesToFormat.map((entry) => `${entry.at} [${entry.kind}] ${entry.text}`).join("\n"); }