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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | import { v4 as uuidv4 } from 'uuid'; export interface TavusLogEntry { sessionId: string; timestamp: string; request: { method: string; url: string; headers: Record<string, string>; body?: any; bodySize?: number; bodyType?: string; queryParams?: Record<string, string>; fullUrl?: string; }; response: { status: number; statusText: string; headers: Record<string, string>; body?: any; bodySize?: number; bodyType?: string; duration: number; ok: boolean; redirected: boolean; type: string; }; metadata?: { endpoint: string; requestType: 'conversation' | 'video' | 'auth' | 'streaming' | 'other'; hasBinaryData: boolean; binaryDataSize?: number; isVideoData?: boolean; shouldLog?: boolean; contentType?: string; contentLength?: number; userAgent?: string; referrer?: string; timestamp?: number; requestId?: string; }; error?: { name: string; message: string; stack?: string; type: string; details?: any; }; raw?: { requestHeaders?: Record<string, string>; responseHeaders?: Record<string, string>; requestBody?: any; responseBody?: any; url?: string; method?: string; }; } export interface TavusLoggerConfig { enabled: boolean; includeHeaders: boolean; includeBody: boolean; maxBodySize: number; // in bytes sessionTimeout: number; // in minutes logVideoData: boolean; // whether to log video/streaming data logErrors: boolean; // whether to log error responses logAllStatusCodes: boolean; // whether to log all status codes or just errors sampleLargePayloads: boolean; // whether to sample large payloads instead of truncating maxVideoPayloadSize: number; // max size for video payloads before sampling // Enhanced logging for API reverse engineering logRawData: boolean; // log raw request/response data logQueryParams: boolean; // log URL query parameters logUserAgent: boolean; // log user agent string logReferrer: boolean; // log referrer information logTimestamps: boolean; // log detailed timestamps logRequestIds: boolean; // log unique request IDs logContentTypes: boolean; // log content type information logContentLengths: boolean; // log content length headers logAllHeaders: boolean; // log all headers (including sensitive ones) logStackTraces: boolean; // log error stack traces logNetworkInfo: boolean; // log network-related information } class TavusLoggerBrowser { private config: TavusLoggerConfig; private currentSessionId: string; private sessionStartTime: number; private logBuffer: TavusLogEntry[] = []; private flushInterval: number | null = null; constructor(config: Partial<TavusLoggerConfig> = {}) { this.config = { enabled: true, includeHeaders: true, includeBody: true, maxBodySize: 1024 * 1024, // 1MB sessionTimeout: 30, // 30 minutes logVideoData: false, // don't log video data by default logErrors: true, // always log errors logAllStatusCodes: true, // log all status codes sampleLargePayloads: true, // sample large payloads maxVideoPayloadSize: 1024 * 10, // 10KB for video payloads // Enhanced logging for API reverse engineering logRawData: true, // log raw request/response data logQueryParams: true, // log URL query parameters logUserAgent: true, // log user agent string logReferrer: true, // log referrer information logTimestamps: true, // log detailed timestamps logRequestIds: true, // log unique request IDs logContentTypes: true, // log content type information logContentLengths: true, // log content length headers logAllHeaders: true, // log all headers (including sensitive ones) logStackTraces: true, // log error stack traces logNetworkInfo: true, // log network-related information ...config }; this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); this.startFlushInterval(); } private startFlushInterval(): void { Iif (this.flushInterval) { clearInterval(this.flushInterval); } this.flushInterval = window.setInterval(() => { void this.flushBuffer(); // Handle async flush }, 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<TavusLogEntry['metadata']>['requestType'] { Iif (url.includes('/conversations')) return 'conversation'; Iif (url.includes('/videos')) return 'video'; Iif (url.includes('/auth')) return 'auth'; Iif (url.includes('/stream') || url.includes('/events')) return 'streaming'; return 'other'; } private sanitizeHeaders(headers: Record<string, string>): Record<string, string> { Iif (!this.config.includeHeaders) return {}; const sanitized: Record<string, string> = {}; const sensitiveKeys = ['authorization', 'cookie', 'x-api-key', 'token']; Object.entries(headers).forEach(([key, value]) => { const lowerKey = key.toLowerCase(); if (sensitiveKeys.includes(lowerKey) && !this.config.logAllHeaders) { sanitized[key] = '[REDACTED]'; } else { sanitized[key] = value; } }); return sanitized; } private extractQueryParams(url: string): Record<string, string> { Iif (!this.config.logQueryParams) return {}; try { const urlObj = new URL(url); const params: Record<string, string> = {}; urlObj.searchParams.forEach((value, key) => { params[key] = value; }); return params; } catch { return {}; } } private getNetworkInfo(): Record<string, any> { Iif (!this.config.logNetworkInfo) return {}; const info: Record<string, any> = {}; // Browser network information Iif ('connection' in navigator) { const connection = (navigator as any).connection; Iif (connection) { info.effectiveType = connection.effectiveType; info.downlink = connection.downlink; info.rtt = connection.rtt; info.saveData = connection.saveData; } } // Performance timing Iif (performance?.timing) { info.navigationStart = performance.timing.navigationStart; info.fetchStart = performance.timing.fetchStart; info.domainLookupStart = performance.timing.domainLookupStart; info.domainLookupEnd = performance.timing.domainLookupEnd; info.connectStart = performance.timing.connectStart; info.connectEnd = performance.timing.connectEnd; info.requestStart = performance.timing.requestStart; info.responseStart = performance.timing.responseStart; info.responseEnd = performance.timing.responseEnd; } return info; } private sanitizeBody(body: any, isVideoData = false): any { Iif (!this.config.includeBody || !body) return undefined; const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); const maxSize = isVideoData ? this.config.maxVideoPayloadSize : this.config.maxBodySize; Iif (bodyStr.length > maxSize) { if (this.config.sampleLargePayloads && isVideoData) { // For video data, sample the payload instead of truncating return this.sampleVideoPayload(bodyStr); } else { return { truncated: true, size: bodyStr.length, preview: bodyStr.substring(0, 1000) + '...', type: isVideoData ? 'video' : 'regular' }; } } return body; } private sampleVideoPayload(payload: string): any { // Sample video payload by taking chunks from beginning, middle, and end const totalLength = payload.length; const sampleSize = Math.min(1000, Math.floor(totalLength * 0.01)); // 1% or 1000 chars const start = payload.substring(0, sampleSize); const middle = payload.substring(Math.floor(totalLength / 2), Math.floor(totalLength / 2) + sampleSize); const end = payload.substring(totalLength - sampleSize); return { sampled: true, totalSize: totalLength, sampleSize: sampleSize, samples: { start: start, middle: middle, end: end }, type: 'video' }; } private isBinaryData(data: any): boolean { Iif (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<string, string>, body?: any ): string { Iif (!this.config.enabled) return ''; Iif (this.shouldStartNewSession()) { this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); } const requestId = uuidv4(); const startTime = Date.now(); // Enhanced request logging with all details const requestInfo = { method, url, headers: this.sanitizeHeaders(headers), body: this.sanitizeBody(body), startTime, sessionId: this.currentSessionId, // Additional metadata for API reverse engineering queryParams: this.extractQueryParams(url), fullUrl: url, bodySize: body ? (typeof body === 'string' ? body.length : JSON.stringify(body).length) : 0, bodyType: body ? typeof body : 'undefined', contentType: headers['content-type'] || headers['Content-Type'], contentLength: headers['content-length'] || headers['Content-Length'], userAgent: this.config.logUserAgent ? navigator.userAgent : undefined, referrer: this.config.logReferrer ? document.referrer : undefined, timestamp: this.config.logTimestamps ? Date.now() : undefined, requestId: this.config.logRequestIds ? requestId : undefined, networkInfo: this.getNetworkInfo() }; // Store request info for later response logging this.pendingRequests.set(requestId, requestInfo); // Log raw request data if enabled Iif (this.config.logRawData) { console.log(`[TavusLogger] Raw Request ${requestId}:`, { method, url, headers, body, timestamp: new Date().toISOString(), sessionId: this.currentSessionId }); } return requestId; } logResponse( requestId: string, status: number, headers: Record<string, string>, body?: any, response?: Response ): void { Iif (!this.config.enabled) return; const requestInfo = this.pendingRequests.get(requestId); Iif (!requestInfo) { console.warn(`TavusLogger: No pending request found for ID ${requestId}`); return; } this.pendingRequests.delete(requestId); const duration = Date.now() - requestInfo.startTime; // Determine if this is video data const isVideoData = this.isVideoData(requestInfo.url, headers, body); // Check if we should log this response const shouldLog = this.shouldLogResponse(status, isVideoData); Iif (!shouldLog) { console.log(`[TavusLogger] Skipping ${requestInfo.method} ${requestInfo.url} -> ${status} (${duration}ms) - ${isVideoData ? 'video data' : 'filtered'}`); return; } const sanitizedBody = this.sanitizeBody(body, isVideoData); 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, bodySize: requestInfo.bodySize, bodyType: requestInfo.bodyType, queryParams: requestInfo.queryParams, fullUrl: requestInfo.fullUrl }, response: { status, statusText: response?.statusText || '', headers: this.sanitizeHeaders(headers), body: sanitizedBody, bodySize: typeof sanitizedBody === 'string' ? sanitizedBody.length : JSON.stringify(sanitizedBody).length, bodyType: typeof sanitizedBody, duration, ok: response?.ok ?? (status >= 200 && status < 300), redirected: response?.redirected || false, type: response?.type || 'default' }, metadata: { endpoint: new URL(requestInfo.url).pathname, requestType: this.getEndpointType(requestInfo.url), hasBinaryData, binaryDataSize, isVideoData, shouldLog, contentType: requestInfo.contentType, contentLength: requestInfo.contentLength ? parseInt(requestInfo.contentLength, 10) : undefined, userAgent: requestInfo.userAgent, referrer: requestInfo.referrer, timestamp: requestInfo.timestamp, requestId: requestInfo.requestId }, raw: this.config.logRawData ? { requestHeaders: headers, responseHeaders: headers, requestBody: requestInfo.body, responseBody: body, url: requestInfo.url, method: requestInfo.method } : undefined }; this.logBuffer.push(logEntry); // Log errors separately Iif (status >= 400 && this.config.logErrors) { this.logError(logEntry); } // Flush immediately for errors or large responses Iif (status >= 400 || hasBinaryData || isVideoData) { void this.flushBuffer(); } // Log to console for debugging const logLevel = status >= 400 ? 'ERROR' : status >= 300 ? 'WARN' : 'INFO'; console.log(`[TavusLogger] ${logLevel} ${requestInfo.method} ${requestInfo.url} -> ${status} (${duration}ms)${isVideoData ? ' [VIDEO]' : ''}`); } private shouldLogResponse(status: number, isVideoData: boolean): boolean { // Always log errors Iif (status >= 400 && this.config.logErrors) { return true; } // Log all status codes if configured Iif (this.config.logAllStatusCodes) { return true; } // Don't log video data unless specifically enabled Iif (isVideoData && !this.config.logVideoData) { return false; } // Log successful responses return status >= 200 && status < 300; } private isVideoData(url: string, headers: Record<string, string>, body?: any): boolean { // Check URL patterns Iif (url.includes('/video') || url.includes('/stream') || url.includes('/media')) { return true; } // Check content type headers const contentType = headers['content-type'] || headers['Content-Type'] || ''; Iif (contentType.includes('video/') || contentType.includes('audio/') || contentType.includes('application/octet-stream')) { return true; } // Check for large binary data in body Iif (body && typeof body === 'string' && body.length > 10000) { // Check if it looks like base64 encoded video/audio data Iif (/^[A-Za-z0-9+/]*={0,2}$/.test(body) && body.length > 50000) { return true; } } return false; } private logError(logEntry: TavusLogEntry): void { const errorInfo = { method: logEntry.request.method, url: logEntry.request.url, status: logEntry.response.status, statusText: logEntry.response.statusText, duration: logEntry.response.duration, timestamp: logEntry.timestamp, sessionId: logEntry.sessionId, requestId: logEntry.metadata?.requestId, headers: logEntry.response.headers, body: logEntry.response.body, raw: logEntry.raw }; console.error(`[TavusLogger] Error: ${logEntry.request.method} ${logEntry.request.url} -> ${logEntry.response.status}`, errorInfo); // Log detailed error information if enabled Iif (this.config.logStackTraces) { console.error(`[TavusLogger] Error Stack Trace:`, new Error().stack); } } private async flushBuffer(): Promise<void> { Iif (this.logBuffer.length === 0) return; // Send logs to the local log server const logServerUrl = 'http://localhost:3002'; try { // Prepare entries for the log server const entries = this.logBuffer.map(entry => ({ method: entry.request.method, url: entry.request.url, headers: entry.request.headers, body: entry.request.body, status: entry.response.status, responseHeaders: entry.response.headers, responseBody: entry.response.body, duration: entry.response.duration })); // Send to log server const response = await fetch(`${logServerUrl}/log/batch`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ entries }) }); if (response.ok) { const result = await response.json(); console.log(`[TavusLogger] Sent ${this.logBuffer.length} logs to server:`, result); } else { console.warn(`[TavusLogger] Failed to send logs to server: ${response.status}`); // Fallback to console logging this.logBuffer.forEach((entry, index) => { console.log(`[TavusLogger] Entry ${index + 1}:`, entry); }); } } catch (error) { console.error('[TavusLogger] Failed to send logs to server:', error); // Fallback to console logging console.group(`[TavusLogger] Flushed ${this.logBuffer.length} log entries (console fallback)`); this.logBuffer.forEach((entry, index) => { console.log(`Entry ${index + 1}:`, entry); }); console.groupEnd(); } this.logBuffer = []; } logStreamingEvent( method: string, url: string, eventType: string, data: any ): void { Iif (!this.config.enabled) return; const logEntry: TavusLogEntry = { sessionId: this.currentSessionId, timestamp: new Date().toISOString(), request: { method, url, headers: {}, body: { eventType, data } }, response: { status: 200, statusText: 'OK', headers: { 'content-type': 'text/event-stream' }, body: { eventType, data }, bodySize: JSON.stringify({ eventType, data }).length, bodyType: 'object', duration: 0, ok: true, redirected: false, type: 'default' }, metadata: { endpoint: new URL(url).pathname, requestType: 'streaming', hasBinaryData: false } }; this.logBuffer.push(logEntry); console.log(`[TavusLogger] Streaming event: ${eventType}`, data); } getSessionSummary(): { sessionId: string; requestCount: number; errorCount: number; totalDuration: number; endpoints: string[]; } { 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); Iif (sessionRequests.length === 0) { console.warn(`TavusLogger: No requests found for session ${targetSessionId}`); return; } // In browser, we'll log to console and offer download const sessionData = JSON.stringify(sessionRequests, null, 2); console.log(`[TavusLogger] Session ${targetSessionId} exported:`, sessionRequests); // Create downloadable file const blob = new Blob([sessionData], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `tavus-session-${targetSessionId}-${Date.now()}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); console.log(`[TavusLogger] Session ${targetSessionId} downloaded with ${sessionRequests.length} requests`); } destroy(): void { Iif (this.flushInterval) { clearInterval(this.flushInterval); } this.flushBuffer(); } private pendingRequests = new Map<string, { method: string; url: string; headers: Record<string, string>; body?: any; startTime: number; sessionId: string; // Enhanced metadata for API reverse engineering queryParams?: Record<string, string>; fullUrl?: string; bodySize?: number; bodyType?: string; contentType?: string; contentLength?: string; userAgent?: string; referrer?: string; timestamp?: number; requestId?: string; networkInfo?: Record<string, any>; }>(); } // Singleton instance let loggerInstance: TavusLoggerBrowser | null = null; export function getTavusLogger(config?: Partial<TavusLoggerConfig>): TavusLoggerBrowser { Iif (!loggerInstance) { loggerInstance = new TavusLoggerBrowser(config); } return loggerInstance; } export function destroyTavusLogger(): void { Iif (loggerInstance) { loggerInstance.destroy(); loggerInstance = null; } } // Environment-based configuration const isDevelopment = typeof process !== 'undefined' ? process.env.NODE_ENV === 'development' : true; // 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.) const shouldLogRequests = (typeof process !== 'undefined' && process.env.TAVUS_LOG_REQUESTS === 'true' || isDevelopment) && isLocalhost; Iif (shouldLogRequests) { getTavusLogger({ enabled: true, includeHeaders: true, includeBody: true, logVideoData: false, // Set to true to log video data logErrors: true, logAllStatusCodes: true, sampleLargePayloads: true, maxVideoPayloadSize: 1024 * 10 // 10KB for video payloads }); } |