All files / src/adapters/vite logger.ts

82.79% Statements 77/93
64.58% Branches 62/96
88.46% Functions 23/26
85.55% Lines 77/90

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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280                              2x             22x         5x 5x 2x 3x                     2x   2x     2x 2x 2x 2x 2x 2x                   18x 18x 18x 18x                                                           22x 22x 22x 22x   22x 1x 1x         22x               1x 1x                                 2x 1x 1x   1x     1x 1x   2x 2x 2x       1x               2x 1x 1x   1x     1x 1x   2x 2x       1x               2x 1x               1x 1x               1x 1x               1x 1x               3x 1x 1x               3x 2x 2x 2x 2x                 1x       2x 1x         2x 1x         2x 1x 1x 1x         2x 1x 1x 1x         1x                  
/**
 * Logger adapter for Vite
 * Translates core events into Vite logs
 */
 
import type { Logger } from 'vite';
 
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
 
export interface LoggingOptions {
  level?: LogLevel;
  enableRequestLogging?: boolean;
  enableRouteLogging?: boolean;
}
 
const RESET = '\x1b[0m';
 
/**
 * Formats the [vitek] tag with green color and bold
 * Uses ANSI codes: \x1b[1m = bold, \x1b[32m = green, \x1b[0m = reset
 */
function formatTag(text: string): string {
  return `\x1b[1m\x1b[32m${text}${RESET}`;
}
 
/** ANSI color for HTTP method in Registered routes (method only) */
function methodColor(method: string): string {
  const m = method.toUpperCase();
  switch (m) {
    case 'GET': return '\x1b[32m';    // green
    case 'POST': return '\x1b[33m';    // yellow
    case 'PUT': return '\x1b[34m';     // blue
    case 'PATCH': return '\x1b[36m';   // cyan
    case 'DELETE': return '\x1b[31m';  // red
    case 'HEAD':
    case 'OPTIONS': return '\x1b[90m'; // gray
    default: return '\x1b[0m';
  }
}
 
/** ANSI color for "WS" in Registered sockets */
const WS_COLOR = '\x1b[95m'; // bright magenta (pink)
 
const PAYLOAD_PREVIEW_MAX = 80;
 
function payloadPreview(data: unknown): string {
  Iif (data === undefined || data === null) return '';
  Iif (typeof data === 'string') return data.length <= PAYLOAD_PREVIEW_MAX ? data : data.slice(0, PAYLOAD_PREVIEW_MAX) + '…';
  Iif (Buffer.isBuffer(data)) return `<Buffer ${data.length} bytes>`;
  try {
    const s = JSON.stringify(data);
    return s.length <= PAYLOAD_PREVIEW_MAX ? s : s.slice(0, PAYLOAD_PREVIEW_MAX) + '…';
  } catch {
    return String(data).slice(0, PAYLOAD_PREVIEW_MAX);
  }
}
 
/**
 * Checks if a log level should be logged based on the configured level
 */
function shouldLog(level: LogLevel, configuredLevel: LogLevel): boolean {
  const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];
  const levelIndex = levels.indexOf(level);
  const configuredIndex = levels.indexOf(configuredLevel);
  return levelIndex >= configuredIndex;
}
 
export interface VitekLogger {
  debug(message: string, data?: Record<string, any>): void;
  info(message: string, data?: Record<string, any>): void;
  warn(message: string, data?: Record<string, any>): void;
  error(message: string, data?: Record<string, any>): void;
  routesRegistered(routes: Array<{ method: string; pattern: string }>, apiBasePath: string): void;
  socketsRegistered(sockets: Array<{ pattern: string }>, socketBasePath: string): void;
  routeMatched(pattern: string, method: string): void;
  middlewareLoaded(count: number): void;
  typesGenerated(outputPath: string): void;
  servicesGenerated(outputPath: string): void;
  /** Log when a request is received (endpoint called). Only when enableRequestLogging. */
  requestStart(method: string, path: string): void;
  request(method: string, path: string, statusCode: number, duration?: number): void;
  response(method: string, path: string, statusCode: number, duration?: number): void;
  /** Socket events (only logged when enableRequestLogging is true) */
  socketConnected(path: string, pattern?: string): void;
  socketDisconnected(path: string, pattern?: string): void;
  socketMessageReceived(path: string, pattern?: string, data?: unknown): void;
  socketMessageEmitted(path: string, data?: unknown): void;
  getOptions(): LoggingOptions;
}
 
/**
 * Creates a logger that uses Vite's logger
 */
export function createViteLogger(viteLogger: Logger, options?: LoggingOptions): VitekLogger {
  const tag = formatTag('[vitek]');
  const logLevel: LogLevel = options?.level || 'info';
  const enableRequestLogging = options?.enableRequestLogging || false;
  const enableRouteLogging = options?.enableRouteLogging !== false; // Default true
  
  const formatData = (data?: Record<string, any>): string => {
    Eif (!data || Object.keys(data).length === 0) {
      return '';
    }
    return ' ' + JSON.stringify(data);
  };
  
  return {
    debug(message: string, data?: Record<string, any>) {
      if (shouldLog('debug', logLevel)) {
        viteLogger.info(`${tag} [DEBUG] ${message}${formatData(data)}`, { timestamp: true });
      }
    },
    
    info(message: string, data?: Record<string, any>) {
      Eif (shouldLog('info', logLevel)) {
        viteLogger.info(`${tag} ${message}${formatData(data)}`, { timestamp: true });
      }
    },
    
    warn(message: string, data?: Record<string, any>) {
      if (shouldLog('warn', logLevel)) {
        viteLogger.warn(`${tag} ${message}${formatData(data)}`, { timestamp: true });
      }
    },
    
    error(message: string, data?: Record<string, any>) {
      if (shouldLog('error', logLevel)) {
        viteLogger.error(`${tag} ${message}${formatData(data)}`, { timestamp: true });
      }
    },
    
    routesRegistered(routes: Array<{ method: string; pattern: string }>, apiBasePath: string) {
      if (routes.length === 0) {
        Eif (shouldLog('info', logLevel)) {
          viteLogger.info(`${tag} No routes registered`, { timestamp: true });
        }
        return;
      }
      
      Eif (shouldLog('info', logLevel)) {
        const routesList = routes
          .map(r => {
            const pattern = r.pattern === '' ? '/' : `/${r.pattern}`;
            const method = r.method.toUpperCase();
            return `  ${methodColor(r.method)}${method}${RESET} ${apiBasePath}${pattern}`;
          })
          .join('\n');
        
        viteLogger.info(
          `${tag} Registered routes:\n${routesList}`,
          { timestamp: true }
        );
      }
    },
 
    socketsRegistered(sockets: Array<{ pattern: string }>, socketBasePath: string) {
      if (sockets.length === 0) {
        Eif (shouldLog('info', logLevel)) {
          viteLogger.info(`${tag} No sockets registered`, { timestamp: true });
        }
        return;
      }
 
      Eif (shouldLog('info', logLevel)) {
        const socketsList = sockets
          .map(s => {
            const pathSegment = s.pattern === '' ? '' : `/${s.pattern}`;
            return `  ${WS_COLOR}WS${RESET} ${socketBasePath}${pathSegment}`;
          })
          .join('\n');
 
        viteLogger.info(
          `${tag} Registered sockets:\n${socketsList}`,
          { timestamp: true }
        );
      }
    },
    
    routeMatched(pattern: string, method: string) {
      if (enableRouteLogging && shouldLog('debug', logLevel)) {
        viteLogger.info(
          `${tag} [ROUTE] ${method.toUpperCase()} ${pattern}`,
          { timestamp: true }
        );
      }
    },
    
    middlewareLoaded(count: number) {
      Eif (shouldLog('info', logLevel)) {
        viteLogger.info(
          `${tag} Loaded ${count} global middleware(s)`,
          { timestamp: true }
        );
      }
    },
    
    typesGenerated(outputPath: string) {
      Eif (shouldLog('info', logLevel)) {
        viteLogger.info(
          `${tag} Generated types: ${outputPath}`,
          { timestamp: true }
        );
      }
    },
    
    servicesGenerated(outputPath: string) {
      Eif (shouldLog('info', logLevel)) {
        viteLogger.info(
          `${tag} Generated services: ${outputPath}`,
          { timestamp: true }
        );
      }
    },
    
    requestStart(method: string, path: string) {
      if (enableRequestLogging && shouldLog('info', logLevel)) {
        const m = method.toUpperCase();
        viteLogger.info(
          `${tag} ${methodColor(method)}[${m}]${RESET} ${path} →`,
          { timestamp: true }
        );
      }
    },
 
    request(method: string, path: string, statusCode: number, duration?: number) {
      if (enableRequestLogging && shouldLog('info', logLevel)) {
        const durationStr = duration !== undefined ? ` (${duration}ms)` : '';
        const statusColor = statusCode >= 500 ? '\x1b[31m' : statusCode >= 400 ? '\x1b[33m' : '\x1b[32m';
        const m = method.toUpperCase();
        viteLogger.info(
          `${tag} ${methodColor(method)}[${m}]${RESET} ${path} ${statusColor}${statusCode}${RESET}${durationStr}`,
          { timestamp: true }
        );
      }
    },
    
    response(method: string, path: string, statusCode: number, duration?: number) {
      // Alias for request (for consistency)
      this.request(method, path, statusCode, duration);
    },
 
    socketConnected(path: string, pattern?: string) {
      if (enableRequestLogging && shouldLog('info', logLevel)) {
        viteLogger.info(`${tag} ${WS_COLOR}[WS]${RESET} connected ${path}`, { timestamp: true });
      }
    },
 
    socketDisconnected(path: string, pattern?: string) {
      if (enableRequestLogging && shouldLog('info', logLevel)) {
        viteLogger.info(`${tag} ${WS_COLOR}[WS]${RESET} disconnected ${path}`, { timestamp: true });
      }
    },
 
    socketMessageReceived(path: string, pattern?: string, data?: unknown) {
      if (enableRequestLogging && shouldLog('info', logLevel)) {
        const preview = payloadPreview(data);
        const suffix = preview ? ` ${preview}` : '';
        viteLogger.info(`${tag} ${WS_COLOR}[WS]${RESET} received ${path}${suffix}`, { timestamp: true });
      }
    },
 
    socketMessageEmitted(path: string, data?: unknown) {
      if (enableRequestLogging && shouldLog('info', logLevel)) {
        const preview = payloadPreview(data);
        const suffix = preview ? ` ${preview}` : '';
        viteLogger.info(`${tag} ${WS_COLOR}[WS]${RESET} emitted ${path}${suffix}`, { timestamp: true });
      }
    },
 
    getOptions(): LoggingOptions {
      return {
        level: logLevel,
        enableRequestLogging,
        enableRouteLogging,
      };
    },
  };
}