import * as fs from 'fs'; import * as path from 'path'; import axios from 'axios'; import { logger } from '../utils/logger'; interface LogEntry { testId?: string; testName?: string; timestamp: string; request: { method: string; url: string; headers: Record; body: unknown; }; response: { status: number; statusText: string; headers: Record; body: unknown; ok: boolean; }; duration: number; metadata?: unknown; } interface TestResult { testId: string; testName: string; passed: boolean; expected: unknown; actual: unknown; differences: string[]; duration: number; url: string; } export class ComplianceTester { private logDataPath: string; private fakeServerUrl: string; private results: TestResult[] = []; constructor(logDataPath = '../../documentation/data/tavus-logs', fakeServerUrl = 'http://localhost:3001') { this.logDataPath = path.resolve(__dirname, logDataPath); this.fakeServerUrl = fakeServerUrl; } /** * Load all log files from the specified directory */ private loadLogFiles(): LogEntry[] { const logEntries: LogEntry[] = []; // Load test-calls const testCallsPath = path.join(this.logDataPath, 'test-calls'); if (fs.existsSync(testCallsPath)) { const testCallFiles = fs.readdirSync(testCallsPath).filter(file => file.endsWith('.json')); for (const file of testCallFiles) { try { const content = fs.readFileSync(path.join(testCallsPath, file), 'utf8'); const logEntry = JSON.parse(content) as LogEntry; logEntries.push(logEntry); } catch (_error) { logger.error(`Failed to parse test call file ${file}:`, error); } } } // Load requests const requestsPath = path.join(this.logDataPath, 'requests'); if (fs.existsSync(requestsPath)) { const requestFiles = fs.readdirSync(requestsPath).filter(file => file.endsWith('.json')); for (const file of requestFiles) { try { const content = fs.readFileSync(path.join(requestsPath, file), 'utf8'); const logEntry = JSON.parse(content) as LogEntry; logEntries.push(logEntry); } catch (_error) { logger.error(`Failed to parse request file ${file}:`, error); } } } return logEntries; } /** * Convert real Tavus URL to fake server URL */ private convertUrl(originalUrl: string): string { // Convert from proxy URLs to fake server URLs let convertedUrl = originalUrl .replace('https://buzztrail-proxy.vercel.app/api', this.fakeServerUrl) .replace('https://tavusapi.com', this.fakeServerUrl); // Ensure we're using the correct port if (!convertedUrl.includes('localhost:3001')) { convertedUrl = convertedUrl.replace('http://localhost', 'http://localhost:3001'); } return convertedUrl; } /** * Extract API key from headers or body */ private extractApiKey(headers: Record, body: unknown): string { // Check for x-api-key header if (headers['x-api-key']) { return headers['x-api-key']; } // Check for Authorization header if (headers['authorization'] && headers['authorization'].startsWith('Bearer ')) { return headers['authorization'].replace('Bearer ', ''); } // Check body for apiKey if (body && body.apiKey) { return body.apiKey; } // Default to test API key return 'test-api-key'; } /** * Compare two objects and return differences */ private compareObjects(expected: unknown, actual: unknown, path = ''): string[] { const differences: string[] = []; if (typeof expected !== typeof actual) { differences.push(`${path}: Expected type ${typeof expected}, got ${typeof actual}`); return differences; } if (typeof expected !== 'object' || expected === null || actual === null) { if (expected !== actual) { differences.push(`${path}: Expected "${expected}", got "${actual}"`); } return differences; } if (Array.isArray(expected) !== Array.isArray(actual)) { differences.push(`${path}: Expected ${Array.isArray(expected) ? 'array' : 'object'}, got ${Array.isArray(actual) ? 'array' : 'object'}`); return differences; } if (Array.isArray(expected)) { if (expected.length !== actual.length) { differences.push(`${path}: Expected array length ${expected.length}, got ${actual.length}`); } for (let i = 0; i < Math.min(expected.length, actual.length); i++) { differences.push(...this.compareObjects(expected[i], actual[i], `${path}[${i}]`)); } } else { const expectedKeys = Object.keys(expected); const actualKeys = Object.keys(actual); for (const key of expectedKeys) { if (!actualKeys.includes(key)) { differences.push(`${path}.${key}: Expected key missing`); } else { differences.push(...this.compareObjects(expected[key], actual[key], `${path}.${key}`)); } } for (const key of actualKeys) { if (!expectedKeys.includes(key)) { differences.push(`${path}.${key}: Unexpected key present`); } } } return differences; } /** * Run a single test against the fake server */ private async runTest(logEntry: LogEntry): Promise { const testId = logEntry.testId || `test-${Date.now()}`; const testName = logEntry.testName || 'unknown'; try { // Convert URL to fake server URL const fakeUrl = this.convertUrl(logEntry.request.url); // Extract API key const apiKey = this.extractApiKey(logEntry.request.headers, logEntry.request.body); // Prepare headers for fake server const headers: Record = { 'Content-Type': 'application/json', 'x-api-key': apiKey }; // Make request to fake server const startTime = Date.now(); const response = await axios({ method: logEntry.request.method.toLowerCase() as unknown, url: fakeUrl, headers, data: logEntry.request.body, validateStatus: () => true // Don't throw on error status codes }); const duration = Date.now() - startTime; // Compare responses const differences = this.compareObjects(logEntry.response.body, response.data); const result: TestResult = { testId, testName, passed: differences.length === 0 && response.status === logEntry.response.status, expected: logEntry.response.body, actual: response.data, differences, duration, url: fakeUrl }; return result; } catch (_error) { logger.error(`Test ${testId} failed with error:`, error); return { testId, testName, passed: false, expected: logEntry.response.body, actual: { error: error.message }, differences: [`Request failed: ${error.message}`], duration: 0, url: this.convertUrl(logEntry.request.url) }; } } /** * Run all compliance tests */ async runAllTests(): Promise { logger.info('Starting compliance tests...'); const logEntries = this.loadLogFiles(); logger.info(`Loaded ${logEntries.length} log entries for testing`); this.results = []; for (const logEntry of logEntries) { const result = await this.runTest(logEntry); this.results.push(result); if (result.passed) { logger.info(`✅ ${result.testName} (${result.testId}) - PASSED`); } else { logger.warn(`❌ ${result.testName} (${result.testId}) - FAILED`); logger.warn(` Differences: ${result.differences.join(', ')}`); } // Small delay to avoid overwhelming the server await new Promise(resolve => setTimeout(resolve, 100)); } return this.results; } /** * Generate test report */ generateReport(): string { const totalTests = this.results.length; const passedTests = this.results.filter(r => r.passed).length; const failedTests = totalTests - passedTests; const successRate = totalTests > 0 ? (passedTests / totalTests * 100).toFixed(2) : '0'; let report = ` # Fake Tavus Server Compliance Test Report ## Summary - **Total Tests**: ${totalTests} - **Passed**: ${passedTests} - **Failed**: ${failedTests} - **Success Rate**: ${successRate}% ## Failed Tests `; const failedResults = this.results.filter(r => !r.passed); for (const result of failedResults) { report += ` ### ${result.testName} (${result.testId}) - **URL**: ${result.url} - **Duration**: ${result.duration}ms - **Differences**: ${result.differences.join(', ')} - **Expected**: ${JSON.stringify(result.expected, null, 2)} - **Actual**: ${JSON.stringify(result.actual, null, 2)} `; } if (failedResults.length === 0) { report += ` 🎉 All tests passed! The fake server is fully compliant with the real Tavus API. `; } return report; } /** * Save test results to file */ saveResults(outputPath = './test-results.json'): void { const report = this.generateReport(); const resultsData = { timestamp: new Date().toISOString(), summary: { total: this.results.length, passed: this.results.filter(r => r.passed).length, failed: this.results.filter(r => !r.passed).length }, results: this.results, report }; fs.writeFileSync(outputPath, JSON.stringify(resultsData, null, 2)); fs.writeFileSync(outputPath.replace('.json', '.md'), report); logger.info(`Test results saved to ${outputPath}`); } }