import { MockDataService } from './mock-data-service'; import { IdGenerator as _IdGenerator } from '../utils/id-generator'; export class ResponseGenerator { private static errorRate = 0.1; private static responseDelay = { min: 100, max: 2000 }; static setErrorRate(rate: number): void { this.errorRate = rate; } static setResponseDelay(min: number, max: number): void { this.responseDelay = { min, max }; } static shouldInjectError(): boolean { return Math.random() < this.errorRate; } static getRandomErrorType(): string { const errorTypes = ['validation_error', 'not_found', 'rate_limit', 'internal_server_error']; return errorTypes[Math.floor(Math.random() * errorTypes.length)]; } static generateErrorResponse(errorType: string, _statusCode = 400): unknown { const timestamp = new Date().toISOString(); switch (errorType) { case 'validation_error': return { error: 'validation_error', message: 'Invalid request parameters', status_code: 400, timestamp }; case 'not_found': return { error: 'resource_not_found', message: 'The requested resource was not found', status_code: 404, timestamp }; case 'rate_limit': return { error: 'rate_limit_exceeded', message: 'Rate limit exceeded. Please try again later.', status_code: 429, timestamp }; default: return { error: 'internal_server_error', message: 'An unexpected error occurred', status_code: 500, timestamp }; } } static async addResponseDelay(): Promise { const delay = Math.random() * (this.responseDelay.max - this.responseDelay.min) + this.responseDelay.min; await new Promise(resolve => setTimeout(resolve, delay)); } static async generateResponse(method: string, path: string, requestBody?: unknown): Promise { // Add response delay await this.addResponseDelay(); // Check if we should inject an error if (this.shouldInjectError()) { const errorType = this.getRandomErrorType(); const errorResponse = this.generateErrorResponse(errorType, 400); throw new Error(JSON.stringify(errorResponse)); } // Generate response based on method and path switch (method) { case 'GET': return this.generateGetResponse(path); case 'POST': return this.generatePostResponse(path, requestBody); case 'PUT': return this.generatePutResponse(path, requestBody); case 'DELETE': return this.generateDeleteResponse(path); default: return this.generateErrorResponse('method_not_allowed', 405); } } private static generateGetResponse(path: string): unknown { switch (path) { case '/v2/auth/validate': return MockDataService.getUserInfo('test-api-key'); case '/v2/conversations': { const conversations = MockDataService.getConversations(); return { conversations: conversations.slice(0, 10), pagination: { total: conversations.length, limit: 10, offset: 0, has_more: false } }; } case '/v2/personas': { const personas = MockDataService.getPersonas(); return { personas: personas.slice(0, 10), pagination: { total: personas.length, limit: 10, offset: 0, has_more: false } }; } case '/v2/replicas': { const replicas = MockDataService.getReplicas(); return { data: replicas.reduce((acc, replica, index) => { acc[index.toString()] = replica; return acc; }, {} as Record) }; } case '/v2/videos': { const videos = MockDataService.getVideos(); return { videos: videos.slice(0, 10), pagination: { total: videos.length, limit: 10, offset: 0, has_more: false } }; } case '/v2/speech': { const speech = MockDataService.getSpeech(); return { speech: speech.slice(0, 10), pagination: { total: speech.length, limit: 10, offset: 0, has_more: false } }; } case '/v2/lipsync': { const lipsyncs = MockDataService.getLipsyncs(); return { lipsync: lipsyncs.slice(0, 10), pagination: { total: lipsyncs.length, limit: 10, offset: 0, has_more: false } }; } case '/v2/webhooks': { const webhooks = MockDataService.getWebhooks(); return { webhooks: webhooks.slice(0, 10), pagination: { total: webhooks.length, limit: 10, offset: 0, has_more: false } }; } case '/v2/analytics/usage': return MockDataService.getUsageAnalytics(); case '/v2/analytics/conversations': return MockDataService.getConversationAnalytics(); default: // Handle dynamic paths like /v2/conversations/:id if (path.includes('/conversations/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.getConversation(id!) || this.generateErrorResponse('not_found', 404); } if (path.includes('/personas/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.getPersona(id!) || this.generateErrorResponse('not_found', 404); } if (path.includes('/replicas/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.getReplica(id!) || this.generateErrorResponse('not_found', 404); } if (path.includes('/videos/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.getVideo(id!) || this.generateErrorResponse('not_found', 404); } if (path.includes('/speech/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.getSpeechById(id!) || this.generateErrorResponse('not_found', 404); } if (path.includes('/lipsync/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.getLipsync(id!) || this.generateErrorResponse('not_found', 404); } return this.generateErrorResponse('not_found', 404); } } private static generatePostResponse(path: string, requestBody?: unknown): unknown { switch (path) { case '/v2/conversations': if (!requestBody?.replica_id || !requestBody?.persona_id) { return this.generateErrorResponse('validation_error', 400); } return MockDataService.createConversation({ replica_id: requestBody.replica_id, persona_id: requestBody.persona_id, conversation_name: requestBody.conversation_name || `Conversation with ${requestBody.persona_id}`, callback_url: requestBody.callback_url, metadata: requestBody.metadata }); case '/v2/personas': if (!requestBody?.name || !requestBody?.description || !requestBody?.instructions || !requestBody?.voice_id || !requestBody?.language) { return this.generateErrorResponse('validation_error', 400); } return MockDataService.createPersona({ name: requestBody.name, description: requestBody.description, instructions: requestBody.instructions, voice_id: requestBody.voice_id, language: requestBody.language, metadata: requestBody.metadata }); case '/v2/replicas': if (!requestBody?.replica_name && !requestBody?.name) { return this.generateErrorResponse('validation_error', 400); } return MockDataService.createReplica({ replica_name: requestBody.replica_name || requestBody.name, model_name: requestBody.model_name }); case '/v2/videos': if (!requestBody?.conversation_id || !requestBody?.title) { return this.generateErrorResponse('validation_error', 400); } return MockDataService.createVideo({ conversation_id: requestBody.conversation_id, title: requestBody.title, description: requestBody.description, format: requestBody.format || 'mp4', quality: requestBody.quality || 'high', metadata: requestBody.metadata }); case '/v2/speech': if (!requestBody?.text || !requestBody?.voice_id || !requestBody?.language) { return this.generateErrorResponse('validation_error', 400); } return MockDataService.createSpeech({ text: requestBody.text, voice_id: requestBody.voice_id, language: requestBody.language, speed: requestBody.speed || 1.0, pitch: requestBody.pitch || 1.0, metadata: requestBody.metadata }); case '/v2/lipsync': if (!requestBody?.replica_id || !requestBody?.audio_url || !requestBody?.title) { return this.generateErrorResponse('validation_error', 400); } return MockDataService.createLipsync({ replica_id: requestBody.replica_id, audio_url: requestBody.audio_url, title: requestBody.title, description: requestBody.description, quality: requestBody.quality || 'high', metadata: requestBody.metadata }); case '/v2/webhooks': if (!requestBody?.url || !requestBody?.events || !requestBody?.secret) { return this.generateErrorResponse('validation_error', 400); } return MockDataService.createWebhook({ url: requestBody.url, events: requestBody.events, secret: requestBody.secret, description: requestBody.description }); default: // Handle dynamic paths like /v2/conversations/:id/end if (path.includes('/conversations/') && path.endsWith('/end')) { const id = path.split('/')[3]; return MockDataService.endConversation(id, requestBody?.reason); } return this.generateErrorResponse('not_found', 404); } } private static generatePutResponse(path: string, requestBody?: unknown): unknown { // Handle dynamic paths like /v2/personas/:id if (path.includes('/personas/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.updatePersona(id!, requestBody) || this.generateErrorResponse('not_found', 404); } if (path.includes('/replicas/') && path.split('/').length === 4) { const id = path.split('/').pop(); return MockDataService.updateReplica(id!, requestBody) || this.generateErrorResponse('not_found', 404); } return this.generateErrorResponse('method_not_allowed', 405); } private static generateDeleteResponse(path: string): unknown { // Handle dynamic paths like /v2/conversations/:id if (path.includes('/conversations/') && path.split('/').length === 4) { const id = path.split('/').pop(); const deleted = MockDataService.deleteConversation(id!); return deleted ? { conversation_id: id, message: 'Conversation deleted successfully' } : this.generateErrorResponse('not_found', 404); } if (path.includes('/personas/') && path.split('/').length === 4) { const id = path.split('/').pop(); const deleted = MockDataService.deletePersona(id!); return deleted ? { persona_id: id, message: 'Persona deleted successfully' } : this.generateErrorResponse('not_found', 404); } if (path.includes('/replicas/') && path.split('/').length === 4) { const id = path.split('/').pop(); const deleted = MockDataService.deleteReplica(id!); return deleted ? { replica_id: id, message: 'Replica deleted successfully' } : this.generateErrorResponse('not_found', 404); } if (path.includes('/videos/') && path.split('/').length === 4) { const id = path.split('/').pop(); const deleted = MockDataService.deleteVideo(id!); return deleted ? { video_id: id, message: 'Video deleted successfully' } : this.generateErrorResponse('not_found', 404); } if (path.includes('/speech/') && path.split('/').length === 4) { const id = path.split('/').pop(); const deleted = MockDataService.deleteSpeech(id!); return deleted ? { speech_id: id, message: 'Speech deleted successfully' } : this.generateErrorResponse('not_found', 404); } if (path.includes('/lipsync/') && path.split('/').length === 4) { const id = path.split('/').pop(); const deleted = MockDataService.deleteLipsync(id!); return deleted ? { lipsync_id: id, message: 'Lipsync deleted successfully' } : this.generateErrorResponse('not_found', 404); } if (path.includes('/webhooks/') && path.split('/').length === 4) { const id = path.split('/').pop(); const deleted = MockDataService.deleteWebhook(id!); return deleted ? { webhook_id: id, message: 'Webhook deleted successfully' } : this.generateErrorResponse('not_found', 404); } return this.generateErrorResponse('not_found', 404); } }