import { v4 as uuidv4 } from 'uuid'; import * as fs from 'fs'; import * as path from 'path'; import { isError, isErrorWithCode, isHttpBody, isRecord, type TavusLogEntry, type TavusLoggerConfig, type HttpBody, type LogEntryMetadata, type PendingRequest, type ProxyRequest, type ProxyResponse, type ErrorInfo, type SessionSummary } from '@buzztrail/shared-types'; class TavusLogger { private config: TavusLoggerConfig; private currentSessionId: string; private sessionStartTime: number; private logBuffer: TavusLogEntry[] = []; private flushInterval: NodeJS.Timeout | null = null; constructor(config: Partial = {}) { this.config = { enabled: true, logDirectory: path.join(process.cwd(), 'documentation', 'data', 'tavus-logs'), includeHeaders: true, includeBody: true, maxBodySize: 1024 * 1024, // 1MB sessionTimeout: 30, // 30 minutes // Enhanced logging defaults logProxyRequests: true, logClientInfo: true, logPerformance: true, logErrors: true, ...config }; this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); this.ensureLogDirectory(); this.startFlushInterval(); } private ensureLogDirectory(): void { const logDir = this.config.logDirectory; if (!logDir) { console.error('[TavusLogger] logDirectory not configured'); return; } const dirs = [ logDir, path.join(logDir, 'requests'), path.join(logDir, 'sessions'), path.join(logDir, 'schemas'), path.join(logDir, 'errors'), path.join(logDir, 'responses') ]; dirs.forEach(dir => { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } }); } private startFlushInterval(): void { if (this.flushInterval) { clearInterval(this.flushInterval); } this.flushInterval = setInterval(() => { this.flushBuffer(); }, 5000); // Flush every 5 seconds } private shouldStartNewSession(): boolean { const sessionAge = Date.now() - this.sessionStartTime; return sessionAge > this.config.sessionTimeout * 60 * 1000; } private getEndpointType(url: string): NonNullable { if (url.includes('/conversations')) return 'conversation'; if (url.includes('/videos')) return 'video'; if (url.includes('/auth')) return 'auth'; if (url.includes('/stream') || url.includes('/events')) return 'streaming'; return 'other'; } private sanitizeHeaders(headers: Record): Record { if (!this.config.includeHeaders) return {}; // Log everything for complete API reverse engineering // User will rotate keys after logging return { ...headers }; } private sanitizeBody(body: T): T | undefined { if (!this.config.includeBody || !body) return undefined; // Log everything for complete API reverse engineering // No truncation - capture full request/response data return body; } private isBinaryData(data: unknown): boolean { if (typeof data === 'string') { // Check if it's base64 encoded binary data return /^[A-Za-z0-9+/]*={0,2}$/.test(data) && data.length > 100; } return false; } logRequest( method: string, url: string, headers: Record, body?: HttpBody ): string { if (!this.config.enabled) return ''; if (this.shouldStartNewSession()) { this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); } const requestId = uuidv4(); const startTime = Date.now(); // Store request info for later response logging this.pendingRequests.set(requestId, { method, url, headers: this.sanitizeHeaders(headers), body: this.sanitizeBody(body), startTime, sessionId: this.currentSessionId }); return requestId; } logResponse( requestId: string, status: number, headers: Record, body?: HttpBody ): void { if (!this.config.enabled) return; const requestInfo = this.pendingRequests.get(requestId); if (!requestInfo) { console.warn(`TavusLogger: No pending request found for ID ${requestId}`); return; } this.pendingRequests.delete(requestId); const duration = Date.now() - requestInfo.startTime; const sanitizedBody = this.sanitizeBody(body); const hasBinaryData = this.isBinaryData(sanitizedBody); const binaryDataSize = hasBinaryData && typeof sanitizedBody === 'string' ? sanitizedBody.length : undefined; const logEntry: TavusLogEntry = { sessionId: requestInfo.sessionId, timestamp: new Date().toISOString(), request: { method: requestInfo.method, url: requestInfo.url, headers: requestInfo.headers, body: requestInfo.body }, response: { status, headers: this.sanitizeHeaders(headers), body: sanitizedBody, duration }, metadata: { endpoint: new URL(requestInfo.url).pathname, requestType: this.getEndpointType(requestInfo.url), hasBinaryData, binaryDataSize } }; this.logBuffer.push(logEntry); // Log errors separately if (status >= 400) { this.logErrorEntry(logEntry); } // Flush immediately for errors or large responses if (status >= 400 || hasBinaryData) { this.flushBuffer(); } } private logErrorEntry(logEntry: TavusLogEntry): void { const logDir = this.config.logDirectory; if (!logDir) return; const errorFile = path.join( logDir, 'errors', `${logEntry.metadata?.requestType}-${logEntry.response.status}-${Date.now()}.json` ); try { fs.writeFileSync(errorFile, JSON.stringify(logEntry, null, 2)); } catch (error) { console.error('TavusLogger: Failed to write error log:', error); } } private flushBuffer(): void { if (this.logBuffer.length === 0) return; const logDir = this.config.logDirectory; if (!logDir) return; const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const requestFile = path.join( logDir, 'requests', `requests-${timestamp}.json` ); try { fs.writeFileSync(requestFile, JSON.stringify(this.logBuffer, null, 2)); this.logBuffer = []; } catch (error) { console.error('TavusLogger: Failed to write request log:', error); } } logStreamingEvent( method: string, url: string, eventType: string, data: unknown ): void { if (!this.config.enabled) return; const logEntry: TavusLogEntry = { sessionId: this.currentSessionId, timestamp: new Date().toISOString(), request: { method, url, headers: {}, body: { eventType, data } }, response: { status: 200, headers: { 'content-type': 'text/event-stream' }, body: { eventType, data }, duration: 0 }, metadata: { endpoint: new URL(url).pathname, requestType: 'streaming', hasBinaryData: false } }; this.logBuffer.push(logEntry); } getSessionSummary(): SessionSummary { const requests = this.logBuffer.filter(entry => entry.sessionId === this.currentSessionId); const errors = requests.filter(entry => entry.response.status >= 400); const endpoints = [...new Set(requests.map(entry => entry.metadata?.endpoint || ''))]; return { sessionId: this.currentSessionId, requestCount: requests.length, errorCount: errors.length, totalDuration: requests.reduce((sum, entry) => sum + entry.response.duration, 0), endpoints }; } exportSession(sessionId?: string): void { const targetSessionId = sessionId || this.currentSessionId; const sessionRequests = this.logBuffer.filter(entry => entry.sessionId === targetSessionId); if (sessionRequests.length === 0) { console.warn(`TavusLogger: No requests found for session ${targetSessionId}`); return; } const logDir = this.config.logDirectory; if (!logDir) return; const sessionFile = path.join( logDir, 'sessions', `session-${targetSessionId}-${Date.now()}.json` ); try { fs.writeFileSync(sessionFile, JSON.stringify(sessionRequests, null, 2)); console.log(`TavusLogger: Exported session ${targetSessionId} with ${sessionRequests.length} requests`); } catch (error) { console.error('TavusLogger: Failed to export session:', error); } } destroy(): void { if (this.flushInterval) { clearInterval(this.flushInterval); } this.flushBuffer(); } private pendingRequests = new Map(); // Proxy server logging methods logProxyRequest(req: unknown, endpoint: string): string { // Don't log in production or on Vercel if (!this.config.logProxyRequests || isProduction || isVercel) return ''; // Type guard: ensure req is an object with expected properties if (!isRecord(req)) { console.error('[TavusLogger] Invalid request object for logging'); return ''; } const requestId = uuidv4(); const timestamp = new Date().toISOString(); // Safe access with type guards const getHeader = (name: string): string | undefined => { if (typeof req.get === 'function') { const value = req.get(name); return typeof value === 'string' ? value : undefined; } return undefined; }; const userAgent = getHeader('User-Agent'); const contentLength = getHeader('Content-Length'); const requestData: ProxyRequest = { requestId, timestamp, endpoint, method: typeof req.method === 'string' ? req.method : 'UNKNOWN', url: typeof req.url === 'string' ? req.url : '', originalUrl: typeof req.originalUrl === 'string' ? req.originalUrl : undefined, path: typeof req.path === 'string' ? req.path : undefined, query: isRecord(req.query) ? req.query : undefined, params: isRecord(req.params) ? req.params : undefined, headers: isRecord(req.headers) ? req.headers as Record : {}, body: isHttpBody(req.body) ? req.body : undefined, rawBody: req.rawBody, ip: typeof req.ip === 'string' ? req.ip : undefined, ips: Array.isArray(req.ips) ? req.ips as string[] : undefined, hostname: typeof req.hostname === 'string' ? req.hostname : undefined, protocol: typeof req.protocol === 'string' ? req.protocol : undefined, secure: typeof req.secure === 'boolean' ? req.secure : undefined, userAgent, referer: getHeader('Referer'), origin: getHeader('Origin'), contentType: getHeader('Content-Type'), contentLength, accept: getHeader('Accept'), acceptEncoding: getHeader('Accept-Encoding'), acceptLanguage: getHeader('Accept-Language'), connection: getHeader('Connection'), cacheControl: getHeader('Cache-Control'), pragma: getHeader('Pragma'), metadata: { isLocalhost: req.hostname === 'localhost' || req.hostname === '127.0.0.1', isCurl: userAgent?.includes('curl') || false, isPostman: userAgent?.includes('Postman') || false, isInsomnia: userAgent?.includes('Insomnia') || false, hasOrigin: !!getHeader('Origin'), hasReferer: !!getHeader('Referer'), requestSize: contentLength ? parseInt(contentLength, 10) : 0, timestamp: Date.now() } }; // Store start time for duration calculation this.pendingRequests.set(requestId, { method: requestData.method, url: requestData.url, headers: requestData.headers, body: requestData.body, startTime: Date.now(), sessionId: this.currentSessionId }); // Write to file const logDir = this.config.logDirectory; if (logDir) { const filename = `proxy-request-${timestamp.replace(/[:.]/g, '-')}-${requestId}.json`; const filepath = path.join(logDir, 'requests', filename); try { fs.writeFileSync(filepath, JSON.stringify(requestData, null, 2)); console.log(`[TavusLogger] Logged proxy request: ${requestId} -> ${endpoint}`); } catch (error) { console.error('[TavusLogger] Failed to log proxy request:', error); } } return requestId; } logProxyResponse(requestId: string, res: unknown, responseData: HttpBody, error: unknown = null): void { // Don't log in production or on Vercel if (!this.config.logProxyRequests || isProduction || isVercel) return; const pendingRequest = this.pendingRequests.get(requestId); const duration = pendingRequest ? Date.now() - pendingRequest.startTime : 0; const timestamp = new Date().toISOString(); // Type guards for res object if (!isRecord(res)) { console.error('[TavusLogger] Invalid response object for logging'); return; } const statusCode = typeof res.statusCode === 'number' ? res.statusCode : 0; const statusMessage = typeof res.statusMessage === 'string' ? res.statusMessage : ''; const headers = typeof res.getHeaders === 'function' ? res.getHeaders() as Record : {}; const errorInfo: ErrorInfo | undefined = error ? { message: isError(error) ? error.message : String(error), stack: isError(error) ? error.stack : undefined, name: isError(error) ? error.name : 'UnknownError', code: isErrorWithCode(error) ? error.code : undefined } : undefined; const responseLog: ProxyResponse = { requestId, timestamp, statusCode, statusMessage, headers, body: responseData, error: errorInfo, duration, metadata: { isError: !!error, isSuccess: !error && statusCode < 400, responseSize: responseData ? JSON.stringify(responseData).length : 0, timestamp: Date.now() } }; // Write to file const logDir = this.config.logDirectory; if (logDir) { const filename = `proxy-response-${timestamp.replace(/[:.]/g, '-')}-${requestId}.json`; const filepath = path.join(logDir, 'responses', filename); try { fs.writeFileSync(filepath, JSON.stringify(responseLog, null, 2)); console.log(`[TavusLogger] Logged proxy response: ${requestId} -> ${statusCode} (${duration}ms)`); } catch (error) { console.error('[TavusLogger] Failed to log proxy response:', error); } } // Clean up this.pendingRequests.delete(requestId); } logError(requestId: string, error: unknown, context: Record = {}): void { // Don't log in production or on Vercel if (!this.config.logErrors || isProduction || isVercel) return; const timestamp = new Date().toISOString(); const errorLog = { requestId, timestamp, error: { message: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, name: error instanceof Error ? error.name : 'UnknownError', code: error instanceof Error && 'code' in error ? (error as Error & { code?: string }).code : undefined }, context, metadata: { timestamp: Date.now() } }; // Write to file const logDir = this.config.logDirectory; if (logDir) { const filename = `error-${timestamp.replace(/[:.]/g, '-')}-${requestId || 'unknown'}.json`; const filepath = path.join(logDir, 'errors', filename); try { fs.writeFileSync(filepath, JSON.stringify(errorLog, null, 2)); console.error(`[TavusLogger] Logged error: ${requestId || 'unknown'} -> ${error instanceof Error ? error.message : String(error)}`); } catch (writeError) { console.error('[TavusLogger] Failed to log error:', writeError); } } } } // Singleton instance let loggerInstance: TavusLogger | null = null; export function getTavusLogger(config?: Partial): TavusLogger { if (!loggerInstance) { loggerInstance = new TavusLogger(config); } return loggerInstance; } export function destroyTavusLogger(): void { if (loggerInstance) { loggerInstance.destroy(); loggerInstance = null; } } // Environment-based configuration const isDevelopment = process.env.NODE_ENV === 'development'; const isVercel = !!process.env.VERCEL || !!process.env.VERCEL_ENV; const isProduction = process.env.NODE_ENV === 'production'; // Check if we're in a browser environment const isLocalhost = typeof window !== 'undefined' && window.location ? ( window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname.startsWith('192.168.') || window.location.hostname.startsWith('10.') || window.location.hostname.startsWith('172.') ) : true; // Allow logging in Node.js environments (test scripts, etc.) // Only log in development/local environments, never in production or on Vercel const shouldLogRequests = ( process.env.TAVUS_LOG_REQUESTS === 'true' || (isDevelopment && !isVercel) ) && isLocalhost && !isProduction; if (shouldLogRequests) { getTavusLogger({ enabled: true, logDirectory: process.env.TAVUS_LOG_DIRECTORY || path.join(process.cwd(), 'documentation', 'tavus-mock-data') }); }