/** * Debug logging sink for pi extensions. * * Pure logging — no UI coupling, no file I/O, no flag/command registration. * A sister extension (extensions/dbg.ts) handles the /dbg command, * file writing, rotation, and the tail panel. * * Uses globalThis for shared state because jiti may load this module * multiple times with separate module identities, each getting its own * module-scoped variables. globalThis survives across jiti instances. * * Usage: * import { dbgScope } from "lib/dbg"; * * const log = dbgScope("remember"); * log("session started", { cwd }); * log("saved fact", { id: "RM001" }); * * // Unscoped: * import { dbg } from "lib/dbg"; * dbg("something happened"); */ import type { DbgSettings } from "./settings.ts"; import { getSettings } from "./settings.ts"; // ── Types ──────────────────────────────────────────────────────────────── export interface DbgLogEntry { ts: string; source: string; msg: string; } type LogSink = (entry: DbgLogEntry) => void; // ── State via globalThis ───────────────────────────────────────────────── // jiti loads this module multiple times with separate identities. // Module-scoped let/const are NOT shared across those instances. // globalThis IS shared — it's the same JS global across all jiti modules. const G = globalThis as unknown as { __pi_dbg_enabled?: boolean; __pi_dbg_sink?: LogSink; }; // Initialize defaults (idempotent — only first import wins) if (G.__pi_dbg_enabled === undefined) G.__pi_dbg_enabled = false; if (G.__pi_dbg_sink === undefined) G.__pi_dbg_sink = () => {}; // Eagerly activate if --dbg flag or persisted settings say so if (!G.__pi_dbg_enabled) { const saved = getSettings("dbg"); if (saved.enabled) { G.__pi_dbg_enabled = true; } else if (typeof process !== "undefined") { if (process.env.PI_DBG === "1" || process.argv?.includes("--dbg")) { G.__pi_dbg_enabled = true; } } } // ── Formatting ─────────────────────────────────────────────────────────── function formatArgs(args: unknown[]): string { return args .map(a => a instanceof Error ? `${a.message}\n${a.stack}` : typeof a === "object" ? JSON.stringify(a, null, 2) : String(a), ) .join(" "); } // ── Public API ─────────────────────────────────────────────────────────── /** Whether debug mode is enabled. */ export function isDbgEnabled(): boolean { return G.__pi_dbg_enabled ?? false; } /** Enable or disable debug mode (in-memory). */ export function setDbgEnabled(enabled: boolean): void { G.__pi_dbg_enabled = enabled; } /** Set the log sink. Called by the dbg extension. */ export function setDbgSink(sink: LogSink): void { G.__pi_dbg_sink = sink; } /** Unscoped log (source = "dbg"). */ export function dbg(...args: unknown[]): void { if (!G.__pi_dbg_enabled) return; G.__pi_dbg_sink?.({ ts: new Date().toISOString(), source: "dbg", msg: formatArgs(args) }); } /** * Create a scoped logger. Returns a function that tags every entry * with the given source string. Use for fuzzy filtering in tail panel. * * const log = dbgScope("remember"); * log("session started", { cwd }); */ export function dbgScope(source: string): (...args: unknown[]) => void { return (...args: unknown[]) => { if (!G.__pi_dbg_enabled) return; G.__pi_dbg_sink?.({ ts: new Date().toISOString(), source, msg: formatArgs(args) }); }; } /** * Debug-gated soft check. Logs when condition is false and debug is on. * Never throws, no type narrowing. */ export function dbgCheck(condition: boolean, message = "check failed"): void { if (!condition && G.__pi_dbg_enabled) { dbg(`CHECK: ${message}`); } }