/** * @fileoverview Logger avanzado con arquitectura modular y API simplificada * * Sistema de logging profesional con estilos CSS avanzados, temas adaptativos, * badges automáticos, contextos temporales y exportación de datos. */ import type { LogLevel, LogTag, Verbosity, ThemeVariant, BannerType, LoggerConfig, ILogHandler, StyleOptions, Bindings, SerializerFn, HookEvent, HookCallback, MiddlewareFn, TransportTarget, TransportRecord, ILogResourceRef, StackInfo } from './types/index.js'; import { SerializerRegistry } from './serializers/index.js'; import { HookManager } from './hooks/index.js'; import { TransportManager } from './transports/index.js'; import { ScopedLogger, APILogger, ComponentLogger } from './ScopedLogger.js'; import type { CLILogLevel, ISpinnerHandle, IBoxOptions, ITableOptions } from './types/index.js'; /** * Clase principal Logger con capacidades avanzadas de logging * * @class Logger * @description Sistema completo de logging con temas, badges, contextos y exportación. * Detecta automáticamente el tema claro/oscuro del navegador. * * @example * // Uso básico sin configuración * import logger from '@mks2508/better-logger'; * logger.info('Aplicación iniciada'); * logger.success('Conexión establecida'); * * @example * // Aplicar un preset temático * logger.preset('cyberpunk'); * logger.warn('Advertencia con estilo neón'); * * @example * // Logger con scope para componentes * const auth = logger.component('Autenticación'); * auth.info('Usuario intentando login'); * auth.success('Login exitoso'); * */ export declare class Logger { private config; private scopedPrefix?; private handlers; private timers; private groupDepth; private cliProcessor?; private themeChangeListener?; private badgeList; private displaySettings; private serializerBridge; private hookBridge; private logContext; private transportBridge; /** Set during success() so log() skips its own dispatch (N2 fix). */ private _successTagDispatched; private styleManager; /** Whether CLI primitives (step, box, header, etc.) should be shown*/ private _showPrimitives; private terminalBridge; /** * Active smart-preset reference (set by `preset()`). Typed as `unknown` * to keep the public surface clean; consumed by `createStyledOutput`. */ private _activePreset?; /** * Name of the active smart-preset. Stored separately so theme-change * detection can re-render without re-running the preset body. */ private _activePresetName?; /** * Last-applied `customize()` overrides. Stored for later read by * `createStyledOutput`. */ private _customization?; /** * This logger's own context bindings (from child() calls). * Single source of truth for this logger's contribution to the context chain. * @private */ private _bindings; /** * Reference to the parent's merged context record at the time this logger * was created. Together with _bindings, forms the context chain. * Undefined for the root logger. * @private */ private _parentContextRecord; /** * Crea una nueva instancia del Logger * * @param {Partial} config - Configuración opcional del logger * * @example * // Logger con configuración personalizada * const logger = new Logger({ * theme: 'neon', * globalPrefix: 'MiApp', * verbosity: 'debug', * bufferSize: 1000 * }); */ constructor(config?: Partial); /** * Configura la detección automática de tema con listener de cambios * @private * @description Detecta automáticamente si el navegador está en modo claro u oscuro */ private setupAutoThemeDetection; /** * Obtiene la configuración actual del logger * * @returns {LoggerConfig} Configuración completa actual * * @example * const config = logger.getConfig(); * console.log('Verbosidad actual:', config.verbosity); * console.log('Tema actual:', config.theme); * */ getConfig(): LoggerConfig; /** * Actualiza la configuración del logger * * @param {Partial} updates - Propiedades a actualizar * * @example * logger.updateConfig({ * verbosity: 'debug', * enableTimestamps: false, * theme: 'cyberpunk' * }); * */ updateConfig(updates: Partial): void; /** * Establece el prefijo global para todos los mensajes de log * * @param {string} prefix - Prefijo a usar * * @example * logger.setGlobalPrefix('MiApp'); * logger.info('Iniciado'); // [MiApp] Iniciado * */ setGlobalPrefix(prefix: string): void; /** * Establece el nivel de verbosidad para filtrar la salida de logs * * @param {Verbosity} level - Nivel mínimo a mostrar ('debug' | 'info' | 'warn' | 'error' | 'critical' | 'silent') * * @example * logger.setVerbosity('warn'); // Solo muestra warn, error y critical * logger.setVerbosity('debug'); // Muestra todos los niveles * logger.setVerbosity('silent'); // No muestra nada * */ setVerbosity(level: Verbosity): void; /** * Establece el tema del logger * * @param {ThemeVariant} theme - Tema a aplicar ('default' | 'dark' | 'light' | 'neon' | 'minimal' | 'cyberpunk') * * @example * logger.setTheme('neon'); // Tema con colores neón * logger.setTheme('minimal'); // Tema minimalista * logger.setTheme('cyberpunk'); // Tema cyberpunk con efectos * */ setTheme(theme: ThemeVariant): void; /** * Establece el tipo de banner para mostrar en la inicialización * * @param {BannerType} bannerType - Tipo de banner ('simple' | 'ascii' | 'unicode' | 'svg' | 'animated') * * @example * logger.setBannerType('ascii'); // Banner con arte ASCII * logger.setBannerType('unicode'); // Banner con caracteres Unicode * logger.setBannerType('animated'); // Banner con animación * */ setBannerType(bannerType: BannerType): void; /** * Runs `fn` within an AsyncLocalStorage scope where `bindings` are * merged into the context for all log calls inside `fn`. * * Without `fn` (the old setter shape): no-op for backwards compatibility. * Prefer `child()` for persistent bindings or `withContextAsync()` for * async callbacks. * * @param bindings - Key-value pairs to attach for the duration of `fn` * @param fn - Optional synchronous function to run with scoped bindings * @returns The return value of `fn`, or undefined if no fn provided * * @example * // Scoped synchronous callback * logger.withContext({ requestId: 'r-42' }, () => { * doWork(); // logs inside see requestId in attributes * }); * * @example * // Persistent binding: use child() * const reqLog = logger.child({ requestId: 'r-42' }); * reqLog.info('handling request'); // attributes include requestId * * @see {@link child} for an immutable copy with the merged context * @see {@link withContextAsync} for async callback variant */ withContext(bindings: Record, fn?: () => R): R | undefined; /** * Async variant of `withContext`. Runs `fn` within an AsyncLocalStorage * scope so bindings are available to all async log calls inside `fn`. * * @param bindings - Key-value pairs to attach for the duration of `fn` * @param fn - Async function to run with the scoped bindings * @returns The return value of `fn` * * @example * await logger.withContextAsync({ requestId: 'r-42' }, async () => { * await fetchData(); // logs inside see requestId in attributes * }); * * @see {@link child} for a persistent child logger * @see {@link withContext} for synchronous callback variant */ withContextAsync(bindings: Record, fn: () => Promise): Promise; /** * Returns an immutable copy of this logger with the extra context bound. * Future calls on the child emit with the merged context, without * mutating the parent — the canonical MDC pattern. * * @param extra - Key-value pairs to attach (requestId, userId, ...) * @returns A new Logger with merged context * * @example * const reqLog = logger.child({ requestId: req.id }); * reqLog.info('start'); // emits attributes: { requestId } * logger.info('unrelated'); // NOT affected — parent's context untouched * */ child(extra: Record): Logger; /** * Drops every key from the bound context. After this call, emitted * records no longer carry `attributes` until {@link withContext} or * {@link child} re-establish one. * * @returns The same logger instance, now context-free */ clearContext(): this; /** * Snapshot of the bound context. Returned object is a shallow copy: * mutating it does NOT affect what subsequent log calls emit. * * @returns A read-only snapshot of the current context */ getContext(): Readonly>; /** * Updates the default OTel resource (service.name, version, env). * Persisted into every emitted record's `resource` field unless the * record itself overrides it. * * @param resource - Partial OTel resource to merge into the current one * @returns The same logger instance, for chaining * * @example * logger.setResource({ 'service.name': 'api', 'service.version': '1.2.3' }); * */ setResource(resource: Partial): this; /** * Reinicia el logger a la configuración por defecto * * @example * logger.resetConfig(); * // Todo vuelve a la configuración inicial * */ resetConfig(): void; /** * Método de limpieza para eliminar listeners y liberar recursos * * @example * // Antes de cerrar la aplicación * logger.cleanup(); * */ /** * Tears down every resource held by this Logger. Safe to call multiple * times. Fixed in 5.1.0 to fully drain transports + clear timers + * drop the legacy handler list + reset group depth + clear context. * * @example * await logger.cleanup(); // before process exit / hot reload * */ cleanup(): Promise; /** * Aplica un preset inteligente - funciona perfectamente sin configuración * * @param {string} name - Nombre del preset a aplicar * * @example * // Presets disponibles * logger.preset('default'); // Limpio y adaptativo * logger.preset('cyberpunk'); // Colores neón, efectos brillantes * logger.preset('glassmorphism'); // Efectos de blur modernos * logger.preset('minimal'); // Minimalista y elegante * logger.preset('debug'); // Modo desarrollo detallado * logger.preset('production'); // Optimizado para producción * */ preset(name: string): void; /** * Lista todos los presets disponibles * * @returns {string[]} Array con nombres de presets disponibles * * @example * const disponibles = logger.presets(); * console.log(disponibles); // ['default', 'cyberpunk', 'glassmorphism', ...] * */ presets(): string[]; /** * Oculta el timestamp en los logs * * @example * logger.hideTimestamp(); * logger.info('Sin marca de tiempo'); // Sin timestamp visible * */ hideTimestamp(): this; /** * Muestra el timestamp en los logs * * @example * logger.showTimestamp(); * logger.info('Con marca de tiempo'); // [2024-01-15 10:30:45] Con marca de tiempo * */ showTimestamp(): this; /** * Oculta la información de ubicación (archivo:línea) en los logs * * @example * logger.hideLocation(); * logger.debug('Sin ubicación'); // Sin mostrar archivo:línea * */ hideLocation(): this; /** * Muestra la información de ubicación (archivo:línea) en los logs * * @example * logger.showLocation(); * logger.debug('Con ubicación'); // app.js:42 Con ubicación * */ showLocation(): this; /** * Oculta los badges en los logs * * @example * logger.hideBadges(); * const api = logger.api('REST'); * api.info('Sin badges'); // Sin mostrar [API] [REST] * */ hideBadges(): this; /** * Muestra los badges en los logs * * @example * logger.showBadges(); * const api = logger.api('GraphQL'); * api.info('Con badges'); // [API] [GraphQL] Con badges * */ showBadges(): this; /** * Establece múltiples badges para los logs * * @param {string[]} badges - Array de badges a mostrar * @returns {this} Logger instance para encadenamiento * * @example * logger.badges(['v3', 'stable']).info('Release publicado'); * logger.badges(['API', 'v2']).warn('Endpoint deprecado'); * */ badges(badges: string[]): this; /** * Añade un badge individual a la lista * * @param {string} badge - Badge a añadir * @returns {this} Logger instance para encadenamiento * * @example * logger.badge('DEBUG').badge('AUTH').info('Token validado'); * */ badge(badge: string): this; /** * Limpia todos los badges activos * * @returns {this} Logger instance para encadenamiento * * @example * logger.clearBadges().info('Sin badges'); * */ clearBadges(): this; component(name: string): ComponentLogger; api(name: string): APILogger; scope(name: string): ScopedLogger; /** * Personalización simple con configuración mínima * * @param {Object} overrides - Opciones de personalización * @param {Object} overrides.message - Configuración del mensaje * @param {Object} overrides.timestamp - Configuración del timestamp * @param {Object} overrides.location - Configuración de ubicación * @param {Object} overrides.level - Configuración del nivel * @param {Object} overrides.prefix - Configuración del prefijo * @param {string} overrides.spacing - Espaciado: 'compact' | 'normal' | 'spacious' * * @example * logger.customize({ * message: { color: '#00ff00', size: '16px' }, * timestamp: { show: false }, * spacing: 'compact' * }); * */ customize(overrides: { message?: { color?: string; font?: string; size?: string; }; timestamp?: { show?: boolean; color?: string; }; location?: { show?: boolean; color?: string; }; level?: { uppercase?: boolean; style?: string; }; prefix?: { show?: boolean; style?: string; }; spacing?: 'compact' | 'normal' | 'spacious'; }): void; /** * Añade un handler personalizado para extender funcionalidad * * @param {ILogHandler} handler - Handler que implementa ILogHandler * * @example * // Handler personalizado para enviar logs a servidor * logger.addHandler({ * handle(level, message, args, metadata) { * fetch('/logs', { method: 'POST', body: JSON.stringify({ level, message }) }); * } * }); * * @example * // Para escribir a archivo, usa `addTransport` con un `FileTransport` * logger.addTransport({ target: new FileTransport({ destination: 'app.log' }) }); * */ addHandler(handler: ILogHandler): void; /** * Obtiene todos los handlers registrados * * @returns {ILogHandler[]} Array de handlers activos */ getHandlers(): ILogHandler[]; /** * Añade un serializador personalizado para un tipo específico * * @param type - Constructor del tipo a serializar * @param serializer - Función de serialización * @param priority - Prioridad (mayor = primero) * * @example * logger.addSerializer(Error, (err) => ({ * name: err.name, * message: err.message, * stack: err.stack?.split('\n').slice(0, 5) * })); * */ addSerializer(type: new (...args: unknown[]) => T, serializer: SerializerFn, priority?: number): void; /** * Elimina un serializador registrado * * @param type - Constructor del tipo a remover * @returns true si se eliminó * */ removeSerializer(type: new (...args: unknown[]) => T): boolean; /** * Obtiene el registry de serializadores * * @returns SerializerRegistry */ getSerializerRegistry(): SerializerRegistry; /** * Registra un hook para un evento * * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError' * @param callback - Función a ejecutar * @param priority - Prioridad (mayor = primero) * @returns Función para desregistrar * * @example * const unsubscribe = logger.on('beforeLog', (entry) => { * entry.correlationId = getCorrelationId(); * return entry; * }); * */ on(event: HookEvent, callback: HookCallback, priority?: number): () => void; /** * Registra un hook que se ejecuta solo una vez * * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError' * @param callback - Función a ejecutar * @param priority - Prioridad (mayor = primero) * @returns Función para desregistrar * */ once(event: HookEvent, callback: HookCallback, priority?: number): () => void; /** * Elimina un hook registrado * * @param event - Evento del hook * @param callback - Callback a remover * @returns true si se eliminó * */ off(event: HookEvent, callback: HookCallback): boolean; /** * Añade un middleware al pipeline * * @param middleware - Función middleware * @param priority - Prioridad (mayor = primero) * @returns Función para desregistrar * * @example * logger.use((entry, next) => { * entry.requestId = asyncLocalStorage.getStore()?.requestId; * next(); * }); * */ use(middleware: MiddlewareFn, priority?: number): () => void; /** * Obtiene el HookManager * * @returns HookManager */ getHookManager(): HookManager; /** * Añade un transport para envío de logs * * @param target - Configuración del transport * @returns ID único del transport * * @example * // File transport * logger.addTransport({ * target: 'file', * options: { destination: '/var/log/app.log' } * }); * * @example * // HTTP transport con batching * logger.addTransport({ * target: 'http', * options: { * url: 'https://logs.example.com', * batchSize: 100, * flushInterval: 5000 * }, * level: 'warn' * }); * */ addTransport(target: TransportTarget): string; /** * Elimina un transport * * @param id - ID del transport a remover * @returns true si se eliminó * */ removeTransport(id: string): boolean; /** * Fuerza el flush de todos los transports * * @returns Promise que resuelve cuando todos los buffers están vaciados * */ flushTransports(): Promise; /** * Cierra todos los transports * * @returns Promise que resuelve cuando todos están cerrados * */ closeTransports(): Promise; /** * Obtiene el TransportManager * * @returns TransportManager o undefined si no hay transports */ getTransportManager(): TransportManager | undefined; /** * Verifica si un nivel de log debe mostrarse según la verbosidad actual. * @private * @param {LogLevel} level - Nivel de log a verificar * @returns {boolean} True si debe mostrarse, false si no */ private shouldLog; /** * Builds and dispatches a `TransportRecord` to the {@link TransportManager} * (no-op if no transports are registered). Shared by every log path — * `log()`, `success()`, and visual methods like `table()` / `group()` / * `time()` — so all emissions hit the same transport pipeline. * * @param level - The canonical log level (trace/debug/info/warn/error/critical) * @param message - Final, post-hook message text * @param prefix - Effective prefix (global + scope) * @param stackInfo - Optional caller location * @param extra - Optional fields to merge into the record (e.g. `{ tag: 'success' }`) */ protected _dispatchTag: string | undefined; /** * Computes the fully-merged context for this logger. * * The context chain is built at child-creation time: each child stores * its parent's fully-merged context (at that moment) as _parentContextRecord. * This means _parentContextRecord already contains all ancestors' bindings * in the correct precedence order (root first, nearest child last). * * Merge order (later wins): * 1. _parentContextRecord — parent's merged context snapshot at creation time * 2. _bindings — this logger's own bindings (child() calls) * 3. ALS store — withContext/withContextAsync scope (highest priority) * * @internal * @returns The merged context record */ private _getMergedContext; /** @internal Exposes base merged context (no ALS) to LogContext child factory closure. */ _captureMergedContext(): Record; protected dispatchToTransports(level: LogLevel, message: string, prefix: string | undefined, stackInfo: StackInfo | null, extra?: Partial): void; /** * Obtiene el prefijo efectivo (global + scope) * @private * @returns {string | undefined} Prefijo combinado o undefined */ private getEffectivePrefix; /** * Método central de logging. Awaits the `beforeLog` hook pipeline * synchronously (so redactions / enrichments are reflected in the * emitted message before console + transport dispatch). * * Fire-and-forget callers (e.g. `logger.info(...)` without `await`) * still work — the resulting `Promise` is dropped on the floor. * Awaiting is recommended when `beforeLog` hooks mutate `message` * (e.g. PII redaction, correlation IDs). * * @protected * @param level - Nivel del log * @param args - Argumentos a loggear * @returns Promise that resolves once the record has been dispatched * */ /** * Protected logging method. Awaits the `beforeLog` hook pipeline * synchronously (so redactions / enrichments are reflected in the * emitted message before console + transport dispatch). * * Fire-and-forget callers (e.g. `logger.info(...)` without `await`) * still work — the resulting `Promise` is dropped on the floor. * Awaiting is recommended when `beforeLog` hooks mutate `message` * (e.g. PII redaction, correlation IDs). * * @protected * @param level - Nivel del log * @param args - Argumentos a loggear * @param tag - Optional tag forwarded to `dispatchToTransports` as * `TransportRecord.tag` (e.g. `'success'` for success records). * @returns Promise that resolves once the record has been dispatched * */ protected log(level: LogLevel, ...args: unknown[]): Promise; logWithBindings(bindings: Bindings, level: LogLevel, ...args: unknown[]): Promise; /** * Like `logWithBindings()` but sets _dispatchTag first so that * `log()` dispatches with the tag. Used by ScopedLogger.success() * to propagate tag:'success' through the normal log() pipeline. */ logWithBindingsAndTag(bindings: Bindings, level: LogLevel, tag: LogTag, ...args: unknown[]): Promise; debug(...args: unknown[]): Promise; /** * Registra mensajes informativos. Devuelve `Promise` desde 5.1.0. * * @param args - Mensajes y datos informativos * * @example * logger.info('Servidor iniciado en puerto 3000'); * await logger.info('Procesando', totalItems, 'elementos'); // espera hooks * */ info(...args: unknown[]): Promise; /** * Registra mensajes de advertencia. Devuelve `Promise` desde 5.1.0. * * @param args - Mensajes de advertencia * */ warn(...args: unknown[]): Promise; /** * Registra mensajes de error. Devuelve `Promise` desde 5.1.0. * * @param args - Mensaje de error y stack traces * */ error(...args: unknown[]): Promise; /** * Registra mensajes de éxito. Mapeado internamente a nivel `info` con * styling de success y `record.tag = 'success'` para que los transports * puedan distinguirlo (sin perder info semantics para filtering). * * @param args - Mensaje + datos adicionales * * @example * logger.success('Base de datos conectada'); * logger.success('Usuario creado con ID:', userId); * logger.success('✓ Tests pasados: 42/42'); * */ success(...args: unknown[]): Promise; /** * Registra información de trace (nivel más bajo, debajo de debug). * Alineado con OpenTelemetry `TRACE` severity (1-4). * * @param args - Datos muy verbosos (entrada/salida de funciones, valores intermedios) * * @example * logger.trace('Entrando en función processData'); * logger.trace('Variables intermedias:', { a, b, c }); * */ trace(...args: unknown[]): void; /** * Registra errores críticos (prioridad más alta). Devuelve `Promise` desde 5.1.0. * * @param args - Errores críticos del sistema * * @example * await logger.critical('Sistema caído - reinicio inmediato requerido'); * */ critical(...args: unknown[]): Promise; /** * Muestra datos en formato de tabla. Pasa por la pipeline completa * (outputMode-respecting writeOutput + transports + hooks). * * @param data - Array de objetos o matriz * @param columns - Columnas específicas a mostrar (opcional) * * @example * logger.table([{ id: 1, nombre: 'Juan' }, { id: 2, nombre: 'María' }]); * */ table(data: unknown, columns?: string[]): void; /** * Inicia un grupo colapsable en la consola. Emite un marker a * transports con `attributes.logger.visual = 'groupStart'` para que * backends puedan reconstruir la jerarquía. * * @param label - Etiqueta del grupo * @param collapsed - Si el grupo inicia colapsado (default: false) * * @example * logger.group('Procesando usuarios'); * logger.info('Usuario 1 procesado'); * logger.groupEnd(); * */ group(label: string, collapsed?: boolean): void; /** * Finaliza el grupo actual de la consola. Emite un marker a transports * simétrico al `group()` start, para que backends puedan cerrar la * jerarquía correctamente. * * @example * logger.group('Operaciones'); * logger.info('Operación 1'); * logger.groupEnd(); * */ groupEnd(): void; /** * Inicia un temporizador con la etiqueta dada * * @param {string} label - Etiqueta identificadora del temporizador * * @example * logger.time('proceso-datos'); * // ... operación costosa ... * logger.timeEnd('proceso-datos'); // ⏱️ Timer ended: proceso-datos - 1523.45ms * */ time(label: string): void; /** * Finaliza un temporizador y muestra el tiempo transcurrido * * @param {string} label - Etiqueta del temporizador a finalizar * @returns {number} Elapsed milliseconds, or -1 if timer not found * * @example * logger.time('consulta-db'); * await consultarBaseDatos(); * const elapsed = logger.timeEnd('consulta-db'); // ⏱️ Timer ended: consulta-db - 234.56ms * */ timeEnd(label: string): number; /** * Muestra un banner con el tipo especificado o configurado * * @param {BannerType} bannerType - Tipo de banner (opcional) * * @example * logger.showBanner('ascii'); // Banner ASCII art * logger.showBanner('unicode'); // Banner con caracteres Unicode * logger.showBanner('svg'); // Banner con gráfico SVG * logger.showBanner(); // Usa el tipo configurado * */ showBanner(bannerType?: BannerType): void; /** * Registra mensaje con imagen SVG de fondo * * @param {string} message - Mensaje a mostrar * @param {string} svgContent - Contenido SVG personalizado (opcional) * @param {StyleOptions} options - Opciones de estilo (ancho, alto, padding) * * @example * // SVG automático con gradiente * logger.logWithSVG('🎆 Bienvenido a Better Logger'); * * @example * // SVG personalizado * const customSVG = '...'; * logger.logWithSVG('Logo', customSVG, { width: 400, height: 100 }); * */ logWithSVG(message: string, svgContent?: string, options?: StyleOptions): void; /** * Registra mensaje con gradiente animado de fondo * * @param {string} message - Mensaje a animar * @param {number} duration - Duración de la animación en segundos (default: 3) * * @example * logger.logAnimated('🌈 Animación en progreso'); * logger.logAnimated('Cargando...', 5); // Animación de 5 segundos * */ logAnimated(message: string, duration?: number): void; /** * Displays a step progress indicator in the terminal * * @param {number} current - Current step number * @param {number} total - Total number of steps * @param {string} message - Step description * * @example * logger.step(1, 5, 'Analyzing repository...'); * logger.step(2, 5, 'Generating commit message...'); * */ step(current: number, total: number, message: string): void; /** * Displays a styled header with optional subtitle * * @param {string} title - Main title text * @param {string} subtitle - Optional subtitle (rendered dimmed) * * @example * logger.header('Commit Wizard', 'v2.0.0'); * */ header(title: string, subtitle?: string): void; /** * Displays a horizontal divider line * * @example * logger.divider(); * */ divider(): void; /** * Outputs a blank line * * @example * logger.blank(); * */ blank(): void; /** * Renders content inside a bordered box * * @param {string} content - Content string (may contain newlines) * @param {IBoxOptions} options - Box rendering options * * @example * logger.box('3 commits generated\nProvider: Groq', { title: 'Done', borderColor: '#00ff00' }); * */ box(content: string, options?: IBoxOptions): void; /** * Renders an array of objects as a formatted ASCII table. * Note: This is distinct from the existing table() method which uses console.table. * * @param {Record[]} rows - Array of row objects * @param {ITableOptions} options - Table rendering options * * @example * logger.cliTable([ * { provider: 'Groq', status: 'Available', model: 'llama-3.3-70b' }, * { provider: 'Gemini', status: 'Configured', model: 'gemini-2.5-flash' }, * ]); * */ cliTable(rows: Record[], options?: ITableOptions): void; /** * Creates a spinner handle for showing progress during async operations. * Returns a NoopSpinner in non-TTY environments. * * @param {string} message - Initial spinner text * @returns {ISpinnerHandle} Spinner controller * * @example * const s = logger.spinner('Analyzing repository...'); * s.start(); * await analyzeRepo(); * s.succeed('Analysis complete (1.2s)'); * */ spinner(message: string): ISpinnerHandle; /** * Sets the CLI verbosity level, controlling both log verbosity and primitive visibility * * @param {CLILogLevel} level - CLI log level * * @example * logger.setCLILevel('quiet'); // Only errors, no CLI primitives * logger.setCLILevel('verbose'); // Debug logs + all CLI primitives * */ setCLILevel(level: CLILogLevel): void; /** * Returns the current CLI log level * @returns {CLILogLevel} Current CLI log level */ get cliLevel(): CLILogLevel; /** * Writes formatted output to the configured destination. * Respects outputMode configuration for console, silent, or custom output. * * @private * @param {string} message - Formatted log message * @param {LogLevel} level - Log level * @param {string[]} styles - CSS styles for browser console * @param {unknown[]} additionalArgs - Additional arguments to log */ private writeOutput; /** * Procesador de comandos CLI para configuración y exportación del logger * * @param {string} command - Comando CLI a ejecutar * @returns {Promise} * * @example * // Comandos disponibles * await logger.cli('export json'); // Exporta logs en JSON * await logger.cli('export csv'); // Exporta logs en CSV * await logger.cli('theme list'); // Lista temas disponibles * await logger.cli('theme set neon'); // Cambia al tema neon * await logger.cli('config show'); // Muestra configuración actual * await logger.cli('history clear'); // Limpia historial de logs * await logger.cli('status'); // Muestra estado del logger * await logger.cli('help'); // Muestra ayuda de comandos * */ cli(command: string): Promise; } /** * Resets the default singleton. Clears the cached instance so the next call * to `getDefaultLogger()` rebuilds it from defaults. Useful for tests and * hot reload scenarios. * */ export declare function resetDefaultLogger(): void; /** * Lazy default export — every property access defers to `getDefaultLogger()`. * Side-effect-free at module import (BUG-N11). * * @example * import logger from 'better-logger'; * logger.info('hello'); // first call here triggers singleton init */ declare const loggerProxy: Logger; export default loggerProxy; /** * Métodos individuales exportados para conveniencia * @description Todos los métodos están correctamente enlazados al singleton lazy */ export declare const debug: (...args: unknown[]) => Promise; export declare const info: (...args: unknown[]) => Promise; export declare const warn: (...args: unknown[]) => Promise; export declare const error: (...args: unknown[]) => Promise; export declare const success: (...args: unknown[]) => Promise; export declare const trace: (...args: unknown[]) => void; export declare const critical: (...args: unknown[]) => Promise; export declare const table: (data: unknown, columns?: string[]) => void; export declare const group: (label: string, collapsed?: boolean) => void; export declare const groupEnd: () => void; export declare const time: (label: string) => void; export declare const timeEnd: (label: string) => number; export declare const setGlobalPrefix: (prefix: string) => void; export declare const setVerbosity: (level: Verbosity) => void; export declare const addHandler: (handler: ILogHandler) => void; export declare const setTheme: (theme: ThemeVariant) => void; export declare const setBannerType: (bannerType: BannerType) => void; export declare const showBanner: (bannerType?: BannerType) => void; export declare const logWithSVG: (message: string, svgContent?: string, options?: StyleOptions) => void; export declare const logAnimated: (message: string, duration?: number) => void; export declare const cli: (command: string) => Promise; export declare const cleanup: () => Promise; export declare const preset: (name: string) => void; export declare const presets: () => string[]; export declare const hideTimestamp: () => Logger; export declare const showTimestamp: () => Logger; export declare const hideLocation: () => Logger; export declare const showLocation: () => Logger; export declare const hideBadges: () => Logger; export declare const showBadges: () => Logger; export declare const badges: (badgeList: string[]) => Logger; export declare const badge: (badgeName: string) => Logger; export declare const clearBadges: () => Logger; export declare const component: (name: string) => ComponentLogger; export declare const api: (name: string) => APILogger; export declare const scope: (name: string) => ScopedLogger; export declare const customize: (overrides: Parameters[0]) => void; export declare const addSerializer: (type: new (...args: unknown[]) => T, serializer: SerializerFn, priority?: number) => void; export declare const removeSerializer: (type: new (...args: unknown[]) => T) => boolean; export declare const on: (event: HookEvent, callback: HookCallback, priority?: number) => () => void; export declare const once: (event: HookEvent, callback: HookCallback, priority?: number) => () => void; export declare const off: (event: HookEvent, callback: HookCallback) => boolean; export declare const use: (middleware: MiddlewareFn, priority?: number) => () => void; export declare const addTransport: (target: TransportTarget) => string; export declare const removeTransport: (id: string) => boolean; export declare const flushTransports: () => Promise; export declare const closeTransports: () => Promise; export { StyleBuilder, StylePresets as Styles } from './styling/index.js'; export { SerializerRegistry } from './serializers/index.js'; export { HookManager } from './hooks/index.js'; export { TransportManager, ConsoleTransport, FileTransport, HttpTransport } from './transports/index.js'; //# sourceMappingURL=Logger.d.ts.map