{"owner":"EvolutionAPI","repo":"evolution-api","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["AGENTS.md","CLAUDE.md"],"skills":{"AGENTS.md":"# Evolution API - AI Agent Guidelines\n\nThis document provides comprehensive guidelines for AI agents (Claude, GPT, Cursor, etc.) working with the Evolution API codebase.\n\n## Project Overview\n\n**Evolution API** is a production-ready, multi-tenant WhatsApp API platform built with Node.js, TypeScript, and Express.js. It supports multiple WhatsApp providers and extensive integrations with chatbots, CRM systems, and messaging platforms.\n\n## Project Structure & Module Organization\n\n### Core Directories\n- **`src/`** – TypeScript source code with modular architecture\n  - `api/controllers/` – HTTP route handlers (thin layer)\n  - `api/services/` – Business logic (core functionality)\n  - `api/routes/` – Express route definitions (RouterBroker pattern)\n  - `api/integrations/` – External service integrations\n    - `channel/` – WhatsApp providers (Baileys, Business API, Evolution)\n    - `chatbot/` – AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)\n    - `event/` – Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)\n    - `storage/` – File storage (S3, MinIO)\n  - `dto/` – Data Transfer Objects (simple classes, no decorators)\n  - `guards/` – Authentication/authorization middleware\n  - `types/` – TypeScript type definitions\n  - `repository/` – Data access layer (Prisma)\n- **`prisma/`** – Database schemas and migrations\n  - `postgresql-schema.prisma` / `mysql-schema.prisma` – Provider-specific schemas\n  - `postgresql-migrations/` / `mysql-migrations/` – Provider-specific migrations\n- **`config/`** – Environment and application configuration\n- **`utils/`** – Shared utilities and helper functions\n- **`validate/`** – JSONSchema7 validation schemas\n- **`exceptions/`** – Custom HTTP exception classes\n- **`cache/`** – Redis and local cache implementations\n\n### Build & Deployment\n- **`dist/`** – Build output (do not edit directly)\n- **`public/`** – Static assets and media files\n- **`Docker*`**, **`docker-compose*.yaml`** – Containerization and local development stack\n\n## Build, Test, and Development Commands\n\n### Development Workflow\n```bash\n# Development server with hot reload\nnpm run dev:server\n\n# Direct execution for testing\nnpm start\n\n# Production build and run\nnpm run build\nnpm run start:prod\n```\n\n### Code Quality\n```bash\n# Linting and formatting\nnpm run lint        # ESLint with auto-fix\nnpm run lint:check  # ESLint check only\n\n# Commit with conventional commits\nnpm run commit      # Interactive commit with Commitizen\n```\n\n### Database Management\n```bash\n# Set database provider first (CRITICAL)\nexport DATABASE_PROVIDER=postgresql  # or mysql\n\n# Generate Prisma client\nnpm run db:generate\n\n# Development migrations (with provider sync)\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n\n# Production deployment\nnpm run db:deploy      # Unix/Mac\nnpm run db:deploy:win  # Windows\n\n# Database tools\nnpm run db:studio      # Open Prisma Studio\n```\n\n### Docker Development\n```bash\n# Start local services (Redis, PostgreSQL, etc.)\ndocker-compose up -d\n\n# Full development stack\ndocker-compose -f docker-compose.dev.yaml up -d\n```\n\n## Coding Standards & Architecture Patterns\n\n### Code Style (Enforced by ESLint + Prettier)\n- **TypeScript strict mode** with full type coverage\n- **2-space indentation**, single quotes, trailing commas\n- **120-character line limit**\n- **Import order** via `simple-import-sort`\n- **File naming**: `feature.kind.ts` (e.g., `whatsapp.baileys.service.ts`)\n- **Naming conventions**:\n  - Classes: `PascalCase`\n  - Functions/variables: `camelCase`\n  - Constants: `UPPER_SNAKE_CASE`\n  - Files: `kebab-case.type.ts`\n\n### Architecture Patterns\n\n#### Service Layer Pattern\n```typescript\nexport class ExampleService {\n  constructor(private readonly waMonitor: WAMonitoringService) {}\n  \n  private readonly logger = new Logger('ExampleService');\n  \n  public async create(instance: InstanceDto, data: ExampleDto) {\n    // Business logic here\n    return { example: { ...instance, data } };\n  }\n  \n  public async find(instance: InstanceDto): Promise<ExampleDto | null> {\n    try {\n      const result = await this.waMonitor.waInstances[instance.instanceName].findData();\n      return result || null; // Return null on not found (Evolution pattern)\n    } catch (error) {\n      this.logger.error('Error finding data:', error);\n      return null; // Return null on error (Evolution pattern)\n    }\n  }\n}\n```\n\n#### Controller Pattern (Thin Layer)\n```typescript\nexport class ExampleController {\n  constructor(private readonly exampleService: ExampleService) {}\n  \n  public async createExample(instance: InstanceDto, data: ExampleDto) {\n    return this.exampleService.create(instance, data);\n  }\n}\n```\n\n#### RouterBroker Pattern\n```typescript\nexport class ExampleRouter extends RouterBroker {\n  constructor(...guards: any[]) {\n    super();\n    this.router.post(this.routerPath('create'), ...guards, async (req, res) => {\n      const response = await this.dataValidate<ExampleDto>({\n        request: req,\n        schema: exampleSchema, // JSONSchema7\n        ClassRef: ExampleDto,\n        execute: (instance, data) => controller.createExample(instance, data),\n      });\n      res.status(201).json(response);\n    });\n  }\n}\n```\n\n#### DTO Pattern (Simple Classes)\n```typescript\n// CORRECT - Evolution API pattern (no decorators)\nexport class ExampleDto {\n  name: string;\n  description?: string;\n  enabled: boolean;\n}\n\n// INCORRECT - Don't use class-validator decorators\nexport class BadExampleDto {\n  @IsString() // ❌ Evolution API doesn't use decorators\n  name: string;\n}\n```\n\n#### Validation Pattern (JSONSchema7)\n```typescript\nimport { JSONSchema7 } from 'json-schema';\nimport { v4 } from 'uuid';\n\nexport const exampleSchema: JSONSchema7 = {\n  $id: v4(),\n  type: 'object',\n  properties: {\n    name: { type: 'string' },\n    description: { type: 'string' },\n    enabled: { type: 'boolean' },\n  },\n  required: ['name', 'enabled'],\n};\n```\n\n## Multi-Tenant Architecture\n\n### Instance Isolation\n- **CRITICAL**: All operations must be scoped by `instanceName` or `instanceId`\n- **Database queries**: Always include `where: { instanceId: ... }`\n- **Authentication**: Validate instance ownership before operations\n- **Data isolation**: Complete separation between tenant instances\n\n### WhatsApp Instance Management\n```typescript\n// Access instance via WAMonitoringService\nconst waInstance = this.waMonitor.waInstances[instance.instanceName];\nif (!waInstance) {\n  throw new NotFoundException(`Instance ${instance.instanceName} not found`);\n}\n```\n\n## Database Patterns\n\n### Multi-Provider Support\n- **PostgreSQL**: Uses `@db.Integer`, `@db.JsonB`, `@default(now())`\n- **MySQL**: Uses `@db.Int`, `@db.Json`, `@default(now())`\n- **Environment**: Set `DATABASE_PROVIDER=postgresql` or `mysql`\n- **Migrations**: Provider-specific folders auto-selected\n\n### Prisma Repository Pattern\n```typescript\n// Always use PrismaRepository for database operations\nconst result = await this.prismaRepository.instance.findUnique({\n  where: { name: instanceName },\n});\n```\n\n## Integration Patterns\n\n### Channel Integration (WhatsApp Providers)\n- **Baileys**: WhatsApp Web with QR code authentication\n- **Business API**: Official Meta WhatsApp Business API  \n- **Evolution API**: Custom WhatsApp integration\n- **Pattern**: Extend base channel service classes\n\n### Chatbot Integration\n- **Base classes**: Extend `BaseChatbotService` and `BaseChatbotController`\n- **Trigger system**: Support keyword, regex, and advanced triggers\n- **Session management**: Handle conversation state per user\n- **Available integrations**: EvolutionBot, OpenAI, Dify, Typebot, Chatwoot, Flowise, N8N, EvoAI\n\n### Event Integration\n- **Internal events**: EventEmitter2 for application events\n- **External events**: WebSocket, RabbitMQ, SQS, NATS, Pusher\n- **Webhook delivery**: Reliable delivery with retry logic\n\n## Testing Guidelines\n\n### Current State\n- **No formal test suite** currently implemented\n- **Manual testing** is the primary approach\n- **Integration testing** in development environment\n\n### Testing Strategy\n```typescript\n// Place tests in test/ directory as *.test.ts\n// Run: npm test (watches test/all.test.ts)\n\ndescribe('ExampleService', () => {\n  it('should create example', async () => {\n    // Mock external dependencies\n    // Test business logic\n    // Assert expected behavior\n  });\n});\n```\n\n### Recommended Approach\n- Focus on **critical business logic** in services\n- **Mock external dependencies** (WhatsApp APIs, databases)\n- **Integration tests** for API endpoints\n- **Manual testing** for WhatsApp connection flows\n\n## Commit & Pull Request Guidelines\n\n### Conventional Commits (Enforced by commitlint)\n```bash\n# Use interactive commit tool\nnpm run commit\n\n# Commit format: type(scope): subject (max 100 chars)\n# Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert, security\n```\n\n### Examples\n- `feat(api): add WhatsApp message status endpoint`\n- `fix(baileys): resolve connection timeout issue`\n- `docs(readme): update installation instructions`\n- `refactor(service): extract common message validation logic`\n\n### Pull Request Requirements\n- **Clear description** of changes and motivation\n- **Linked issues** if applicable\n- **Migration impact** (specify database provider)\n- **Local testing steps** with screenshots/logs\n- **Breaking changes** clearly documented\n\n## Security & Configuration\n\n### Environment Setup\n```bash\n# Copy example environment file\ncp .env.example .env\n\n# NEVER commit secrets to version control\n# Set DATABASE_PROVIDER before database commands\nexport DATABASE_PROVIDER=postgresql  # or mysql\n```\n\n### Security Best Practices\n- **API key authentication** via `apikey` header\n- **Input validation** with JSONSchema7\n- **Rate limiting** on all endpoints\n- **Webhook signature validation**\n- **Instance-based access control**\n- **Secure defaults** for all configurations\n\n### Vulnerability Reporting\n- See `SECURITY.md` for security vulnerability reporting process\n- Contact: `contato@evolution-api.com`\n\n## Communication Standards\n\n### Language Requirements\n- **User communication**: Always respond in Portuguese (PT-BR)\n- **Code/comments**: English for technical documentation\n- **API responses**: English for consistency\n- **Error messages**: Portuguese for user-facing errors\n\n### Documentation Standards\n- **Inline comments**: Document complex business logic\n- **API documentation**: Document all public endpoints\n- **Integration guides**: Document new integration patterns\n- **Migration guides**: Document database schema changes\n\n## Performance & Scalability\n\n### Caching Strategy\n- **Redis primary**: Distributed caching for production\n- **Node-cache fallback**: Local caching when Redis unavailable\n- **TTL strategy**: Appropriate cache expiration per data type\n- **Cache invalidation**: Proper invalidation on data changes\n\n### Connection Management\n- **Database**: Prisma connection pooling\n- **WhatsApp**: One connection per instance with lifecycle management\n- **Redis**: Connection pooling and retry logic\n- **External APIs**: Rate limiting and retry with exponential backoff\n\n### Monitoring & Observability\n- **Structured logging**: Pino logger with correlation IDs\n- **Error tracking**: Comprehensive error scenarios\n- **Health checks**: Instance status and connection monitoring\n- **Telemetry**: Usage analytics (non-sensitive data only)\n\n","CLAUDE.md":"# CLAUDE.md\n\nThis file provides comprehensive guidance to Claude AI when working with the Evolution API codebase.\n\n## Project Overview\n\n**Evolution API** is a powerful, production-ready REST API for WhatsApp communication that supports multiple WhatsApp providers:\n- **Baileys** (WhatsApp Web) - Open-source WhatsApp Web client\n- **Meta Business API** - Official WhatsApp Business API\n- **Evolution API** - Custom WhatsApp integration\n\nBuilt with **Node.js 20+**, **TypeScript 5+**, and **Express.js**, it provides extensive integrations with chatbots, CRM systems, and messaging platforms in a **multi-tenant architecture**.\n\n## Common Development Commands\n\n### Build and Run\n```bash\n# Development\nnpm run dev:server    # Run in development with hot reload (tsx watch)\n\n# Production\nnpm run build        # TypeScript check + tsup build\nnpm run start:prod   # Run production build\n\n# Direct execution\nnpm start           # Run with tsx\n```\n\n### Code Quality\n```bash\nnpm run lint        # ESLint with auto-fix\nnpm run lint:check  # ESLint check only\nnpm run commit      # Interactive commit with commitizen\n```\n\n### Database Management\n```bash\n# Set database provider first\nexport DATABASE_PROVIDER=postgresql  # or mysql\n\n# Generate Prisma client (automatically uses DATABASE_PROVIDER env)\nnpm run db:generate\n\n# Deploy migrations (production)\nnpm run db:deploy      # Unix/Mac\nnpm run db:deploy:win  # Windows\n\n# Development migrations (with sync to provider folder)\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n\n# Open Prisma Studio\nnpm run db:studio\n\n# Development migrations\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n```\n\n### Testing\n```bash\nnpm test    # Run tests with watch mode\n```\n\n## Architecture Overview\n\n### Core Structure\n- **Multi-tenant SaaS**: Complete instance isolation with per-tenant authentication\n- **Multi-provider database**: PostgreSQL and MySQL via Prisma ORM with provider-specific schemas and migrations\n- **WhatsApp integrations**: Baileys, Meta Business API, and Evolution API with unified interface\n- **Event-driven architecture**: EventEmitter2 for internal events + WebSocket, RabbitMQ, SQS, NATS, Pusher for external events\n- **Microservices pattern**: Modular integrations for chatbots, storage, and external services\n\n### Directory Layout\n```\nsrc/\n├── api/\n│   ├── controllers/     # HTTP route handlers (thin layer)\n│   ├── services/        # Business logic (core functionality)\n│   ├── repository/      # Data access layer (Prisma)\n│   ├── dto/            # Data Transfer Objects (simple classes)\n│   ├── guards/         # Authentication/authorization middleware\n│   ├── integrations/   # External service integrations\n│   │   ├── channel/    # WhatsApp providers (Baileys, Business API, Evolution)\n│   │   ├── chatbot/    # AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)\n│   │   ├── event/      # Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)\n│   │   └── storage/    # File storage (S3, MinIO)\n│   ├── routes/         # Express route definitions (RouterBroker pattern)\n│   └── types/          # TypeScript type definitions\n├── config/             # Environment and app configuration\n├── cache/             # Redis and local cache implementations\n├── exceptions/        # Custom HTTP exception classes\n├── utils/            # Shared utilities and helpers\n└── validate/         # JSONSchema7 validation schemas\n```\n\n### Key Integration Points\n\n**Channel Integrations** (`src/api/integrations/channel/`):\n- **Baileys**: WhatsApp Web client with QR code authentication\n- **Business API**: Official Meta WhatsApp Business API\n- **Evolution API**: Custom WhatsApp integration\n- Connection lifecycle management per instance with automatic reconnection\n\n**Chatbot Integrations** (`src/api/integrations/chatbot/`):\n- **EvolutionBot**: Native chatbot with trigger system\n- **Chatwoot**: Customer service platform integration\n- **Typebot**: Visual chatbot flow builder\n- **OpenAI**: AI capabilities including GPT and Whisper (audio transcription)\n- **Dify**: AI agent workflow platform\n- **Flowise**: LangChain visual builder\n- **N8N**: Workflow automation platform\n- **EvoAI**: Custom AI integration\n\n**Event Integrations** (`src/api/integrations/event/`):\n- **WebSocket**: Real-time Socket.io connections\n- **RabbitMQ**: Message queue for async processing\n- **Amazon SQS**: Cloud-based message queuing\n- **NATS**: High-performance messaging system\n- **Pusher**: Real-time push notifications\n\n**Storage Integrations** (`src/api/integrations/storage/`):\n- **AWS S3**: Cloud object storage\n- **MinIO**: Self-hosted S3-compatible storage\n- Media file management and URL generation\n\n### Database Schema Management\n- Separate schema files: `postgresql-schema.prisma` and `mysql-schema.prisma`\n- Environment variable `DATABASE_PROVIDER` determines active database\n- Migration folders are provider-specific and auto-selected during deployment\n\n### Authentication & Security\n- **API key-based authentication** via `apikey` header (global or per-instance)\n- **Instance-specific tokens** for WhatsApp connection authentication\n- **Guards system** for route protection and authorization\n- **Input validation** using JSONSchema7 with RouterBroker `dataValidate`\n- **Rate limiting** and security middleware\n- **Webhook signature validation** for external integrations\n\n## Important Implementation Details\n\n### WhatsApp Instance Management\n- Each WhatsApp connection is an \"instance\" with unique name\n- Instance data stored in database with connection state\n- Session persistence in database or file system (configurable)\n- Automatic reconnection handling with exponential backoff\n\n### Message Queue Architecture\n- Supports RabbitMQ, Amazon SQS, and WebSocket for events\n- Event types: message.received, message.sent, connection.update, etc.\n- Configurable per instance which events to send\n\n### Media Handling\n- Local storage or S3/Minio for media files\n- Automatic media download from WhatsApp\n- Media URL generation for external access\n- Support for audio transcription via OpenAI\n\n### Multi-tenancy Support\n- Instance isolation at database level\n- Separate webhook configurations per instance\n- Independent integration settings per instance\n\n## Environment Configuration\n\nKey environment variables are defined in `.env.example`. The system uses a strongly-typed configuration system via `src/config/env.config.ts`.\n\nCritical configurations:\n- `DATABASE_PROVIDER`: postgresql or mysql\n- `DATABASE_CONNECTION_URI`: Database connection string\n- `AUTHENTICATION_API_KEY`: Global API authentication\n- `REDIS_ENABLED`: Enable Redis cache\n- `RABBITMQ_ENABLED`/`SQS_ENABLED`: Message queue options\n\n## Development Guidelines\n\nThe project follows comprehensive development standards defined in `.cursor/rules/`:\n\n### Core Principles\n- **Always respond in Portuguese (PT-BR)** for user communication\n- **Follow established architecture patterns** (Service Layer, RouterBroker, etc.)\n- **Robust error handling** with retry logic and graceful degradation\n- **Multi-database compatibility** (PostgreSQL and MySQL)\n- **Security-first approach** with input validation and rate limiting\n- **Performance optimizations** with Redis caching and connection pooling\n\n### Code Standards\n- **TypeScript strict mode** with full type coverage\n- **JSONSchema7** for input validation (not class-validator)\n- **Conventional Commits** enforced by commitlint\n- **ESLint + Prettier** for code formatting\n- **Service Object pattern** for business logic\n- **RouterBroker pattern** for route handling with `dataValidate`\n\n### Architecture Patterns\n- **Multi-tenant isolation** at database and instance level\n- **Event-driven communication** with EventEmitter2\n- **Microservices integration** pattern for external services\n- **Connection pooling** and lifecycle management\n- **Caching strategy** with Redis primary and Node-cache fallback\n\n## Testing Approach\n\nCurrently, the project has minimal formal testing infrastructure:\n- **Manual testing** is the primary approach\n- **Integration testing** in development environment\n- **No unit test suite** currently implemented\n- Test files can be placed in `test/` directory as `*.test.ts`\n- Run `npm test` for watch mode development testing\n\n### Recommended Testing Strategy\n- Focus on **critical business logic** in services\n- **Mock external dependencies** (WhatsApp APIs, databases)\n- **Integration tests** for API endpoints\n- **Manual testing** for WhatsApp connection flows\n\n## Deployment Considerations\n\n- Docker support with `Dockerfile` and `docker-compose.yaml`\n- Graceful shutdown handling for connections\n- Health check endpoints for monitoring\n- Sentry integration for error tracking\n- Telemetry for usage analytics (non-sensitive data only)"},"files":{"AGENTS.md":"# Evolution API - AI Agent Guidelines\n\nThis document provides comprehensive guidelines for AI agents (Claude, GPT, Cursor, etc.) working with the Evolution API codebase.\n\n## Project Overview\n\n**Evolution API** is a production-ready, multi-tenant WhatsApp API platform built with Node.js, TypeScript, and Express.js. It supports multiple WhatsApp providers and extensive integrations with chatbots, CRM systems, and messaging platforms.\n\n## Project Structure & Module Organization\n\n### Core Directories\n- **`src/`** – TypeScript source code with modular architecture\n  - `api/controllers/` – HTTP route handlers (thin layer)\n  - `api/services/` – Business logic (core functionality)\n  - `api/routes/` – Express route definitions (RouterBroker pattern)\n  - `api/integrations/` – External service integrations\n    - `channel/` – WhatsApp providers (Baileys, Business API, Evolution)\n    - `chatbot/` – AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)\n    - `event/` – Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)\n    - `storage/` – File storage (S3, MinIO)\n  - `dto/` – Data Transfer Objects (simple classes, no decorators)\n  - `guards/` – Authentication/authorization middleware\n  - `types/` – TypeScript type definitions\n  - `repository/` – Data access layer (Prisma)\n- **`prisma/`** – Database schemas and migrations\n  - `postgresql-schema.prisma` / `mysql-schema.prisma` – Provider-specific schemas\n  - `postgresql-migrations/` / `mysql-migrations/` – Provider-specific migrations\n- **`config/`** – Environment and application configuration\n- **`utils/`** – Shared utilities and helper functions\n- **`validate/`** – JSONSchema7 validation schemas\n- **`exceptions/`** – Custom HTTP exception classes\n- **`cache/`** – Redis and local cache implementations\n\n### Build & Deployment\n- **`dist/`** – Build output (do not edit directly)\n- **`public/`** – Static assets and media files\n- **`Docker*`**, **`docker-compose*.yaml`** – Containerization and local development stack\n\n## Build, Test, and Development Commands\n\n### Development Workflow\n```bash\n# Development server with hot reload\nnpm run dev:server\n\n# Direct execution for testing\nnpm start\n\n# Production build and run\nnpm run build\nnpm run start:prod\n```\n\n### Code Quality\n```bash\n# Linting and formatting\nnpm run lint        # ESLint with auto-fix\nnpm run lint:check  # ESLint check only\n\n# Commit with conventional commits\nnpm run commit      # Interactive commit with Commitizen\n```\n\n### Database Management\n```bash\n# Set database provider first (CRITICAL)\nexport DATABASE_PROVIDER=postgresql  # or mysql\n\n# Generate Prisma client\nnpm run db:generate\n\n# Development migrations (with provider sync)\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n\n# Production deployment\nnpm run db:deploy      # Unix/Mac\nnpm run db:deploy:win  # Windows\n\n# Database tools\nnpm run db:studio      # Open Prisma Studio\n```\n\n### Docker Development\n```bash\n# Start local services (Redis, PostgreSQL, etc.)\ndocker-compose up -d\n\n# Full development stack\ndocker-compose -f docker-compose.dev.yaml up -d\n```\n\n## Coding Standards & Architecture Patterns\n\n### Code Style (Enforced by ESLint + Prettier)\n- **TypeScript strict mode** with full type coverage\n- **2-space indentation**, single quotes, trailing commas\n- **120-character line limit**\n- **Import order** via `simple-import-sort`\n- **File naming**: `feature.kind.ts` (e.g., `whatsapp.baileys.service.ts`)\n- **Naming conventions**:\n  - Classes: `PascalCase`\n  - Functions/variables: `camelCase`\n  - Constants: `UPPER_SNAKE_CASE`\n  - Files: `kebab-case.type.ts`\n\n### Architecture Patterns\n\n#### Service Layer Pattern\n```typescript\nexport class ExampleService {\n  constructor(private readonly waMonitor: WAMonitoringService) {}\n  \n  private readonly logger = new Logger('ExampleService');\n  \n  public async create(instance: InstanceDto, data: ExampleDto) {\n    // Business logic here\n    return { example: { ...instance, data } };\n  }\n  \n  public async find(instance: InstanceDto): Promise<ExampleDto | null> {\n    try {\n      const result = await this.waMonitor.waInstances[instance.instanceName].findData();\n      return result || null; // Return null on not found (Evolution pattern)\n    } catch (error) {\n      this.logger.error('Error finding data:', error);\n      return null; // Return null on error (Evolution pattern)\n    }\n  }\n}\n```\n\n#### Controller Pattern (Thin Layer)\n```typescript\nexport class ExampleController {\n  constructor(private readonly exampleService: ExampleService) {}\n  \n  public async createExample(instance: InstanceDto, data: ExampleDto) {\n    return this.exampleService.create(instance, data);\n  }\n}\n```\n\n#### RouterBroker Pattern\n```typescript\nexport class ExampleRouter extends RouterBroker {\n  constructor(...guards: any[]) {\n    super();\n    this.router.post(this.routerPath('create'), ...guards, async (req, res) => {\n      const response = await this.dataValidate<ExampleDto>({\n        request: req,\n        schema: exampleSchema, // JSONSchema7\n        ClassRef: ExampleDto,\n        execute: (instance, data) => controller.createExample(instance, data),\n      });\n      res.status(201).json(response);\n    });\n  }\n}\n```\n\n#### DTO Pattern (Simple Classes)\n```typescript\n// CORRECT - Evolution API pattern (no decorators)\nexport class ExampleDto {\n  name: string;\n  description?: string;\n  enabled: boolean;\n}\n\n// INCORRECT - Don't use class-validator decorators\nexport class BadExampleDto {\n  @IsString() // ❌ Evolution API doesn't use decorators\n  name: string;\n}\n```\n\n#### Validation Pattern (JSONSchema7)\n```typescript\nimport { JSONSchema7 } from 'json-schema';\nimport { v4 } from 'uuid';\n\nexport const exampleSchema: JSONSchema7 = {\n  $id: v4(),\n  type: 'object',\n  properties: {\n    name: { type: 'string' },\n    description: { type: 'string' },\n    enabled: { type: 'boolean' },\n  },\n  required: ['name', 'enabled'],\n};\n```\n\n## Multi-Tenant Architecture\n\n### Instance Isolation\n- **CRITICAL**: All operations must be scoped by `instanceName` or `instanceId`\n- **Database queries**: Always include `where: { instanceId: ... }`\n- **Authentication**: Validate instance ownership before operations\n- **Data isolation**: Complete separation between tenant instances\n\n### WhatsApp Instance Management\n```typescript\n// Access instance via WAMonitoringService\nconst waInstance = this.waMonitor.waInstances[instance.instanceName];\nif (!waInstance) {\n  throw new NotFoundException(`Instance ${instance.instanceName} not found`);\n}\n```\n\n## Database Patterns\n\n### Multi-Provider Support\n- **PostgreSQL**: Uses `@db.Integer`, `@db.JsonB`, `@default(now())`\n- **MySQL**: Uses `@db.Int`, `@db.Json`, `@default(now())`\n- **Environment**: Set `DATABASE_PROVIDER=postgresql` or `mysql`\n- **Migrations**: Provider-specific folders auto-selected\n\n### Prisma Repository Pattern\n```typescript\n// Always use PrismaRepository for database operations\nconst result = await this.prismaRepository.instance.findUnique({\n  where: { name: instanceName },\n});\n```\n\n## Integration Patterns\n\n### Channel Integration (WhatsApp Providers)\n- **Baileys**: WhatsApp Web with QR code authentication\n- **Business API**: Official Meta WhatsApp Business API  \n- **Evolution API**: Custom WhatsApp integration\n- **Pattern**: Extend base channel service classes\n\n### Chatbot Integration\n- **Base classes**: Extend `BaseChatbotService` and `BaseChatbotController`\n- **Trigger system**: Support keyword, regex, and advanced triggers\n- **Session management**: Handle conversation state per user\n- **Available integrations**: EvolutionBot, OpenAI, Dify, Typebot, Chatwoot, Flowise, N8N, EvoAI\n\n### Event Integration\n- **Internal events**: EventEmitter2 for application events\n- **External events**: WebSocket, RabbitMQ, SQS, NATS, Pusher\n- **Webhook delivery**: Reliable delivery with retry logic\n\n## Testing Guidelines\n\n### Current State\n- **No formal test suite** currently implemented\n- **Manual testing** is the primary approach\n- **Integration testing** in development environment\n\n### Testing Strategy\n```typescript\n// Place tests in test/ directory as *.test.ts\n// Run: npm test (watches test/all.test.ts)\n\ndescribe('ExampleService', () => {\n  it('should create example', async () => {\n    // Mock external dependencies\n    // Test business logic\n    // Assert expected behavior\n  });\n});\n```\n\n### Recommended Approach\n- Focus on **critical business logic** in services\n- **Mock external dependencies** (WhatsApp APIs, databases)\n- **Integration tests** for API endpoints\n- **Manual testing** for WhatsApp connection flows\n\n## Commit & Pull Request Guidelines\n\n### Conventional Commits (Enforced by commitlint)\n```bash\n# Use interactive commit tool\nnpm run commit\n\n# Commit format: type(scope): subject (max 100 chars)\n# Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert, security\n```\n\n### Examples\n- `feat(api): add WhatsApp message status endpoint`\n- `fix(baileys): resolve connection timeout issue`\n- `docs(readme): update installation instructions`\n- `refactor(service): extract common message validation logic`\n\n### Pull Request Requirements\n- **Clear description** of changes and motivation\n- **Linked issues** if applicable\n- **Migration impact** (specify database provider)\n- **Local testing steps** with screenshots/logs\n- **Breaking changes** clearly documented\n\n## Security & Configuration\n\n### Environment Setup\n```bash\n# Copy example environment file\ncp .env.example .env\n\n# NEVER commit secrets to version control\n# Set DATABASE_PROVIDER before database commands\nexport DATABASE_PROVIDER=postgresql  # or mysql\n```\n\n### Security Best Practices\n- **API key authentication** via `apikey` header\n- **Input validation** with JSONSchema7\n- **Rate limiting** on all endpoints\n- **Webhook signature validation**\n- **Instance-based access control**\n- **Secure defaults** for all configurations\n\n### Vulnerability Reporting\n- See `SECURITY.md` for security vulnerability reporting process\n- Contact: `contato@evolution-api.com`\n\n## Communication Standards\n\n### Language Requirements\n- **User communication**: Always respond in Portuguese (PT-BR)\n- **Code/comments**: English for technical documentation\n- **API responses**: English for consistency\n- **Error messages**: Portuguese for user-facing errors\n\n### Documentation Standards\n- **Inline comments**: Document complex business logic\n- **API documentation**: Document all public endpoints\n- **Integration guides**: Document new integration patterns\n- **Migration guides**: Document database schema changes\n\n## Performance & Scalability\n\n### Caching Strategy\n- **Redis primary**: Distributed caching for production\n- **Node-cache fallback**: Local caching when Redis unavailable\n- **TTL strategy**: Appropriate cache expiration per data type\n- **Cache invalidation**: Proper invalidation on data changes\n\n### Connection Management\n- **Database**: Prisma connection pooling\n- **WhatsApp**: One connection per instance with lifecycle management\n- **Redis**: Connection pooling and retry logic\n- **External APIs**: Rate limiting and retry with exponential backoff\n\n### Monitoring & Observability\n- **Structured logging**: Pino logger with correlation IDs\n- **Error tracking**: Comprehensive error scenarios\n- **Health checks**: Instance status and connection monitoring\n- **Telemetry**: Usage analytics (non-sensitive data only)\n\n","CLAUDE.md":"# CLAUDE.md\n\nThis file provides comprehensive guidance to Claude AI when working with the Evolution API codebase.\n\n## Project Overview\n\n**Evolution API** is a powerful, production-ready REST API for WhatsApp communication that supports multiple WhatsApp providers:\n- **Baileys** (WhatsApp Web) - Open-source WhatsApp Web client\n- **Meta Business API** - Official WhatsApp Business API\n- **Evolution API** - Custom WhatsApp integration\n\nBuilt with **Node.js 20+**, **TypeScript 5+**, and **Express.js**, it provides extensive integrations with chatbots, CRM systems, and messaging platforms in a **multi-tenant architecture**.\n\n## Common Development Commands\n\n### Build and Run\n```bash\n# Development\nnpm run dev:server    # Run in development with hot reload (tsx watch)\n\n# Production\nnpm run build        # TypeScript check + tsup build\nnpm run start:prod   # Run production build\n\n# Direct execution\nnpm start           # Run with tsx\n```\n\n### Code Quality\n```bash\nnpm run lint        # ESLint with auto-fix\nnpm run lint:check  # ESLint check only\nnpm run commit      # Interactive commit with commitizen\n```\n\n### Database Management\n```bash\n# Set database provider first\nexport DATABASE_PROVIDER=postgresql  # or mysql\n\n# Generate Prisma client (automatically uses DATABASE_PROVIDER env)\nnpm run db:generate\n\n# Deploy migrations (production)\nnpm run db:deploy      # Unix/Mac\nnpm run db:deploy:win  # Windows\n\n# Development migrations (with sync to provider folder)\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n\n# Open Prisma Studio\nnpm run db:studio\n\n# Development migrations\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n```\n\n### Testing\n```bash\nnpm test    # Run tests with watch mode\n```\n\n## Architecture Overview\n\n### Core Structure\n- **Multi-tenant SaaS**: Complete instance isolation with per-tenant authentication\n- **Multi-provider database**: PostgreSQL and MySQL via Prisma ORM with provider-specific schemas and migrations\n- **WhatsApp integrations**: Baileys, Meta Business API, and Evolution API with unified interface\n- **Event-driven architecture**: EventEmitter2 for internal events + WebSocket, RabbitMQ, SQS, NATS, Pusher for external events\n- **Microservices pattern**: Modular integrations for chatbots, storage, and external services\n\n### Directory Layout\n```\nsrc/\n├── api/\n│   ├── controllers/     # HTTP route handlers (thin layer)\n│   ├── services/        # Business logic (core functionality)\n│   ├── repository/      # Data access layer (Prisma)\n│   ├── dto/            # Data Transfer Objects (simple classes)\n│   ├── guards/         # Authentication/authorization middleware\n│   ├── integrations/   # External service integrations\n│   │   ├── channel/    # WhatsApp providers (Baileys, Business API, Evolution)\n│   │   ├── chatbot/    # AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)\n│   │   ├── event/      # Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)\n│   │   └── storage/    # File storage (S3, MinIO)\n│   ├── routes/         # Express route definitions (RouterBroker pattern)\n│   └── types/          # TypeScript type definitions\n├── config/             # Environment and app configuration\n├── cache/             # Redis and local cache implementations\n├── exceptions/        # Custom HTTP exception classes\n├── utils/            # Shared utilities and helpers\n└── validate/         # JSONSchema7 validation schemas\n```\n\n### Key Integration Points\n\n**Channel Integrations** (`src/api/integrations/channel/`):\n- **Baileys**: WhatsApp Web client with QR code authentication\n- **Business API**: Official Meta WhatsApp Business API\n- **Evolution API**: Custom WhatsApp integration\n- Connection lifecycle management per instance with automatic reconnection\n\n**Chatbot Integrations** (`src/api/integrations/chatbot/`):\n- **EvolutionBot**: Native chatbot with trigger system\n- **Chatwoot**: Customer service platform integration\n- **Typebot**: Visual chatbot flow builder\n- **OpenAI**: AI capabilities including GPT and Whisper (audio transcription)\n- **Dify**: AI agent workflow platform\n- **Flowise**: LangChain visual builder\n- **N8N**: Workflow automation platform\n- **EvoAI**: Custom AI integration\n\n**Event Integrations** (`src/api/integrations/event/`):\n- **WebSocket**: Real-time Socket.io connections\n- **RabbitMQ**: Message queue for async processing\n- **Amazon SQS**: Cloud-based message queuing\n- **NATS**: High-performance messaging system\n- **Pusher**: Real-time push notifications\n\n**Storage Integrations** (`src/api/integrations/storage/`):\n- **AWS S3**: Cloud object storage\n- **MinIO**: Self-hosted S3-compatible storage\n- Media file management and URL generation\n\n### Database Schema Management\n- Separate schema files: `postgresql-schema.prisma` and `mysql-schema.prisma`\n- Environment variable `DATABASE_PROVIDER` determines active database\n- Migration folders are provider-specific and auto-selected during deployment\n\n### Authentication & Security\n- **API key-based authentication** via `apikey` header (global or per-instance)\n- **Instance-specific tokens** for WhatsApp connection authentication\n- **Guards system** for route protection and authorization\n- **Input validation** using JSONSchema7 with RouterBroker `dataValidate`\n- **Rate limiting** and security middleware\n- **Webhook signature validation** for external integrations\n\n## Important Implementation Details\n\n### WhatsApp Instance Management\n- Each WhatsApp connection is an \"instance\" with unique name\n- Instance data stored in database with connection state\n- Session persistence in database or file system (configurable)\n- Automatic reconnection handling with exponential backoff\n\n### Message Queue Architecture\n- Supports RabbitMQ, Amazon SQS, and WebSocket for events\n- Event types: message.received, message.sent, connection.update, etc.\n- Configurable per instance which events to send\n\n### Media Handling\n- Local storage or S3/Minio for media files\n- Automatic media download from WhatsApp\n- Media URL generation for external access\n- Support for audio transcription via OpenAI\n\n### Multi-tenancy Support\n- Instance isolation at database level\n- Separate webhook configurations per instance\n- Independent integration settings per instance\n\n## Environment Configuration\n\nKey environment variables are defined in `.env.example`. The system uses a strongly-typed configuration system via `src/config/env.config.ts`.\n\nCritical configurations:\n- `DATABASE_PROVIDER`: postgresql or mysql\n- `DATABASE_CONNECTION_URI`: Database connection string\n- `AUTHENTICATION_API_KEY`: Global API authentication\n- `REDIS_ENABLED`: Enable Redis cache\n- `RABBITMQ_ENABLED`/`SQS_ENABLED`: Message queue options\n\n## Development Guidelines\n\nThe project follows comprehensive development standards defined in `.cursor/rules/`:\n\n### Core Principles\n- **Always respond in Portuguese (PT-BR)** for user communication\n- **Follow established architecture patterns** (Service Layer, RouterBroker, etc.)\n- **Robust error handling** with retry logic and graceful degradation\n- **Multi-database compatibility** (PostgreSQL and MySQL)\n- **Security-first approach** with input validation and rate limiting\n- **Performance optimizations** with Redis caching and connection pooling\n\n### Code Standards\n- **TypeScript strict mode** with full type coverage\n- **JSONSchema7** for input validation (not class-validator)\n- **Conventional Commits** enforced by commitlint\n- **ESLint + Prettier** for code formatting\n- **Service Object pattern** for business logic\n- **RouterBroker pattern** for route handling with `dataValidate`\n\n### Architecture Patterns\n- **Multi-tenant isolation** at database and instance level\n- **Event-driven communication** with EventEmitter2\n- **Microservices integration** pattern for external services\n- **Connection pooling** and lifecycle management\n- **Caching strategy** with Redis primary and Node-cache fallback\n\n## Testing Approach\n\nCurrently, the project has minimal formal testing infrastructure:\n- **Manual testing** is the primary approach\n- **Integration testing** in development environment\n- **No unit test suite** currently implemented\n- Test files can be placed in `test/` directory as `*.test.ts`\n- Run `npm test` for watch mode development testing\n\n### Recommended Testing Strategy\n- Focus on **critical business logic** in services\n- **Mock external dependencies** (WhatsApp APIs, databases)\n- **Integration tests** for API endpoints\n- **Manual testing** for WhatsApp connection flows\n\n## Deployment Considerations\n\n- Docker support with `Dockerfile` and `docker-compose.yaml`\n- Graceful shutdown handling for connections\n- Health check endpoints for monitoring\n- Sentry integration for error tracking\n- Telemetry for usage analytics (non-sensitive data only)"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","title":"AGENTS.md","content":"# Evolution API - AI Agent Guidelines\n\nThis document provides comprehensive guidelines for AI agents (Claude, GPT, Cursor, etc.) working with the Evolution API codebase.\n\n## Project Overview\n\n**Evolution API** is a production-ready, multi-tenant WhatsApp API platform built with Node.js, TypeScript, and Express.js. It supports multiple WhatsApp providers and extensive integrations with chatbots, CRM systems, and messaging platforms.\n\n## Project Structure & Module Organization\n\n### Core Directories\n- **`src/`** – TypeScript source code with modular architecture\n  - `api/controllers/` – HTTP route handlers (thin layer)\n  - `api/services/` – Business logic (core functionality)\n  - `api/routes/` – Express route definitions (RouterBroker pattern)\n  - `api/integrations/` – External service integrations\n    - `channel/` – WhatsApp providers (Baileys, Business API, Evolution)\n    - `chatbot/` – AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)\n    - `event/` – Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)\n    - `storage/` – File storage (S3, MinIO)\n  - `dto/` – Data Transfer Objects (simple classes, no decorators)\n  - `guards/` – Authentication/authorization middleware\n  - `types/` – TypeScript type definitions\n  - `repository/` – Data access layer (Prisma)\n- **`prisma/`** – Database schemas and migrations\n  - `postgresql-schema.prisma` / `mysql-schema.prisma` – Provider-specific schemas\n  - `postgresql-migrations/` / `mysql-migrations/` – Provider-specific migrations\n- **`config/`** – Environment and application configuration\n- **`utils/`** – Shared utilities and helper functions\n- **`validate/`** – JSONSchema7 validation schemas\n- **`exceptions/`** – Custom HTTP exception classes\n- **`cache/`** – Redis and local cache implementations\n\n### Build & Deployment\n- **`dist/`** – Build output (do not edit directly)\n- **`public/`** – Static assets and media files\n- **`Docker*`**, **`docker-compose*.yaml`** – Containerization and local development stack\n\n## Build, Test, and Development Commands\n\n### Development Workflow\n```bash\n# Development server with hot reload\nnpm run dev:server\n\n# Direct execution for testing\nnpm start\n\n# Production build and run\nnpm run build\nnpm run start:prod\n```\n\n### Code Quality\n```bash\n# Linting and formatting\nnpm run lint        # ESLint with auto-fix\nnpm run lint:check  # ESLint check only\n\n# Commit with conventional commits\nnpm run commit      # Interactive commit with Commitizen\n```\n\n### Database Management\n```bash\n# Set database provider first (CRITICAL)\nexport DATABASE_PROVIDER=postgresql  # or mysql\n\n# Generate Prisma client\nnpm run db:generate\n\n# Development migrations (with provider sync)\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n\n# Production deployment\nnpm run db:deploy      # Unix/Mac\nnpm run db:deploy:win  # Windows\n\n# Database tools\nnpm run db:studio      # Open Prisma Studio\n```\n\n### Docker Development\n```bash\n# Start local services (Redis, PostgreSQL, etc.)\ndocker-compose up -d\n\n# Full development stack\ndocker-compose -f docker-compose.dev.yaml up -d\n```\n\n## Coding Standards & Architecture Patterns\n\n### Code Style (Enforced by ESLint + Prettier)\n- **TypeScript strict mode** with full type coverage\n- **2-space indentation**, single quotes, trailing commas\n- **120-character line limit**\n- **Import order** via `simple-import-sort`\n- **File naming**: `feature.kind.ts` (e.g., `whatsapp.baileys.service.ts`)\n- **Naming conventions**:\n  - Classes: `PascalCase`\n  - Functions/variables: `camelCase`\n  - Constants: `UPPER_SNAKE_CASE`\n  - Files: `kebab-case.type.ts`\n\n### Architecture Patterns\n\n#### Service Layer Pattern\n```typescript\nexport class ExampleService {\n  constructor(private readonly waMonitor: WAMonitoringService) {}\n  \n  private readonly logger = new Logger('ExampleService');\n  \n  public async create(instance: InstanceDto, data: ExampleDto) {\n    // Business logic here\n    return { example: { ...instance, data } };\n  }\n  \n  public async find(instance: InstanceDto): Promise<ExampleDto | null> {\n    try {\n      const result = await this.waMonitor.waInstances[instance.instanceName].findData();\n      return result || null; // Return null on not found (Evolution pattern)\n    } catch (error) {\n      this.logger.error('Error finding data:', error);\n      return null; // Return null on error (Evolution pattern)\n    }\n  }\n}\n```\n\n#### Controller Pattern (Thin Layer)\n```typescript\nexport class ExampleController {\n  constructor(private readonly exampleService: ExampleService) {}\n  \n  public async createExample(instance: InstanceDto, data: ExampleDto) {\n    return this.exampleService.create(instance, data);\n  }\n}\n```\n\n#### RouterBroker Pattern\n```typescript\nexport class ExampleRouter extends RouterBroker {\n  constructor(...guards: any[]) {\n    super();\n    this.router.post(this.routerPath('create'), ...guards, async (req, res) => {\n      const response = await this.dataValidate<ExampleDto>({\n        request: req,\n        schema: exampleSchema, // JSONSchema7\n        ClassRef: ExampleDto,\n        execute: (instance, data) => controller.createExample(instance, data),\n      });\n      res.status(201).json(response);\n    });\n  }\n}\n```\n\n#### DTO Pattern (Simple Classes)\n```typescript\n// CORRECT - Evolution API pattern (no decorators)\nexport class ExampleDto {\n  name: string;\n  description?: string;\n  enabled: boolean;\n}\n\n// INCORRECT - Don't use class-validator decorators\nexport class BadExampleDto {\n  @IsString() // ❌ Evolution API doesn't use decorators\n  name: string;\n}\n```\n\n#### Validation Pattern (JSONSchema7)\n```typescript\nimport { JSONSchema7 } from 'json-schema';\nimport { v4 } from 'uuid';\n\nexport const exampleSchema: JSONSchema7 = {\n  $id: v4(),\n  type: 'object',\n  properties: {\n    name: { type: 'string' },\n    description: { type: 'string' },\n    enabled: { type: 'boolean' },\n  },\n  required: ['name', 'enabled'],\n};\n```\n\n## Multi-Tenant Architecture\n\n### Instance Isolation\n- **CRITICAL**: All operations must be scoped by `instanceName` or `instanceId`\n- **Database queries**: Always include `where: { instanceId: ... }`\n- **Authentication**: Validate instance ownership before operations\n- **Data isolation**: Complete separation between tenant instances\n\n### WhatsApp Instance Management\n```typescript\n// Access instance via WAMonitoringService\nconst waInstance = this.waMonitor.waInstances[instance.instanceName];\nif (!waInstance) {\n  throw new NotFoundException(`Instance ${instance.instanceName} not found`);\n}\n```\n\n## Database Patterns\n\n### Multi-Provider Support\n- **PostgreSQL**: Uses `@db.Integer`, `@db.JsonB`, `@default(now())`\n- **MySQL**: Uses `@db.Int`, `@db.Json`, `@default(now())`\n- **Environment**: Set `DATABASE_PROVIDER=postgresql` or `mysql`\n- **Migrations**: Provider-specific folders auto-selected\n\n### Prisma Repository Pattern\n```typescript\n// Always use PrismaRepository for database operations\nconst result = await this.prismaRepository.instance.findUnique({\n  where: { name: instanceName },\n});\n```\n\n## Integration Patterns\n\n### Channel Integration (WhatsApp Providers)\n- **Baileys**: WhatsApp Web with QR code authentication\n- **Business API**: Official Meta WhatsApp Business API  \n- **Evolution API**: Custom WhatsApp integration\n- **Pattern**: Extend base channel service classes\n\n### Chatbot Integration\n- **Base classes**: Extend `BaseChatbotService` and `BaseChatbotController`\n- **Trigger system**: Support keyword, regex, and advanced triggers\n- **Session management**: Handle conversation state per user\n- **Available integrations**: EvolutionBot, OpenAI, Dify, Typebot, Chatwoot, Flowise, N8N, EvoAI\n\n### Event Integration\n- **Internal events**: EventEmitter2 for application events\n- **External events**: WebSocket, RabbitMQ, SQS, NATS, Pusher\n- **Webhook delivery**: Reliable delivery with retry logic\n\n## Testing Guidelines\n\n### Current State\n- **No formal test suite** currently implemented\n- **Manual testing** is the primary approach\n- **Integration testing** in development environment\n\n### Testing Strategy\n```typescript\n// Place tests in test/ directory as *.test.ts\n// Run: npm test (watches test/all.test.ts)\n\ndescribe('ExampleService', () => {\n  it('should create example', async () => {\n    // Mock external dependencies\n    // Test business logic\n    // Assert expected behavior\n  });\n});\n```\n\n### Recommended Approach\n- Focus on **critical business logic** in services\n- **Mock external dependencies** (WhatsApp APIs, databases)\n- **Integration tests** for API endpoints\n- **Manual testing** for WhatsApp connection flows\n\n## Commit & Pull Request Guidelines\n\n### Conventional Commits (Enforced by commitlint)\n```bash\n# Use interactive commit tool\nnpm run commit\n\n# Commit format: type(scope): subject (max 100 chars)\n# Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert, security\n```\n\n### Examples\n- `feat(api): add WhatsApp message status endpoint`\n- `fix(baileys): resolve connection timeout issue`\n- `docs(readme): update installation instructions`\n- `refactor(service): extract common message validation logic`\n\n### Pull Request Requirements\n- **Clear description** of changes and motivation\n- **Linked issues** if applicable\n- **Migration impact** (specify database provider)\n- **Local testing steps** with screenshots/logs\n- **Breaking changes** clearly documented\n\n## Security & Configuration\n\n### Environment Setup\n```bash\n# Copy example environment file\ncp .env.example .env\n\n# NEVER commit secrets to version control\n# Set DATABASE_PROVIDER before database commands\nexport DATABASE_PROVIDER=postgresql  # or mysql\n```\n\n### Security Best Practices\n- **API key authentication** via `apikey` header\n- **Input validation** with JSONSchema7\n- **Rate limiting** on all endpoints\n- **Webhook signature validation**\n- **Instance-based access control**\n- **Secure defaults** for all configurations\n\n### Vulnerability Reporting\n- See `SECURITY.md` for security vulnerability reporting process\n- Contact: `contato@evolution-api.com`\n\n## Communication Standards\n\n### Language Requirements\n- **User communication**: Always respond in Portuguese (PT-BR)\n- **Code/comments**: English for technical documentation\n- **API responses**: English for consistency\n- **Error messages**: Portuguese for user-facing errors\n\n### Documentation Standards\n- **Inline comments**: Document complex business logic\n- **API documentation**: Document all public endpoints\n- **Integration guides**: Document new integration patterns\n- **Migration guides**: Document database schema changes\n\n## Performance & Scalability\n\n### Caching Strategy\n- **Redis primary**: Distributed caching for production\n- **Node-cache fallback**: Local caching when Redis unavailable\n- **TTL strategy**: Appropriate cache expiration per data type\n- **Cache invalidation**: Proper invalidation on data changes\n\n### Connection Management\n- **Database**: Prisma connection pooling\n- **WhatsApp**: One connection per instance with lifecycle management\n- **Redis**: Connection pooling and retry logic\n- **External APIs**: Rate limiting and retry with exponential backoff\n\n### Monitoring & Observability\n- **Structured logging**: Pino logger with correlation IDs\n- **Error tracking**: Comprehensive error scenarios\n- **Health checks**: Instance status and connection monitoring\n- **Telemetry**: Usage analytics (non-sensitive data only)\n\n","category":"root","tokens":2836},{"name":"CLAUDE.md","path":"CLAUDE.md","title":"CLAUDE.md","content":"# CLAUDE.md\n\nThis file provides comprehensive guidance to Claude AI when working with the Evolution API codebase.\n\n## Project Overview\n\n**Evolution API** is a powerful, production-ready REST API for WhatsApp communication that supports multiple WhatsApp providers:\n- **Baileys** (WhatsApp Web) - Open-source WhatsApp Web client\n- **Meta Business API** - Official WhatsApp Business API\n- **Evolution API** - Custom WhatsApp integration\n\nBuilt with **Node.js 20+**, **TypeScript 5+**, and **Express.js**, it provides extensive integrations with chatbots, CRM systems, and messaging platforms in a **multi-tenant architecture**.\n\n## Common Development Commands\n\n### Build and Run\n```bash\n# Development\nnpm run dev:server    # Run in development with hot reload (tsx watch)\n\n# Production\nnpm run build        # TypeScript check + tsup build\nnpm run start:prod   # Run production build\n\n# Direct execution\nnpm start           # Run with tsx\n```\n\n### Code Quality\n```bash\nnpm run lint        # ESLint with auto-fix\nnpm run lint:check  # ESLint check only\nnpm run commit      # Interactive commit with commitizen\n```\n\n### Database Management\n```bash\n# Set database provider first\nexport DATABASE_PROVIDER=postgresql  # or mysql\n\n# Generate Prisma client (automatically uses DATABASE_PROVIDER env)\nnpm run db:generate\n\n# Deploy migrations (production)\nnpm run db:deploy      # Unix/Mac\nnpm run db:deploy:win  # Windows\n\n# Development migrations (with sync to provider folder)\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n\n# Open Prisma Studio\nnpm run db:studio\n\n# Development migrations\nnpm run db:migrate:dev      # Unix/Mac\nnpm run db:migrate:dev:win  # Windows\n```\n\n### Testing\n```bash\nnpm test    # Run tests with watch mode\n```\n\n## Architecture Overview\n\n### Core Structure\n- **Multi-tenant SaaS**: Complete instance isolation with per-tenant authentication\n- **Multi-provider database**: PostgreSQL and MySQL via Prisma ORM with provider-specific schemas and migrations\n- **WhatsApp integrations**: Baileys, Meta Business API, and Evolution API with unified interface\n- **Event-driven architecture**: EventEmitter2 for internal events + WebSocket, RabbitMQ, SQS, NATS, Pusher for external events\n- **Microservices pattern**: Modular integrations for chatbots, storage, and external services\n\n### Directory Layout\n```\nsrc/\n├── api/\n│   ├── controllers/     # HTTP route handlers (thin layer)\n│   ├── services/        # Business logic (core functionality)\n│   ├── repository/      # Data access layer (Prisma)\n│   ├── dto/            # Data Transfer Objects (simple classes)\n│   ├── guards/         # Authentication/authorization middleware\n│   ├── integrations/   # External service integrations\n│   │   ├── channel/    # WhatsApp providers (Baileys, Business API, Evolution)\n│   │   ├── chatbot/    # AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)\n│   │   ├── event/      # Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)\n│   │   └── storage/    # File storage (S3, MinIO)\n│   ├── routes/         # Express route definitions (RouterBroker pattern)\n│   └── types/          # TypeScript type definitions\n├── config/             # Environment and app configuration\n├── cache/             # Redis and local cache implementations\n├── exceptions/        # Custom HTTP exception classes\n├── utils/            # Shared utilities and helpers\n└── validate/         # JSONSchema7 validation schemas\n```\n\n### Key Integration Points\n\n**Channel Integrations** (`src/api/integrations/channel/`):\n- **Baileys**: WhatsApp Web client with QR code authentication\n- **Business API**: Official Meta WhatsApp Business API\n- **Evolution API**: Custom WhatsApp integration\n- Connection lifecycle management per instance with automatic reconnection\n\n**Chatbot Integrations** (`src/api/integrations/chatbot/`):\n- **EvolutionBot**: Native chatbot with trigger system\n- **Chatwoot**: Customer service platform integration\n- **Typebot**: Visual chatbot flow builder\n- **OpenAI**: AI capabilities including GPT and Whisper (audio transcription)\n- **Dify**: AI agent workflow platform\n- **Flowise**: LangChain visual builder\n- **N8N**: Workflow automation platform\n- **EvoAI**: Custom AI integration\n\n**Event Integrations** (`src/api/integrations/event/`):\n- **WebSocket**: Real-time Socket.io connections\n- **RabbitMQ**: Message queue for async processing\n- **Amazon SQS**: Cloud-based message queuing\n- **NATS**: High-performance messaging system\n- **Pusher**: Real-time push notifications\n\n**Storage Integrations** (`src/api/integrations/storage/`):\n- **AWS S3**: Cloud object storage\n- **MinIO**: Self-hosted S3-compatible storage\n- Media file management and URL generation\n\n### Database Schema Management\n- Separate schema files: `postgresql-schema.prisma` and `mysql-schema.prisma`\n- Environment variable `DATABASE_PROVIDER` determines active database\n- Migration folders are provider-specific and auto-selected during deployment\n\n### Authentication & Security\n- **API key-based authentication** via `apikey` header (global or per-instance)\n- **Instance-specific tokens** for WhatsApp connection authentication\n- **Guards system** for route protection and authorization\n- **Input validation** using JSONSchema7 with RouterBroker `dataValidate`\n- **Rate limiting** and security middleware\n- **Webhook signature validation** for external integrations\n\n## Important Implementation Details\n\n### WhatsApp Instance Management\n- Each WhatsApp connection is an \"instance\" with unique name\n- Instance data stored in database with connection state\n- Session persistence in database or file system (configurable)\n- Automatic reconnection handling with exponential backoff\n\n### Message Queue Architecture\n- Supports RabbitMQ, Amazon SQS, and WebSocket for events\n- Event types: message.received, message.sent, connection.update, etc.\n- Configurable per instance which events to send\n\n### Media Handling\n- Local storage or S3/Minio for media files\n- Automatic media download from WhatsApp\n- Media URL generation for external access\n- Support for audio transcription via OpenAI\n\n### Multi-tenancy Support\n- Instance isolation at database level\n- Separate webhook configurations per instance\n- Independent integration settings per instance\n\n## Environment Configuration\n\nKey environment variables are defined in `.env.example`. The system uses a strongly-typed configuration system via `src/config/env.config.ts`.\n\nCritical configurations:\n- `DATABASE_PROVIDER`: postgresql or mysql\n- `DATABASE_CONNECTION_URI`: Database connection string\n- `AUTHENTICATION_API_KEY`: Global API authentication\n- `REDIS_ENABLED`: Enable Redis cache\n- `RABBITMQ_ENABLED`/`SQS_ENABLED`: Message queue options\n\n## Development Guidelines\n\nThe project follows comprehensive development standards defined in `.cursor/rules/`:\n\n### Core Principles\n- **Always respond in Portuguese (PT-BR)** for user communication\n- **Follow established architecture patterns** (Service Layer, RouterBroker, etc.)\n- **Robust error handling** with retry logic and graceful degradation\n- **Multi-database compatibility** (PostgreSQL and MySQL)\n- **Security-first approach** with input validation and rate limiting\n- **Performance optimizations** with Redis caching and connection pooling\n\n### Code Standards\n- **TypeScript strict mode** with full type coverage\n- **JSONSchema7** for input validation (not class-validator)\n- **Conventional Commits** enforced by commitlint\n- **ESLint + Prettier** for code formatting\n- **Service Object pattern** for business logic\n- **RouterBroker pattern** for route handling with `dataValidate`\n\n### Architecture Patterns\n- **Multi-tenant isolation** at database and instance level\n- **Event-driven communication** with EventEmitter2\n- **Microservices integration** pattern for external services\n- **Connection pooling** and lifecycle management\n- **Caching strategy** with Redis primary and Node-cache fallback\n\n## Testing Approach\n\nCurrently, the project has minimal formal testing infrastructure:\n- **Manual testing** is the primary approach\n- **Integration testing** in development environment\n- **No unit test suite** currently implemented\n- Test files can be placed in `test/` directory as `*.test.ts`\n- Run `npm test` for watch mode development testing\n\n### Recommended Testing Strategy\n- Focus on **critical business logic** in services\n- **Mock external dependencies** (WhatsApp APIs, databases)\n- **Integration tests** for API endpoints\n- **Manual testing** for WhatsApp connection flows\n\n## Deployment Considerations\n\n- Docker support with `Dockerfile` and `docker-compose.yaml`\n- Graceful shutdown handling for connections\n- Health check endpoints for monitoring\n- Sentry integration for error tracking\n- Telemetry for usage analytics (non-sensitive data only)","category":"root","tokens":2192}]}