All files / core/src/utils debug.ts

100% Statements 66/66
100% Branches 32/32
100% Functions 11/11
100% Lines 66/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 1611x       1x                   1x 61x 3x 3x   58x   58x 58x   58x 30x 29x 29x 29x 30x 58x             1x 1x 1x                     1x 4x   4x   4x 4x 4x 1x 1x   4x 4x 4x                                                                                                     1x 45x 60x 60x 20x 40x 60x   60x 8x 8x 53x 60x   45x 20x 20x   45x 10x 10x   45x 8x 8x   45x 8x 6x 6x   2x 8x   45x 7x 7x   45x 7x 7x   45x 45x   1x  
import { isFunction, isString } from '@beerush/utils';
 
export type DebugFn = (...args: unknown[]) => void;
 
let currentLogger: DebugFn | undefined = undefined;
 
/**
 * Sets the current debugger function and returns a restore function.
 * The restore function can be called to revert to the previous debugger.
 *
 * @param debugFn - The debugger function to set, or undefined to disable debugging
 * @returns A function that restores the previous debugger when called
 * @throws {Error} If debugFn is neither a function nor undefined
 */
export function setDebugger(debugFn: DebugFn | undefined) {
  if (typeof debugFn !== 'function' && debugFn !== undefined) {
    throw new Error('Debug function must be a function or undefined');
  }
 
  let restored = false;
 
  const prevLogger = currentLogger;
  currentLogger = debugFn;
 
  return () => {
    if (!restored) {
      currentLogger = prevLogger;
      restored = true;
    }
  };
}
 
/**
 * Gets the current debugger function.
 *
 * @returns The current debugger function, or undefined if debugging is disabled
 */
export function getDebugger(): DebugFn | undefined {
  return currentLogger;
}
 
/**
 * Executes a function with a specified debugger, temporarily replacing the current debugger.
 * The original debugger is restored after the function execution, even if an error occurs.
 *
 * @template R - The return type of the function
 * @param fn - The function to execute with the custom debugger
 * @param debugFn - The debugger function to use during execution
 * @returns The result of the executed function
 */
export function withDebugger<R>(fn: () => R, debugFn: DebugFn): R {
  const restoreDebugger = setDebugger(debugFn);
 
  let result: R | undefined = undefined;
 
  try {
    result = fn();
  } catch (error) {
    currentLogger?.(error);
  }
 
  restoreDebugger();
  return result as R;
}
 
/**
 * Debugger interface that extends a function with additional logging methods.
 * Each method logs a message with a specific prefix and color coding.
 */
export interface Debugger {
  /**
   * Generic debug function that can accept any number of arguments.
   * @param args - Arguments to be passed to the debug function
   */
  (...args: unknown[]): void;
 
  /**
   * Logs a success message with a green checkmark prefix.
   * @param message - The message to log
   * @param extras - Additional arguments to log
   */
  ok(message: string, ...extras: unknown[]): void;
 
  /**
   * Logs an informational message with a blue info symbol prefix.
   * @param message - The message to log
   * @param extras - Additional arguments to log
   */
  info(message: string, ...extras: unknown[]): void;
 
  /**
   * Logs a conditional message with a cyan filled square (▣) if condition is true,
   * or a gray empty square (▢) if condition is false.
   * @param message - The message to log
   * @param condition - The condition to evaluate
   * @param extras - Additional arguments to log
   */
  check(message: string, condition: boolean, ...extras: unknown[]): void;
 
  /**
   * Logs an error message with a red cross prefix.
   * @param message - The message to log
   * @param extras - Additional arguments to log
   */
  error(message: string, ...extras: unknown[]): void;
 
  /**
   * Logs a warning message with a yellow exclamation mark prefix.
   * @param message - The message to log
   * @param extras - Additional arguments to log
   */
  warning(message: string, ...extras: unknown[]): void;
}
 
export function createDebugger(prefix?: string, logger?: DebugFn): Debugger {
  const log = (scope: keyof Debugger | 'default', ...args: unknown[]) => {
    const logFn =
      scope === 'default'
        ? (logger ?? currentLogger)
        : ((logger as Debugger)?.[scope] ?? logger ?? (currentLogger as Debugger)?.[scope] ?? currentLogger);
    if (!isFunction(logFn)) return;
 
    if (prefix && isString(args[0])) {
      logFn(`\x1b[1m${prefix}\x1b[0m ${args[0]}`, ...args.slice(1));
    }
    (logFn as DebugFn)(...args);
  };
 
  const debugFn = ((...args: unknown[]) => {
    return log('default', ...args);
  }) as Debugger;
 
  debugFn.ok = (message: string, ...extras: unknown[]) => {
    return log('ok', `\x1b[32m✓ ${message}\x1b[0m`, ...extras);
  };
 
  debugFn.info = (message: string, ...extras: unknown[]) => {
    return log('info', `\x1b[34mℹ ${message}\x1b[0m`, ...extras);
  };
 
  debugFn.check = (message: string, condition: boolean, ...extras: unknown[]) => {
    if (condition) {
      return log('check', `\x1b[36m▣ ${message}\x1b[0m`, ...extras);
    }
 
    return log('check', `\x1b[37m▢ ${message}\x1b[0m`, ...extras);
  };
 
  debugFn.error = (message: string, ...extras: unknown[]) => {
    return log('error', `\x1b[31m✕ ${message}\x1b[0m`, ...extras);
  };
 
  debugFn.warning = (message: string, ...extras: unknown[]) => {
    return log('warning', `\x1b[33m! ${message}\x1b[0m`, ...extras);
  };
 
  return debugFn;
}
 
export const debug = createDebugger() as Debugger;