import type { LogOutputEntry } from './LogOutput'; /** Data blocks above either limit start collapsed. */ export interface LogDataLimits { /** UTF-8 byte size of the pretty-printed data. */ bytes: number; /** Line count of the pretty-printed data. */ lines: number; } export const DEFAULT_LOG_DATA_LIMITS: LogDataLimits = { bytes: 256, lines: 5 }; const encoder = new TextEncoder(); /** * "+12s" (or "-" if before startTime, e.g. clock skew). Log timestamps are * stored with second resolution, so fractions would be noise. */ export function formatElapsed(deltaMs: number): string { const sign = deltaMs < 0 ? '-' : '+'; return `${sign}${Math.round(Math.abs(deltaMs) / 1000)}s`; } /** Pretty-prints `data` if it's valid JSON, otherwise returns it as-is. */ export function prettyData(data: string): string { try { return JSON.stringify(JSON.parse(data), null, 2); } catch { return data; } } /** Byte size and line count of an already pretty-printed data block. */ export function measureData(pretty: string): { bytes: number; lines: number } { return { bytes: encoder.encode(pretty).length, lines: pretty.split('\n').length }; } export function exceedsLimits(size: { bytes: number; lines: number }, limits: LogDataLimits) { return size.bytes > limits.bytes || size.lines > limits.lines; } /** True if any entry's data block exceeds the limits (i.e. renders collapsed by default). */ export function hasLargeData( entries: Pick[], limits: LogDataLimits = DEFAULT_LOG_DATA_LIMITS, ): boolean { return entries.some((e) => e.data && exceedsLimits(measureData(prettyData(e.data)), limits)); } /** * Plain-text rendering of the log, one entry per line with every data block * pretty-printed and indented below its line (e.g. for copying to the clipboard). */ export function formatLogText( entries: LogOutputEntry[], startTime?: string | number | Date, ): string { if (entries.length === 0) return ''; const startMs = new Date(startTime ?? entries[0].createdAt).getTime(); return entries .map((entry) => { const elapsed = formatElapsed(new Date(entry.createdAt).getTime() - startMs); const context = entry.context ? ` [${entry.context}]` : ''; const header = `${elapsed.padStart(6)} ${entry.level.toUpperCase().padEnd(5)}${context} ${entry.message}`; if (!entry.data) return header; const data = prettyData(entry.data) .split('\n') .map((line) => ` ${line}`) .join('\n'); return `${header}\n${data}`; }) .join('\n'); }